CDK Typescript Pipeline Workshop

Vu DaoVu Dao
4 min read

Abstract

  • AWS CDK (Cloud Development Kit) is an open-source framework which gives great depth to the concept of Infrastructure as Code

  • So Why CDK Pipelines? - We need the automation way to deploy our infrastructure as code for development, staging and production stages.

  • CDK pipeline with AWS Codepipeline brings to the table a feature called self-mutation or self-updation. This means whenever changes are pushed from a CDK project configured with CDK Pipelines, it first checks for any changes made to the pipeline itself. If there are no changes to the pipeline, it goes ahead and deploys the actual infrastructure stack.

  • In this blog, I reference to cdk pipeline typescript workshop to provide the full flow and source code as a cdk pipeline project.

Table Of Contents


πŸš€ Pre-requisite

  • Install typescript, node, and aws0 as well as projen (optional) which is a tool of managing project configuration as code.

  • Getting started with aws-cdk

πŸš€ Create repository and pipeline on AWS codecommit

  • We create infrastructure as code and build a pipeline for it, so we need to create a repository and then define the pipeline. So we create them manually using cdk deploy

  • The following source code creates a repository and a pipeline function to create a pipeline base on the input branch.

      import { Stack, StackProps } from 'aws-cdk-lib';
      import { Repository } from 'aws-cdk-lib/aws-codecommit';
      import { CodeBuildStep, CodePipeline, CodePipelineSource } from 'aws-cdk-lib/pipelines';
      import { Construct } from 'constructs';
      import { DEV_REGION, PROD_REGION } from './constants';
      import { WorkshopPipelineStage } from './pipeline-stage';
    
      export class CdkPipelineTest extends Stack {
        constructor(scope: Construct, id: string, props: StackProps) {
          super(scope, id, props);
    
          const repo = new Repository(this, 'workshop-cdk-pipeline-repo', {
            description: 'Test CDK pipeline',
            repositoryName: 'cdk-pipeline-test',
          });
    
          const genPipeline = function(_scope: Construct, branch: string) {
            const _pipeline = new CodePipeline(_scope, `workshop-cdk-pipeline-${branch}`, {
              pipelineName: `workshop-cdk-pipeline-${branch}`,
              synth: new CodeBuildStep('SynthStep', {
                input: CodePipelineSource.codeCommit(repo, branch),
                installCommands: ['npm install -g aws-cdk'],
                commands: [
                  'yarn install --frozen-lockfile',
                  'npx projen build',
                  'npx projen synth',
                ],
              }),
            });
            return _pipeline
          }
        }
      }
    
  • Run cdk deploy to create repository

πŸš€ Add pipeline stages to deploy CDK stacks

  • We create pipeline for master and develop branches. master branch represents for product environment which is deployed in region ap-southeast-1 and develop branch represents for development/test environment which is deployed on the region ap-south-1.

  • And note that, we use Dev/test environment to host the codecommit and pipeline (it's up to you to decide this).

      const developPipeline = genPipeline(this, 'HitCounterHandler` evelop');
      const masterPipeline = genPipeline(this, 'master');
    
  • From the pipeline we add stages which are our application stacks

      developPipeline.addStage(new WorkshopPipelineStage(this, 'Deploy', {
        env: {
          account: this.account,
          region: DEV_REGION
        }
      }));
    
      masterPipeline.addStage(new WorkshopPipelineStage(this, 'DeploySin', {
        env: {
          account: this.account,
          region: PROD_REGION
        }
      }));
    

  • The application stacks here is the CDK Workshop which includes

    • API GW (REST API) to handle API request with lambda integration.

    • The lambda function HitCounterHandler counts the API hits and stores them in dynamoDB and then calls the HelloHandler lambda function to return output which is string text.

  • Run cdk deploy again to add the pipelines.

πŸš€ Push code to test pipelines

  • We now already have a repository and pipeline, next steps we add git remote origin as our codecommit repo and then push code to master / develop branch in order to let the pipeline deploy the CDK application stacks.

  • Add remote origin

      ⚑ $ git remote add origin ssh://git-codecommit.ap-southeast-1.amazonaws.com/v1/repos/cdk-pipeline-test
      ⚑ $ git add -A
      ⚑ $ git push origin master
    
  • Check source code repo and pipeline

  • Cloudformation check stacks

  • Create develop branch and then push to deploy dev/test environment

      ⚑ $ git checkout -b develop origin/master
      ⚑ $ git push origin develop
    

πŸš€ Test webapp

  • Go to API GW stages and get the invoke url

  • Use curl to call API request

      ⚑ $ curl https://5fbyi7ak9e.execute-api.ap-south-1.amazonaws.com/prod
      Hello, CDK! You've hit /
    
      ⚑ $ curl https://5fbyi7ak9e.execute-api.ap-south-1.amazonaws.com/prod/hello
      Hello, CDK! You've hit /hello
    
  • Check DynamoDB for the hit counter

πŸš€ Cleanup

  • To clean up the stacks from this workshop, navigate to the Cloudformation Console, select your stacks, and hit β€œDelete”. This may take some time.

πŸš€ Conclusion

  • Teams now can use CDK to create/update infrastructure through cdk-pipeline without caring about the permission to run cdk deploy

References:

0
Subscribe to my newsletter

Read articles from Vu Dao directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vu Dao
Vu Dao

πŸš€ AWSome Devops | AWS Community Builder | AWS SA || ☁️ CloudOpz ☁️