Lesson 1 of 3 AWS CDK, Terraform and Git

Running and Troubleshooting the AWS CDK Workflow

This lesson explains how the AWS Cloud Development Kit (AWS CDK) defines infrastructure in programming languages and deploys it through CloudFormation, and how CloudOps engineers run and troubleshoot its workflow.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe apps, stacks and constructs.
  • Run the CDK CLI workflow, including bootstrapping.
  • Operate CDK-managed resources through CloudFormation.

Apps, stacks and constructs

A CDK app is a program, in TypeScript, JavaScript, Python, Java, C# or Go, that defines one or more stacks, each of which becomes a CloudFormation stack. Stacks contain constructs, the building blocks. L1 constructs (named Cfn*) map one-to-one to CloudFormation resources. L2 constructs represent a resource with sensible defaults and helper methods, for example bucket.grantRead(role) generates the IAM policy. L3 constructs, or patterns, combine many resources, such as an ApplicationLoadBalancedFargateService. Stacks are bound to an environment (account and Region) explicitly or from the CLI profile.

from aws_cdk import App, Stack, Duration, aws_s3 as s3, aws_cloudwatch as cw
from constructs import Construct

class LogsStack(Stack):
    def __init__(self, scope: Construct, id: str, **kw):
        super().__init__(scope, id, **kw)
        bucket = s3.Bucket(self, "Archive", versioned=True,
                           encryption=s3.BucketEncryption.KMS_MANAGED,
                           lifecycle_rules=[s3.LifecycleRule(expiration=Duration.days(365))])
        objects = cw.Metric(namespace="AWS/S3", metric_name="NumberOfObjects", period=Duration.days(1),
                            dimensions_map={"BucketName": bucket.bucket_name, "StorageType": "AllStorageTypes"})
        cw.Alarm(self, "TooManyObjects", metric=objects, threshold=1_000_000, evaluation_periods=1)

app = App()
LogsStack(app, "LogsStack", env={"account": "111122223333", "region": "eu-west-1"})
app.synth()
Sort into groups

Construct levels

Exam skills 3.1.2

Classify each construct by its level.

Log in to try this activity Interactive activities are free with an account.

The CDK CLI workflow

cdk bootstrap prepares each account and Region once by deploying the CDKToolkit stack, which creates an S3 bucket and ECR repository for assets and IAM roles used for deployments, lookups and file publishing; deploying to an environment that has not been bootstrapped fails with an error about missing bootstrap resources or SSM parameter /cdk-bootstrap/hnb659fds/version. Cross-account deployments bootstrap the target with --trust for the pipeline account. cdk synth runs the app and produces CloudFormation templates in cdk.out; cdk diff compares them with deployed stacks; cdk deploy uploads assets and creates or updates stacks through CloudFormation, showing IAM and security group changes for approval; cdk destroy deletes stacks. cdk.context.json caches lookups such as VPC IDs and AMIs so that synthesis is deterministic and should be committed to source control.

CommandPurpose
cdk bootstrapCreate staging bucket, ECR repository and roles per account and Region
cdk synthGenerate CloudFormation templates
cdk diffShow differences from the deployed stack
cdk deployDeploy stacks through CloudFormation
cdk destroyDelete stacks

The following diagram shows the CLI commands in order.

The CDK CLI workflow. cdk bootstrap prepares each account and Region once with the CDKToolkit stack. cdk synth produces CloudFormation templates in cdk.out, cdk diff compares them with the deployed stacks, and cdk deploy deploys through CloudFormation.
Reviewing cdk diff before deploying catches replacements, like reviewing a change set.
Put in order

CDK workflow

Exam skills 3.1.2

Put the CDK commands for a first deployment to a new account and Region in order.

Log in to try this activity Interactive activities are free with an account.

Operating CDK-managed resources

Because the CDK deploys CloudFormation stacks, all CloudFormation operations still apply: stack events for troubleshooting, drift detection, termination protection (set in code) and RemovalPolicy, the CDK name for DeletionPolicy, which defaults to RETAIN for most stateful resources such as S3 buckets and DynamoDB tables, and to SNAPSHOT for RDS databases. Changing a construct's logical ID, for example by renaming it or moving it in the construct tree, causes CloudFormation to replace the resource, which cdk diff reveals.

Worked example

A first deployment to a new Region

An engineer runs cdk deploy for a stack targeting a newly used Region and receives an error that the environment has not been bootstrapped. They run cdk bootstrap aws://111122223333/ap-southeast-2, which creates the toolkit stack. The deploy then succeeds. Later, cdk diff after a refactor shows the S3 bucket being destroyed and recreated because its construct ID changed; the engineer restores the original ID before deploying.

Check yourself

Which command shows the changes a deployment would make?

Show answer

cdk diff.

Exam Tips

Remember for the exam

  • CDK apps synthesise CloudFormation templates; deploys are CloudFormation stack operations.
  • Run cdk bootstrap once per account and Region before deploying.
  • cdk diff shows changes, including replacements caused by construct ID changes.
  • L2 constructs provide defaults and grant methods; L3 constructs are patterns.
  • Commit cdk.context.json for deterministic lookups.