AWS CDK is a SDK from AWS with the sole purpose of making it fun and easy to define cloud infrastructure in your favourite programming language and deploy it using AWS CloudFormation
.
In this article, we will start from the very basics of cdk, starting from bootstrapping cdk toolkit and why it is essential before we deploy our stack and I will try to summarise my understanding in this.
In order to start using cdk, an aws account would be required.
And it is always recommend to create a new IAM user with programmatic access having suitable policies attached.
Usually as beginner we can attach AdministratorAccess
Configure your credentials โ
Then you can configure the aws credentials so that we will be able to authenticate our sdk to aws.
aws configure
AWS Access Key ID [None]: <type key ID here>
AWS Secret Access Key [None]: <type access key>
Default region name [None]: <choose region (e.g. "us-east-1", "eu-west-1")>
Default output format [None]: <leave blank>
Based on your choice of programming language you can setup the necessary runtime.
Here I will be using nodejs, so I will be checking for the runtime.
node --version
You can then choose an IDE for editing the project. I use vscode here.
Installing the cdk packages ๐
npm install -g aws-cdk
cdk --version
2.0.0 (build 4b6ce31)
Then we can choose our init project template here, i use typescript
mkdir cdk-workshop && cd cdk-workshop
cdk init sample-app --language typescript
Besides that there is other templates as well try to execute cdk init --list
to find them.
Available templates:
* app: Template for a CDK Application
โโ cdk init app --language=[csharp|fsharp|go|java|javascript|python|typescript]
* lib: Template for a CDK Construct Library
โโ cdk init lib --language=typescript
* sample-app: Example CDK Application with some constructs
โโ cdk init sample-app --language=[csharp|fsharp|go|java|javascript|python|typescript]
Once it is download, you can switch the current directory
cd cdk-workshop
npm run watch
this will start the building of the typescript code and generete the compiled code to be used by cdk cmdlet to further process/publish to aws.
Folder structure for the sample-app template ๐
You can expect two important file as shown below.
bin/cdk-workshop.ts
#!/usr/bin/env node
import * as cdk from 'aws-cdk-lib';
import { CdkWorkshopStack } from '../lib/cdk-workshop-stack';
const app = new cdk.App();
new CdkWorkshopStack(app, 'CdkWorkshopStack');
In short the above code instantiates the CdkWorkshopStack
class from the lib/cdk-workshop-stack.ts below.
lib/cdk-workshop-stack.ts
import { Duration, Stack, StackProps } from 'aws-cdk-lib';
import * as sns from 'aws-cdk-lib/aws-sns';
import * as subs from 'aws-cdk-lib/aws-sns-subscriptions';
import * as sqs from 'aws-cdk-lib/aws-sqs';
import { Construct } from 'constructs';
export class CdkWorkshopStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
const queue = new sqs.Queue(this, 'CdkWorkshopQueue', {
visibilityTimeout: Duration.seconds(300)
});
const topic = new sns.Topic(this, 'CdkWorkshopTopic');
topic.addSubscription(new subs.SqsSubscription(queue));
}
}
Synthesize into CloudFormation template ๐
When CDK apps are executed, they produce (or โsynthesizeโ, in CDK parlance) an AWS CloudFormation template for each stack defined in your application.
cdk synth
This command requires that the you to be in the same directory as your cdk.json file.
# With stackName
$ cdk synth stackName
# Without stackName
$ cdk synth
# Without including dependencies
$ cdk synth stackName --exclusively
# Without any output for cloudformation template generated
$ cdk synth stackName --quiet
Identifiying the difference between multiple deployments ๐ก
cdk diff
This command will help to identify the recent changes, from the last deployment. This help us identify what new resources or IAM changes, will happen when we deploy this stack again
$ cdk diff --app='node bin/main.js' stackName
//you may also specify a specific template document
$ cdk diff --app='node bin/main.js' stackName --template=template.yml
Bootstrapping an environment ๐ก
cdk bootstrap
When you run the above command in a cdk project, cdk deploys the CDK toolkit stack into an AWS environment.
The bootstrap command creates a CloudFormation stack in the environment/region passed on the command line. (one time per account/region.)
This stack is know as the cdk toolkit stack includes resources that are used in the toolkitโs operation. Normally, when we start the only resource in that stack is a S3 bucket that holds the file assets and the resulting CloudFormation template to deploy. Besides this IAM roles that grant permissions necessary to perform deployments.
Before starting you may also review and update the template for the toolkit.
cdk bootstrap --show-template > bootstrap-template.yaml
you can review the bootstrap-template.yaml
and update it as per your requirement.
Then you can deploy the toolkit stack with updates like
aws cloudformation create-stack \
--stack-name CDKToolkit \
--template-body file://bootstrap-template.yaml
The cdk bootstrap can be done in many way like the listed below examples.
cdk bootstrap --profile prod
cdk bootstrap aws://789012123456/us-east-1
cdk bootstrap 789012123456/us-east-1 789012123456/us-west-1
When one of the above commands are executed, you can see something like the below running.
โณ Bootstrapping environment aws://<accountid>/<regionid>...
An environment needs to be bootstrapped if any of the following apply.
An AWS CloudFormation template generated by the app exceeds 50 kilobytes.
An AWS CDK stack being deployed uses Assets.
Finally we can run cdk deploy to publish our stack ๐ฃ
Deploys a stack of your CDK app to its environment. During the deployment, the toolkit will output progress indications, similar to what can be observed in the AWS CloudFormation Console.
If the environment was never bootstrapped (using cdk bootstrap), only stacks that are not using assets and synthesize to a template that is under 51,200 bytes will successfully deploy.
Before creating a change set, cdk deploy will compare the template and tags of the currently deployed stack to the template and tags that are about to be deployed and will skip deployment if they are identical. Use --force to override this behaviour and always deploy the stack.
cdk deploy --app='node bin/main.js' MyStackName
Or simply if this is the only stack in project
cdk deploy
This can some time bring warnings which notifies and takes your consent when any IAM polices are created/updated
Specify an outputs file to write to by supplying the --outputs-file
parameter
cdk deploy --outputs-file outputs.json
the same can be mentioned in the cdk.json
{
"app": "npx ts-node bin/myproject.ts",
"context": {
"@aws-cdk/core:enableStackNameDuplicates": "true",
"aws-cdk:enableDiffNoFail": "true",
"@aws-cdk/core:stackRelativeExports": "true"
},
"outputsFile": "outputs.json"
}
This will produce a new file outputs.json
Deployment Progress ๐
stack deployment events are displayed as a progress bar with the events for the resource currently being deployed.
To request the complete history which includes all CloudFormation events
cdk deploy --progress events
this progress key can be specified in the project config (cdk.json) as well.
โ
CdkWorkshopStack
โจ Deployment time: 92.17s
Stack ARN:
arn:aws:cloudformation:ap-south-1:*****5707855*****:stack/CdkWorkshopStack/53b36980-9a54-11ec-a914-064065601e40
โจ Total time: 105.96s
Here CdkWorkshopStack
is the name of the stack we deployed, you can also find the associated arn related to this stack.
Then you can use your aws console to navigate to the cloud formation section, where you could find and manage your deployed stacks.
When you select a specific stack you can also find an option to choose the resources tab which show the resources created into the current aws account/region.
cdk list ls ๐
cdk list or cdk ls
Lists all stacks in the project folder cdk list
ec2-user:~/environment/cdk-workshop (master) $ cdk ls
CdkWorkshopStack
Lists all stacks in the app
cdk doctor ๐
Inspect the environment and produce information useful for troubleshooting
cdk doctor
ec2-user:~/environment/cdk-workshop (master) $ cdk doctor
โน๏ธ CDK Version: 2.12.0 (build c9786db)
โน๏ธ AWS environment variables:
- AWS_STS_REGIONAL_ENDPOINTS = regional
- AWS_NODEJS_CONNECTION_REUSE_ENABLED = 1
โน๏ธ No CDK environment variables
cdk destroy ๐ฃ
cdk destroy
Finally we can clear the stack, which we have provisioned, using the below command. This will destroy the given stack.
cdk destroy --app='node bin/main.js' stackName
or simply you may also use cdk destroy
References
You may also find the full list of commands and usage at the below github repository.
We have lots more to discuss find my next article in this series below.
Thanks for supporting! ๐
Would be really great if you like to โ Buy Me a Coffee, to help boost my efforts, also follow my posts in the platform of your choice listed below.
๐ Reposted at ๐ dev to @aravindvcyber