provisioning resources with cdk aws go
Install aws cdk is the first step we have to do.
npm install -g aws-cdk
Next create the directory
mkdir hello-cdk && cd hello-cdk
Initialize your target development language
cdk init app --language go
That will generate some codes for you and run command below to generate download the required packages.
go get
Use the following code and provide your account.
package main
import (
"github.com/aws/aws-cdk-go/awscdk/v2"
"github.com/aws/aws-cdk-go/awscdk/v2/awslambda"
"github.com/aws/constructs-go/constructs/v10"
"github.com/aws/jsii-runtime-go"
)
func main() {
defer jsii.Close()
app := awscdk.NewApp(nil)
NewHelloCdkStack(app, "HelloCdkStack", &HelloCdkStackProps{
awscdk.StackProps{
Env: env(),
},
})
app.Synth(nil)
}
func env() *awscdk.Environment {
return &awscdk.Environment{
Account: jsii.String(""),
Region: jsii.String("ap-southeast-2"),
}
}
type HelloCdkStackProps struct {
awscdk.StackProps
}
func NewHelloCdkStack(scope constructs.Construct, id string, props *HelloCdkStackProps) awscdk.Stack {
var sprops awscdk.StackProps
if props != nil {
sprops = props.StackProps
}
stack := awscdk.NewStack(scope, &id, &sprops)
// Define the Lambda function resource
myFunction := awslambda.NewFunction(stack, jsii.String("HelloWorldFunction"), &awslambda.FunctionProps{
Runtime: awslambda.Runtime_NODEJS_20_X(), // Provide any supported Node.js runtime
Handler: jsii.String("index.handler"),
Code: awslambda.Code_FromInline(jsii.String(`
exports.handler = async function(event) {
return {
statusCode: 200,
body: JSON.stringify('Hello World!'),
};
};
`)),
})
//fmt.Print("%s", myFunction)
myFunctionUrl := myFunction.AddFunctionUrl(&awslambda.FunctionUrlOptions{
AuthType: awslambda.FunctionUrlAuthType_NONE,
})
// Define a CloudFormation output for your URL
awscdk.NewCfnOutput(stack, jsii.String("myFunctionUrlOutput"), &awscdk.CfnOutputProps{
Value: myFunctionUrl.Url(),
})
return stack
}
Next run the following command to get your environment ready. It will create s3 and other IAM roles here.
cdk bootstrap
go build
To see what sort of stack you have just created, run the following command
cdk list
HelloCdkStack
Run the command below to validate and generate your cloudformation template.
cdk synth
Then to deploy, run cdk deploy
cdk deploy
If you run cdk diff - you can preview your changesets.
Comments