What is the purpose and significance of “CDK bootstrap”?
I am a DevOps engineer and I am currently working on a cloud-native project using the AWS CDK. My team is preparing to deploy infrastructure by using the CDK and one of my colleagues is unfamiliar with the “cdk bootstrap” command. How can I explain the purpose and significance of the “cdk bootstrap” to my colleagues?
In the context of AWS, the “cdk bootstrap” is a very crucial step to prepare your AWS account and environment for deploying and managing infrastructure by using the AWS cdk. It would perform several essential tasks:-
Creating CDK toolkit stack
It can create a special AWS cloud formation stack called the CDK toolkit stack in your particular AWS account. This stack can contain resources required for Cdk deployment such as an S3 bucket.
Deploying assets bucket
The command would set up an S3 bucket in your account to store assets such as synthesized cloud formation templates.
Set up permission
It can configure the necessary IAM permission for the CDK toolkit stack and resources to interact with other AWS services securely.
Here is an example given of how you can use the ‘CDK bootstrap' command in the AWS CDK CLI:-
# Create a new directory for your CDK project and navigate into it
Mkdir my-cdk-project
Cd my-cdk-project
# Initialize a new CDK project and install necessary dependencies
Cdk init app –language=typescript
Npm install @aws-cdk/aws-s3 @aws-cdk/aws-lambda @aws-cdk/aws-iam
# Open the generated lib/my-cdk-project-stack.ts file and replace its contents with the following code
Cat << EOF> lib/my-cdk-project-stack.ts
Import * as cdk from ‘@aws-cdk/core’;
Import * as s3 from ‘@aws-cdk/aws-s3’;
Import * as lambda from ‘@aws-cdk/aws-lambda’;
Import * as iam from ‘@aws-cdk/aws-iam’;
Export class MyCdkProjectStack extends cdk.Stack {
Constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
Super(scope, id, props);
// Create an S3 bucket
Const bucket = new s3.Bucket(this, ‘MyBucket’, {
Versioned: true,
removalPolicy: cdk.RemovalPolicy.DESTROY, // For demonstration purposes
});
// Create a Lambda function
Const lambdaFn = new lambda.Function(this, ‘MyLambda’, {
Runtime: lambda.Runtime.NODEJS_14_X,
Handler: ‘index.handler’,
Code: lambda.Code.fromInline(`exports.handler = async (event) => { return “Hello from Lambda!”; }`),
});
// Grant Lambda permissions to access the S3 bucket
Bucket.grantReadWrite(lambdaFn);
// Output the bucket name and Lambda function ARN
New cdk.CfnOutput(this, ‘BucketName’, { value: bucket.bucketName });
New cdk.CfnOutput(this, ‘LambdaArn’, { value: lambdaFn.functionArn });
}
}
Const app = new cdk.App();
New MyCdkProjectStack(app, ‘MyCdkProjectStack’);
EOF
# Bootstrap your AWS environment and deploy the CDK stack in one command
Cdk bootstrap aws://account-id/region && cdk deploy
Here is the example given of AWS CDK typescript coding and the “cdk bootstrap” command to deploy a simple AWS infrastructure with an S3 bucket and a lambda function:-