🚀 AWS CDK 101 🎡 setup and bootstrapping
Tags: aws, cdk, typescript, serverless
Published: 2022-03-03 07:07:30

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](https://res.cloudinary.com/dev-post/image/authenticated/s--U9P6Lv2h--/v1646286771/private/cdkbootstrap3.png)


## Configure your credentials  :snowman:

Then you can configure the aws credentials so that we will be able to authenticate our sdk to aws.

`aws configure`

```sh
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 :handbag:

`npm install -g aws-cdk`

```sh
cdk --version
2.0.0

```

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.

```sh
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 :file_folder:

You can expect two important file as shown below.

`bin/cdk-workshop.ts`



```typescript
#!/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`

```typescript
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 :blue_book:

 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.

```sh
# 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 :bulb:

`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

```sh
$ 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 :satellite:

`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

```sh
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.

![cdk bootstrap successful](https://res.cloudinary.com/dev-post/image/authenticated/s--UTGzEmmf--/v1646284046/private/cdkbootstrap1.png)

## Finally we can run cdk deploy to publish our stack :mega:

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`

```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 :chart_with_upwards_trend:

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.

![cdk stack successful](https://res.cloudinary.com/dev-post/image/authenticated/s--147HyzSN--/v1646286666/private/cdkbootstrap2.png
)

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](https://res.cloudinary.com/dev-post/image/authenticated/s--A05u4g5v--/v1646482470/private/cdkbootstrap4.png)

## cdk list  :ledger:

`cdk list` or `cdk ls`

Lists all stacks in the project folder `cdk list`

```sh
ec2-user:~/environment/cdk-workshop (master) $ cdk ls
CdkWorkshopStack
```

Lists all stacks in the app

## cdk doctor :green_book:

Inspect the environment and produce information useful for troubleshooting

 `cdk doctor`

 ```sh
 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 :bomb:

`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](https://dev.to/aravindvcyber/aws-cdk-101-lambda-cdk-watch-le9)

Would be really great if you like to [:coffee: Buy Me a Coffee](https://www.buymeacoffee.com/AravindVCyber),  to help boost my efforts. 

<a href='https://ko-fi.com/X8X0CITDJ' target='_blank'><img height='36' style='border:0px;height:36px;' src='https://cdn.ko-fi.com/cdn/kofi3.png?v=3' border='0' alt='Buy Me a Coffee at ko-fi.com' /></a>

<a href="https://www.buymeacoffee.com/AravindVCyber"><img src="https://img.buymeacoffee.com/button-api/?text=Buy me a coffee&emoji=&slug=AravindVCyber&button_colour=BD5FFF&font_colour=ffffff&font_family=Cookie&outline_colour=000000&coffee_colour=FFDD00" /></a>

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

:repeat: Original post at :link: [Dev Post](https://devpost.hashnode.dev/aws-cdk-101)

:repeat: reposted at :link: [dev to @aravindvcyber](https://dev.to/aravindvcyber/aws-cdk-101-4922)