Episode 2: Introduction to AWS CDK & CloudFormation

·

4 min read

AWS CDK is a cloud development kit, it is tool designed to write infrastructure as code. There is a book that highly recommend if you want to dive deep into infra as code.

CloudFormation is a AWS tool allowing you to deploy your infrastructure. AWS CDK will compile and create a CloudFormation stack that will then be deployed.

As this episode is part of the series, we will not be covering all the topics. Here are few resources that may help get started:

Before we start, please ensure you have aws cli, and npm cdk installed.

Lets run few commands to know which version we are running, such that the rest of tutorial will be a breeze to follow.

First validate the aws cli version using the below command:

aws --version

Output may look like:

aws-cli/2.1.16 Python/3.7.4 Darwin/20.6.0 exe/x86_64 prompt/off

Once the above version is validated, lets also check CDK version:

cdk doctor

Output may look like:

CDK Version: 1.122.0 (build ae09c16)
ℹ️ AWS environment variables:
  - AWS_STS_REGIONAL_ENDPOINTS = regional
  - AWS_NODEJS_CONNECTION_REUSE_ENABLED = 1
  - AWS_SDK_LOAD_CONFIG = 1
ℹ️ No CDK environment variables

The whole code is available is available on github.

Let's begin with creating the directory:

mkdir cdk-cloud-formation-appreciation-dashboard

Next, lets change directory

cd cdk-cloud-formation-appreciation-dashboard

To create a project, for this demo we are using typescript

cdk init app --language typescript

Once done, you should see the below output:

Applying project template app for typescript
# Welcome to your CDK TypeScript project!

This is a blank project for TypeScript development with CDK.

The `cdk.json` file tells the CDK Toolkit how to execute your app.

## Useful commands

 * `npm run build`   compile typescript to js
 * `npm run watch`   watch for changes and compile
 * `npm run test`    perform the jest unit tests
 * `cdk deploy`      deploy this stack to your default AWS account/region
 * `cdk diff`        compare deployed stack with current state
 * `cdk synth`       emits the synthesized CloudFormation template

Initializing a new git repository...
Executing npm install...
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
npm WARN deprecated sane@4.1.0: some dependency vulnerabilities fixed, support for node < 10 dropped, and newer ECMAScript syntax/features added
✅ All done!

Before we can start writing anything, we need to install all the node modules:

npm install

Once installed, lets understand the files structure a little. We will be only changing .ts under the /lib/ folder. Rest of the files are needed for the CDK to work, but none that we will be changing.

As we have done in Episode one, i.e. creating a DynamoDB and Lambda and allowing the Lambda to read data from DynamoDB.

Lets add a code that will create a table named Messages with partitionKey message

     const table = new dynamodb.Table(this, 'Messages', {
      partitionKey: { name: 'messsage', type: dynamodb.AttributeType.STRING },
      removalPolicy: cdk.RemovalPolicy.DESTROY
    });

Lets also perform an output of the table name. Please note the table name will not be just Messages it will be suffixed with random values to ensure uniqueness.

new cdk.CfnOutput(this, 'ddbTable', { value: table.tableName });

Once the table is created, lets build Lambda function:

    const readHandler = new lambda.Function(this, 'ReadLambda', {
      runtime: lambda.Runtime.PYTHON_3_8,
      handler: 'index.lambda_handler',
      code: lambda.Code.fromAsset(path.resolve(__dirname, 'read-lambda')),
      environment: {
        "TABLE": table.tableName
      }
    });

Now the handler need a access rights to scan Table, and we can simply provide the access by the below line:

    table.grantFullAccess(readHandler);

Here is the gist of the full code

Once done, its time for us to go back to the terminal (command prompt), and run few commands.

cdk synth

Synth is a command that will generate a Cloudformation template, if all okay, that means it is good to go for us go to next:

cdk bootstrap

It will be reading the credentials from the aws configure and set up the account. Once all done, we can run

cdk deploy

It will ask you to confirm the changes, it may look similar to below:

Screen Shot.png

Once done, It should deploy DynamoDB and ReadLambda Function in AWS.

Explore the Lambda in AWS Console, to check if the ReadLambda was created:

Screen Shot.png

Go to DynamoDB in AWS console to check if table Messages was created:

Screen Shot.png

Now, we can run

cdk destroy

It will destroy the stack i.e. all the resources associated with it. You can do cdk deploy and cdk destroy as many times you wish to do, and there is costing for the CDK itself but it will charge for the resources deployed as part of the stack.