DEV Community

Cover image for ๐Ÿš€ AWS CDK 101 ๐ŸŽก setup and bootstrapping
Aravind V
Aravind V

Posted on • Updated on • Originally published at devpost.hashnode.dev

๐Ÿš€ AWS CDK 101 ๐ŸŽก setup and bootstrapping

AWS CDK is a new 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

AdministratorAccess policy

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>

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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');

Enter fullscreen mode Exit fullscreen mode

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));
  }
}


Enter fullscreen mode Exit fullscreen mode

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

The below 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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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>...
Enter fullscreen mode Exit fullscreen mode

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.

cdk bootstrap successful

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 behavior 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"
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

cdk stack successful

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.

Resources tab

cdk list ๐Ÿ“’

cdk list or cdk ls

Lists all stacks in the project folder cdk list

ec2-user:~/environment/cdk-workshop (master) $ cdk ls
CdkWorkshopStack
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

https://github.com/aws/aws-cdk/blob/master/packages/aws-cdk/README.md

Thanks for supporting! ๐Ÿ™

We will add more connections to this bootstrapped stack and make it more usable in the upcoming articles, so do consider following and subscribing to my newsletter.

โญ We have our next article in serverless, do check out

aws-cdk-101-lambda-cdk-watch

Would be really great if you like to โ˜• Buy Me a Coffee, to help boost my efforts.

Buy Me a Coffee at ko-fi.com

Also follow my posts in the platform of your choice listed below.

๐Ÿ” Original post at ๐Ÿ”— Dev Post

๐Ÿ” reposted at ๐Ÿ”— dev to @aravindvcyber

Top comments (0)