AWS CDK - Building Cloud Infrastructure as CodeπŸ§‘β€πŸ’»

πŸ‘‰ Quick Intro πŸ”₯

  • There are many ways to create resources in AWS like

    • AWS Management Console

    • AWS CLI

    • AWS Software Development Kit (AWS SDK)

    • AWS Cloud Development Kit (CDK)

    • Terraform

    • many more…

  • You should know AWS CloudFormation before going ahead

  • AWS CDK is framework for defining cloud infrastructure as code using familiar programming languages like Python, TypeScript, JavaScript, Java, C#

  • It includes CLI interface for creating, managing, & deploying resources

    Let’s dive in! ➑️

πŸ‘‰ AWS CDK vs SDK vs Terraform πŸ“ƒ

FeaturesAWS CDKAWS SDKTerraform
What ?Framework for defining AWS infrastructure as codeLibraries or packages for various languages like boto3 for pythonOpen-source tool for infrastructure as code
How ?Write code to define resources, managed by AWSCode based API calls to AWS servicesWrite code to describe and manage infrastructure
Use ?Integrates AWS services into applicationsDefine and manage AWS infrastructure with high level constructsMulti cloud infrastructure management support
Languages ?Python, JavaScript, TypeScript, Java, C#Python, JavaScript, TypeScript, JavaHashiCorp Configuration Language (HCL)
Integration ?Generates CloudFormation template for deploymentDirect API interaction with AWS servicesWorks with multiple cloud like AWS, Azure, GCP

Note:- If you are using AWS for resources and you want separate code for infrastructure management then go for AWS CDK

πŸ‘‰ Cloud Development Kit (CDK) πŸ€–

  • In this blog, we’ll break down AWS CDK using a pizza restaurant analogy. Ready to cook up some epic cloud infrastructure ?

  • Setting up a pizza outlet, is kinda like setting up cloud infrastructure with AWS CDK. Your kitchen resources (cloud resources), prepping the ingredients (cloud services) and serving up the delicious pizza (application)

  • With AWS CDK, instead of fiddling with AWS management console for every little thing, you’re coding in languages you already know to define cloud resources.

    Cool, right ? 😎

πŸ‘‰ Setup CDK Project βš™οΈ

  1. Install CDK & pre-requisites

    • Install AWS CLI by following this AWS CLI Installation Guide

    • Install NodeJS, as AWS CDK uses NodeJS in the backend

    • Install Python if you are using Python for CDK coding

    • Install CDK as a global npm package

      npm install -g cdk

    • Check the version

      cdk --version

  1. Setting up project (pizza outlet)

    • Before you serve those cheesy pizzas, you need to get your kitchen ready πŸ§‘β€πŸ³

    • In AWS CDK, the kitchen is your project workspace where you code your cloud setup

    • I will be referring to CDK with python in this blog

    • To create the project, make a new folder. Inside it, use the command below and specify the language you will use for coding resources

      cdk init --language python

  1. Install dependencies (libraries)

    As I am referring python, so I will install libraries using pip

    pip install -r requirements.txt

πŸ‘‰ CDK CLI Commands πŸ’»

  1. Creating project (pizza outlet)

    • We already saw creating CDK project above

      cdk init --language python

  1. Needed resources (stock your kitchen)

    • This step is done only for the first-time setup

    • Now the kitchen is ready, but you need to stock it with all the essentials like the oven and utensils

    • The command below will prepare your AWS account with all the necessary resources CDK needs to deploy

      cdk bootstrap

    • This command sets up your AWS account with the S3 buckets, roles, and permissions needed for CDK. These resources are created through the bootstrap stack - CloudFormation template, which has default name CDKToolkit

  1. Verify everything (check the recipe)

    • Before you start cooking, you need to check the recipe πŸ“ƒ

    • In CDK, the recipe is a CloudFormation template that tells AWS what to do

    • The AWS CDK project is converted into a CloudFormation template using the below command. The template is stored in a new folder called cdk.out at the root level

      cdk synth

      cdk synth <stack_name>

    • If the code is correct, this command will succeed; otherwise, it will give an error

  1. Push the template (serve the pizza)

    • Time to cook and serve those cheesy pizzas! πŸ•

    • Below is the command where magic happens. It takes your CloudFormation template (recipe) and sets up the cloud resources in AWS (pizzas in oven) and get things rolling πŸš€

      cdk deploy

      cdk deploy <stack_name>

      cdk deploy --all

    • Your cloud infrastructure is live - like serving up fresh, hot pizzas to your customers! πŸ‘‹

  1. Check for changes (menu changes)

    • Thinking of adding new pizza to the menu ? πŸ€”

    • Before making changes, it’s smart to compare old and new menus just like the below command which compares your current deployed infrastructure with the changes you made in code

      cdk diff

      cdk diff <stack_name>

    • You’ll see a detailed list of changes, so you know exactly what’s different 🧐

  1. Overview (checkout your restaurant)

    • Want to see a quick overview of your pizza restaurant setup ? πŸ€”

    • Below command helps you see all the different stacks (or outlet branches) you have got running

      cdk ls

      cdk ls <stack_name>

    • It will list all the stacks in your CDK app, it is like looking at map of all your restaurant branches πŸ“

  1. Remove everything (closing time)

    • All the good things must come to an end! 🏴

    • When you’re done with your cloud infrastructure and want to clean up, it’s time to delete all the resources (shut down the kitchen). You can do this using the command below, which ensures everything gets cleaned up, leaving no traces behind

      cdk destroy

      cdk destroy <stack_name>

    • As of now, except S3 buckets everything gets deleted in the stack on destroy

πŸ‘‰ CDK Architecture πŸ“

AWS CDK app structure with stacks, constructs, and deployment to CloudFormation.

πŸ‘‰ Constructs πŸ”—

  • Basic building blocks of AWS CDK applications, categorized into three levels

  • Each level offers an increasing level of abstraction

  • The higher the abstraction, the less configuration required, meaning less expertise is needed, and vice-versa

  • In simple terms, constructs are classes available in libraries for each resource. Some resources may not have all levels of constructs available yet

πŸ‘‰ Constructs Levels πŸ”’

  1. L1 Construct (Low-level)

    • Also known as CFN resources, these are the lowest level of constructs and offer no abstraction

    • They require the most configuration and the highest level of expertise

    • Think of them as your raw ingredientsβ€”flour, cheese, tomatoes needed for pizza πŸ§€πŸ…πŸ•

    • They map directly to CloudFormation resources and are very flexible, but you have to do a lot of work yourself. These constructs are named starting with Cfn

    • Example: CfnFunction for lambda, CfnBucket for S3

  1. L2 Construct (Mid-level)

    • Also known as curated constructs, these are a widely used type

    • They map directly to CloudFormation resources like L1, but offer a higher level of abstraction and provide helper methods for easier and faster configuration

    • These are like pre-made pizza dough, ready-made pizza sauce, or shredded cheeseβ€”some of the hard work is already done πŸ§‘β€πŸ³

    • Example: Function for lambda, Bucket for S3

  1. L3 Construct (High-level)

    • Also known as patterns, with highest level of abstraction

    • Each L3 construct can contain collection of resources that are configured to work together to accomplish a specific task or service within your application

    • These are like pre-made pizzas which are dried and packaged, - you just have to oven it and eat πŸ•πŸ”₯

    • Example: PythonFunction for lambda, NodejsFunction for lambda

πŸ‘‰ Stack πŸ—„οΈ

  • An AWS CDK stack is a collection of one or more constructs that define AWS resources

  • Each CDK stack represents a CloudFormation stack in your CDK app

  • When you run cdk init, you get only one stack by default in your app, but now we will create two stacks in separate files

      # Stack 1 - s3_stack.py
    
      from aws_cdk import Stack, aws_s3 as s3
      from constructs import Construct
    
      class S3BucketStack(Stack):
          def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
              super().__init__(scope, construct_id, **kwargs)
    
              firstBucket = s3.Bucket(
                  self,
                  "FirstBucket",
                  bucket_name="first-bucket-s3",
                  versioned=True,
              )
    
      # Stack 2 - lambda_stack.py
    
      from aws_cdk import Stack, aws_lambda as _lambda
      from constructs import Construct
    
      class LambdaStack(Stack):
          def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
              super().__init__(scope, construct_id, **kwargs)
    
              myLambda = _lambda.Function(
                  self,
                  "FirstLambda",
                  runtime=_lambda.Runtime.PYTHON_3_9,
                  code=_lambda.Code.from_asset("lambda"),
                  handler="hello.handler",
              )
    
      # app.py
    
      #!/usr/bin/env python3
      import aws_cdk as cdk
      from cdk_practice.lambda_stack import LambdaStack
      from cdk_practice.s3_stack import S3BucketStack
    
      app = cdk.App()
    
      LambdaStack(app, "LambdaStack")
      S3BucketStack(app, "S3BucketStack")
    
      app.synth()
    

πŸ‘‰ Apps πŸ“¦

  • AWS CDK app is a collection of one or more CDK Stacks

  • App construct doesn’t require any initialization argument, it is only a construct that can be used as root

  • The App and Stack classes from the AWS Construct Library are unique constructs that provide context to your other constructs without setting up AWS resources themselves

  • All constructs representing AWS resources must be defined within a Stack construct, and Stack constructs must be defined within an App construct

  • By default, when a CDK project is initialized, it will have only one app and one stack

      # app.py
    
      #!/usr/bin/env python3
      from aws_cdk import App
      from cdk_demo.cdk_demo_stack import CdkDemoStack
    
      app = App()
      CdkDemoStack(app, "CdkDemoStack")
    
      app.synth()
    

πŸ‘‰ Conclusion βœ…

This is more than enough to get started with AWS CDK. You can learn as you code. For more details, you can always refer to the CDK documentation.

Happy Learning !!! πŸ‘‹

11
Subscribe to my newsletter

Read articles from Sudhanshu Sanjay Motewar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sudhanshu Sanjay Motewar
Sudhanshu Sanjay Motewar