Stack deployment using cdk and cloud formation template.

aws
Reading Time: 5 minutes

Whenever we need a cloud based deployment with handful of resources we go for manual deployment. But what if the resources needed are large enough to be deployed manually ? In this case we consider programmatically deployment using cdk.

As the complexity of the system increases , the needed infrastructure also grows , so managing it manually becomes little tough. So today we will witness as how to use AWS development kit to deploy a sample app in cloud.

What is AWS CDK ?

The AWS Cloud Development Kit  is an open-source software development framework to define cloud infrastructure in code and provision it through AWS Cloud Formation. It enables us to model application infrastructure using Python , JAVA , .NET etc.

AWS CDK

The above diagram shows the infra workflow of the AWS CDK.

The AWS CDK is available in following languages.

  • JAVA
  • .NET
  • GO
  • PYTHON
  • Javascript or typescript.

Installing AWS CDK In your system.

To install AWS CDK we will use npm to install in our system.

The below command is used to install the kit.

sudo npm install -g aws-cdk

The above command will give the following output.

After this to check the version just type the below command to know the version.

cdk version

2.20.0 (build 738ef49)

So once the cdk is installed lets move to deploy a sample project using aws cdk.

Deploying a sample application using cdk.

We will go step wise to set up the aws cdk.

1 – Initialize AWS CDK project.

The aws cdk gives a simple command to initialize an application in the language of users choice. The below command will set and initialize an application.

cdk init sample-app --language=typescript

THe above command sets a module that contains its own set of dependencies. The above command creates a typescript CDK application with the sample app template.

Lets see the output of the above command.

So after the command is run the initialization starts and it sets the particular folder to initial typescript project. The main file that we need to deal with is the cdk-stack.ts file in the lib folder. This file contains a single stack with constructs in it.

THe below code shows the file 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 AwsCdkStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

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

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

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

The ckd init command produces few files in the particular directory.

  • It produces .gitignore file that and initializes it as a git repo.
  • package.json -> It manages the project dependencies and a tsconfig.json file for Typescript configuration.

While initializing it also gives few commands which show us what when to use. Like to compile the app for catching errors we can use

npm run build

2 – Synthesize the application to cloud formation template.

The synth command helps to synthesize the stack to an AWS CloudFormation template.

The below command helps to atain the above

cdk synth

The output is like :-

Resources:
  AwsCdkQueue7B79C8BE:
    Type: AWS::SQS::Queue
    Properties:
      VisibilityTimeout: 300
    UpdateReplacePolicy: Delete
    DeletionPolicy: Delete
    Metadata:
      aws:cdk:path: AwsCdkStack/AwsCdkQueue/Resource
  AwsCdkQueuePolicy4B641FDF:
    Type: AWS::SQS::QueuePolicy
    Properties:
      PolicyDocument:
        Statement:
          - Action: sqs:SendMessage
            Condition:
              ArnEquals:
                aws:SourceArn:
                  Ref: AwsCdkTopicF164620F
            Effect: Allow
            Principal:
              Service: sns.amazonaws.com
            Resource:
              Fn::GetAtt:
                - AwsCdkQueue7B79C8BE
                - Arn
        Version: "2012-10-17"
      Queues:
        - Ref: AwsCdkQueue7B79C8BE
    Metadata:
      aws:cdk:path: AwsCdkStack/AwsCdkQueue/Policy/Resource
  AwsCdkQueueAwsCdkStackAwsCdkTopic9A093C2831483039:
    Type: AWS::SNS::Subscription
    Properties:
      Protocol: sqs
      TopicArn:
        Ref: AwsCdkTopicF164620F
      Endpoint:
        Fn::GetAtt:
          - AwsCdkQueue7B79C8BE
          - Arn
    Metadata:
      aws:cdk:path: AwsCdkStack/AwsCdkQueue/AwsCdkStackAwsCdkTopic9A093C28/Resource
  AwsCdkTopicF164620F:
    Type: AWS::SNS::Topic
    Metadata:
      aws:cdk:path: AwsCdkStack/AwsCdkTopic/Resource
  CDKMetadata:
    Type: AWS::CDK::Metadata
    Properties:
      Analytics: v2:deflate64:H4sIAAAAAAAA/1WNQQ7CIBBFz9I9HUvjxnUvoK170wIm01aoDGgM4e4WSEzczP//5SXTQttAU41vqoVc6hUnCIMbxcJ2dAv0JAgXr7xi3V2Xku/ZrCg+P1hmZKR3f/ATCYubQ6OT8bevZkORaC4xptorMt6K/KMzWmIyI9NGKpjp8OJH4Cfg1UyItfXa4UNBX/ILmxlUMcEAAAA=
    Metadata:
      aws:cdk:path: AwsCdkStack/CDKMetadata/Default
    Condition: CDKMetadataAvailable
Conditions:
  CDKMetadataAvailable:
    Fn::Or:
      - Fn::Or:
          - Fn::Equals:
              - Ref: AWS::Region
              - af-south-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-east-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-northeast-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-northeast-2
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-south-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-southeast-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-southeast-2
          - Fn::Equals:
              - Ref: AWS::Region
              - ca-central-1
          - Fn::Equals:
              - Ref: AWS::Region
              - cn-north-1
          - Fn::Equals:
              - Ref: AWS::Region
              - cn-northwest-1
      - Fn::Or:
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-central-1
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-north-1
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-south-1
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-west-1
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-west-2
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-west-3
          - Fn::Equals:
              - Ref: AWS::Region
              - me-south-1
          - Fn::Equals:
              - Ref: AWS::Region
              - sa-east-1
          - Fn::Equals:
              - Ref: AWS::Region
              - us-east-1
          - Fn::Equals:
              - Ref: AWS::Region
              - us-east-2
      - Fn::Or:
          - Fn::Equals:
              - Ref: AWS::Region
              - us-west-1
          - Fn::Equals:
              - Ref: AWS::Region
              - us-west-2
Parameters:
  BootstrapVersion:
    Type: AWS::SSM::Parameter::Value<String>
    Default: /cdk-bootstrap/hnb659fds/version
    Description: Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip]
Rules:
  CheckBootstrapVersion:
    Assertions:
      - Assert:
          Fn::Not:
            - Fn::Contains:
                - - "1"
                  - "2"
                  - "3"
                  - "4"
                  - "5"
                - Ref: BootstrapVersion
        AssertDescription: CDK bootstrap stack version 6 required. Please run 'cdk bootstrap' with a recent version of the CDK CLI.

The above is generated in cdk.out file which is the cloud formation template and the file can be deployed either manaully or by using the terminal or command line. The CDK toolkit also supports the deployment . Now lets move towards the deployment using the commandline.

3 – How to deploy the above stack

Prerequisite : Before deploying the below are the mentioned requisite.

  • AWS cli installed
  • Aws credentials configured in your system.

Now to deploy the stack using the above

To deploy the stack we need to run the below command

cdk deploy

The above image shows the deployment .

So these were the very simple steps of how to deploy an application using programmatically using cloud formation template.

Conclusion.

The above article provided a quick overview as how to proceed for programmatic deployment of stack. Also there is manual deployment that simply involves uploading the cloud formation template in the aws.

knoldus

Written by 

Rishivant is a enthusiastic devops learner at Knoldus. He believes in going 1% up everyday and showcases his learning in his work.

Leave a Reply