AWS CDK, New way of managing Infra as a Code IaaC

AWS CDK

AWS CDK is an open source framework for creating and managing AWS resources. By using languages familiar to the developer such as TypeScript or Python, the Infrastructure as Code is described. In doing so, CDK synthesizes the code into AWS Cloudformation Templates and can optionally deploy them right away.

AWS CDK has been experiencing a steady increase in enthusiastic developers since 2019 and already has a strong and helpful community that is very active on Slack, for example. There is of course much more to say about AWS CDK and I recommend you explore it. Drop me a line if you have any questions.

Developers use the CDK framework in one of the supported programming languages to define reusable cloud components called constructs, which are composed together into stacks, forming a "CDK app".

They then use the AWS CDK CLI to interact with their CDK app. The CLI allows developers to synthesize artifacts such as AWS CloudFormation Templates, deploy stacks to development AWS accounts and "diff" against a deployed stack to understand the impact of a code change.

The AWS Construct Library includes a module for each AWS service with constructs that offer rich APIs that encapsulate the details of how to use AWS. The AWS Construct Library aims to reduce the complexity and glue-logic required when integrating various AWS services to achieve your goals on AWS.

Modules in the AWS Construct Library are designated Experimental while we build them; experimental modules may have breaking API changes in any release. After a module is designated Stable, it adheres to semantic versioning, and only major releases can have breaking changes. Each module's stability designation is available on its Overview page in the AWS CDK API Reference. For more information, see Versioning in the CDK Developer Guide.

At a glance

Install or update the AWS CDK CLI from npm (requires Node.js ≥ 14.15.0). We recommend using a version in Active LTS

$ npm i -g aws-cdk

(See Manual Installation for installing the CDK from a signed .zip file).

Initialize a project:

$ mkdir hello-cdk
$ cd hello-cdk
$ cdk init sample-app --language=typescript

This creates a sample project looking like this:

export class HelloCdkStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const queue = new sqs.Queue(this, 'HelloCdkQueue', {
      visibilityTimeout: cdk.Duration.seconds(300)
    });

    const topic = new sns.Topic(this, 'HelloCdkTopic');

    topic.addSubscription(new subs.SqsSubscription(queue));
  }
}

Deploy this to your account:

$ cdk deploy

Lets play with AWS-CDK

so what all we need is all these things below

  • AWS CLI (install Package)
  • AWS Account and User (AWS IAM)
  • Node.js (install using NVM)
  • IDE for your programming language (vscode)
  • AWS CDK Toolkit
  • Little bit Typescript knowledge !!

cdk init

  • Create project directory
  • Create an empty directory on your system:
mkdir qa && cd qa
cdk init

We will use cdk init to create a new TypeScript CDK project:

cdk init sample-app --language typescript

Output should look like this (you can safely ignore warnings about initialization of a git repository, this probably means you don’t have git installed, which is fine for this workshop):

Applying project template app for typescript
Initializing a new git repository...
Executing npm install...
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN tst@0.1.0 No repository field.
npm WARN tst@0.1.0 No license field.
➜  ~ nvm install v16.3.0
Downloading and installing node v16.3.0...
Downloading https://nodejs.org/dist/v16.3.0/node-v16.3.0-darwin-x64.tar.xz...
######################################################################## 100.0%
Computing checksum with shasum -a 256
Checksums matched!
Now using node v16.3.0 (npm v7.15.1)
➜  ~ nvm use v16.3.0    
Now using node v16.3.0 (npm v7.15.1)
➜  ~ npm install -g aws-cdk                   
added 2 packages, and audited 3 packages in 2s
➜  ~ cd
➜  ~ mkdir QA
➜  ~ cd QA
➜  QA cdk init sample-app --language typescript

Applying project template sample-app for typescript

Welcome to your CDK TypeScript project

You should explore the contents of this project. It demonstrates a CDK app with an instance of a stack (QaStack) which contains an Amazon SQS queue that is subscribed to an Amazon SNS topic.

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

Lets Check the code

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 QaStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    const queue = new sqs.Queue(this, 'QaQueue', {
      visibilityTimeout: Duration.seconds(300)
    });

    const topic = new sns.Topic(this, 'QaTopic');

    topic.addSubscription(new subs.SqsSubscription(queue));
  }
  • lib/qa-stack.ts is where your CDK application’s main stack is defined. This is the file we’ll be spending most of our time in.
  • bin/qa.ts is the entrypoint of the CDK application. It will load the stack defined in lib/qa-stack.ts.
  • package.json is your npm module manifest. It includes information like the name of your app, version, dependencies and build scripts like “watch” and “build” (package-lock.json is maintained by npm)
  • cdk.json tells the toolkit how to run your app. In our case it will be "npx ts-node bin/qa.ts"
  • tsconfig.json your project’s typescript configuration
  • .gitignore and .npmignore tell git and npm which files to include/exclude from source control and when publishing this module to the package manager.
  • node_modules is maintained by npm and includes all your project’s dependencies.
  • Your app’s entry point

Let’s have a quick look at bin/qa.ts:

#!/usr/bin/env node
import * as cdk from 'aws-cdk-lib';
import { CdkQAStack } from '../lib/qa-stack';

const app = new cdk.App();
new CdkWorkshopStack(app, 'CdkQAStack');

This code loads and instantiates the CdkWorkshopStack class from the lib/qa-stack.ts file. We won’t need to look at this file anymore.

The main stack Open up lib/qa-stack.ts. This is where the meat of our application is:

import * as cdk 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';

export class CdkQAStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const queue = new sqs.Queue(this, 'CdkWorkshopQueue', {
      visibilityTimeout: cdk.Duration.seconds(300)
    });

    const topic = new sns.Topic(this, 'CdkWorkshopTopic');

    topic.addSubscription(new subs.SqsSubscription(queue));
  }
}

As you can see, our app was created with a sample CDK stack (CdkWorkshopStack).

The stack includes:

  • SQS Queue (new sqs.Queue)
  • SNS Topic (new sns.Topic)
  • Subscribes the queue to receive any messages published to the topic (topic.addSubscription)

Synthesize a template from your app

  • The CDK CLI requires you to be in the same directory as your cdk.json file. If you have changed directories in your terminal, please navigate back now.
cdk synth

Will output the following CloudFormation template:

Resources:
  CdkWorkshopQueue50D9D426:
    Type: AWS::SQS::Queue
    Properties:
      VisibilityTimeout: 300
    Metadata:
      aws:cdk:path: CdkWorkshopStack/CdkWorkshopQueue/Resource
  CdkWorkshopQueuePolicyAF2494A5:
    Type: AWS::SQS::QueuePolicy
    Properties:
      PolicyDocument:
        Statement:
          - Action: sqs:SendMessage
            Condition:
              ArnEquals:
                aws:SourceArn:
                  Ref: CdkWorkshopTopicD368A42F
            Effect: Allow
            Principal:
              Service: sns.amazonaws.com
            Resource:
              Fn::GetAtt:
                - CdkWorkshopQueue50D9D426
                - Arn
        Version: "2012-10-17"
      Queues:
        - Ref: CdkWorkshopQueue50D9D426
    Metadata:
    ...

Bootstrapping an environment

The first time you deploy an AWS CDK app into an environment (account/region), you can install a “bootstrap stack”. This stack includes resources that are used in the toolkit’s operation. For example, the stack includes an S3 bucket that is used to store templates and assets during the deployment process.

You can use the cdk bootstrap command to install the bootstrap stack into an environment:

cdk bootstrap

Now Lets Deploy

cdk deploy You should see a warning like the following:

This deployment will make potentially sensitive changes according to your current security approval level (--require-approval broadening). Please confirm you intend to make the following modifications:

IAM Statement Changes (NOTE: There may be security-related changes not in this list. See https://github.com/aws/aws-cdk/issues/1299)

Do you wish to deploy these changes (y/n)?Y

CdkWorkshopStack: deploying...
CdkWorkshopStack: creating CloudFormation changeset...

 ✅  CdkWorkshopStack
Stack ARN:
arn:aws:cloudformation:REGION:ACCOUNT-ID:stack/CdkWorkshopStack/STACK-ID

The CloudFormation Console CDK apps are deployed through AWS CloudFormation. Each CDK stack maps 1:1 with CloudFormation stack.

This means that you can use the AWS CloudFormation console in order to manage your stacks. Let’s take a look at the AWS CloudFormation console. Just go to AWS cloudfromation and check console

cleanup on AWS resources

Open lib/QA-stack.ts and clean it up. Eventually it should look like this:

import * as cdk from 'aws-cdk-lib';

export class CdkWorkshopStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // nothing here!
  }
}

cdk diff

Now that we modified our stack’s contents, we can ask the toolkit to show us the difference between our CDK app and what’s currently deployed. This is a safe way to check what will happen once we run cdk deploy and is always good practice:

and now wecan trigger cdk deploy

- [-] AWS::SQS::Queue CdkWorkshopQueue50D9D426 destroy
- [-] AWS::SQS::QueuePolicy CdkWorkshopQueuePolicyAF2494A5 destroy
- [-] AWS::SNS::Topic CdkWorkshopTopicD368A42F destroy
- [-] AWS::SNS::Subscription CdkWorkshopTopicCdkWorkshopQueueSubscription88D211C7 destroy

Conclusion This Blog was about getting started Now we should be able to deploy any application from our vscode simple editor using AWS SDK, we just need AWS Profile with User account and aws-cdk installed on system In coming section i will cover some more advance examples using AWS-CDK

References

Comments