Understanding AWS CDK, one stack at a time

In one sentence: With AWS Cloud Development Kit (CDK), we write a program that produces a CloudFormation template. CloudFormation reads that template and creates or updates the resources in AWS.

Keep that split in mind: the CDK application describes the infrastructure; CloudFormation builds it. The CDK command-line tool connects the two.

1. The problem

Say we need a network, a load balancer, a Postgres database and an application running in Amazon Elastic Container Service (ECS). We have three ways to describe the setup.

  1. Configure it in the AWS console. We can create the resources, but repeating the setup and reviewing changes means keeping track of the individual settings ourselves.
  2. Write a CloudFormation template by hand. The setup becomes a file we can review and reuse. As we add roles, security groups, logs and connections, that file grows.
  3. Write a program that produces the template. That is CDK. We get functions, loops and types, and the output is still a file CloudFormation understands.

For example, beta and production might use the same arrangement with different sizes. A program can express the shared arrangement once and take the size as an input.

2. Start with CloudFormation

Before looking at CDK, we need three ideas.

A template is a description in JSON or YAML: “I want a bucket, a queue and a role that can read the bucket.” Each resource has a type, properties and a logical ID identifying it within the template.

A stack is the group of resources CloudFormation manages using that template.

CloudFormation is the builder. We give it a template to create a stack. Later, we submit a revised template to update that stack.

Put the old and new templates beside each other:

Old template New template What the change means
Bucket A Bucket A, same properties No template change for A.
Queue B Queue B, changed properties Update B; the property rules determine whether replacement is needed.
Service C No C Remove C from the stack, following its deletion policy.
No D Role D Create D.

The important idea is that removing a resource from the description is itself a change. On the next deployment, CloudFormation acts on that removal. Depending on its policy, the resource may be deleted or retained.

The template does not continuously control AWS on its own. Editing a file on our laptop changes nothing in the running stack until we deploy it.

3. CDK draws the blueprint

Think of the CDK application as an architect's program that draws a blueprint. CloudFormation is the builder who receives it. Creating an object in that program is not the same as creating its resource in AWS.

CDK calls those objects constructs. They form a tree: an app contains stacks, and each stack contains constructs describing its infrastructure.

A simplified tree: the CDK app contains a stack, the stack contains bucket and role constructs, and grantRead adds a policy under the role.

Each stack produces a template. An app with several stacks can produce several templates.

Constructs come at different levels:

Level What we write Example
L1 A direct description of a CloudFormation resource. Class names start with Cfn. CfnBucket
L2 A resource with defaults and helper methods. Bucket, with grantRead(role)
L3 A pattern combining several constructs. A load-balanced Fargate service.

For example, bucket.grantRead(role) creates the Identity and Access Management (IAM) policy needed to give that role read access. The generated policy refers to the bucket's Amazon Resource Name (ARN). We do not have to write those references by hand.

That also explains why one line of CDK code can add more than one resource to the template. The construct may describe a whole arrangement, including its supporting resources.

4. Follow one deployment from start to finish

For a TypeScript app that has been compiled, cdk.json might contain:

{
  "app": "node dist/app.js"
}

Now follow cdk deploy UploadsDemo.

Step 1. The command-line tool finds the program. It reads the app command from cdk.json and starts it.

Step 2. The program runs. It creates the app, stacks and construct tree in memory. A bucket constructor adds a description of a bucket; it does not provision one. The program can still read files or call other services. CDK resource lookups may query AWS and cache their results in cdk.context.json.

Step 3. Synthesis writes the output. The application produces a cloud assembly, normally in cdk.out. It contains a template for each stack and a manifest.json describing the assembly. Deployable files or Docker image sources can also be included as assets.

Step 4. The tool publishes assets when needed. Lambda code may need to go into S3; a container image may need to go into an Elastic Container Registry (ECR) repository. Bootstrapping sets up supporting resources, including asset storage and deployment roles, in the target AWS account and region. Those supporting resources can be updated later.

Step 5. CloudFormation prepares a change set. This previews the proposed operations: add, modify, replace or remove resources. It does not execute those operations just by showing them.

Step 6. CloudFormation executes the changes. It works through resource dependencies. A role needed by a task definition must be available before that task definition can use it. The terminal shows progress and failures. If an operation fails, rollback can try to undo the stack changes, but rollback can fail too and cannot guarantee recovery of stored data.

The CDK application produces a cloud assembly. The command-line tool submits it to CloudFormation, which creates or updates AWS resources.

So an ordinary cdk deploy includes synthesis. It runs the application before applying the resulting description. cdk synth stops after producing that description.

5. Map the commands to the steps

Command What it does
cdk synth Runs the app and writes the cloud assembly.
cdk ls Runs the app and lists its stacks.
cdk diff Compares the new template with the deployed template, or a template we supply.
cdk deploy <stack> Synthesizes, publishes assets when needed, and deploys the stack and its dependencies.
cdk deploy <stack> --exclusively Deploys only the selected stack, skipping its dependencies.
cdk destroy <stack> Asks CloudFormation to delete the stack, subject to resource policies.
cdk bootstrap Creates or updates deployment-support resources in an account and region.
cdk deploy --hotswap For supported development changes, updates resources directly through service APIs. Otherwise, falls back to a normal deployment.

deploy, destroy and bootstrap can change AWS resources. synth and ls do not perform the ordinary stack deployment, but running the app can still involve lookups or other service calls. diff against a deployed stack reads its template.

Run diff before deploying. Use it to review what changed, then inspect any proposed replacement or removal. A CloudFormation change set provides another view of the proposed operations. Neither a template diff nor a change set proves that execution will succeed.

Hotswap is a development shortcut. It bypasses CloudFormation for supported changes and introduces drift, so it should not be used for production deployments.

6. The surprises to understand

Removing something from code can remove it from AWS. A condition might leave a service out of the new template. If the old template contained it, the next deployment removes it from the stack. For data-bearing resources, inspect deletion and retention policies before proceeding.

A rename can change resource identity. CloudFormation uses logical IDs to track resources. CDK derives those IDs from construct paths. A variable name and a construct identifier therefore have different consequences.

Renaming a variable leaves the template unchanged. Adding encryption changes properties under the same logical ID. Renaming the construct produces a new logical ID.

In the small bucket example shown here, renaming the TypeScript variable leaves the template unchanged. Renaming the construct from Uploads to Documents changes the bucket's logical ID. CloudFormation sees the old entry disappear and a new one appear. Retaining the old bucket keeps its files; it does not copy them to the new bucket.

Some property changes require replacement. Keeping the same logical ID does not guarantee an update in place. The rules for the resource and property determine whether CloudFormation can modify it or must replace it.

Console edits can drift from the template. Changing a security group in the console does not update the file in our repository. A later stack operation may overwrite that change or fail because of it. A template diff alone does not fully inspect live drift.

Stacks can depend on each other. When two stacks in the same account and region share a resource value, CDK can produce a CloudFormation export in one and an import in the other. That export cannot be removed or changed while another stack imports it. Splitting infrastructure into stacks gives us boundaries, but also dependencies to manage.

7. Keep the whole path in view

The path is:

TypeScript → construct tree → templates → CloudFormation → AWS resources.

The first three stages produce the description. Deployment applies it. This is why we can inspect a CDK application's output without deploying the infrastructure.

For a small exercise, use CDK v2.28.0 to synthesize a stack containing a bucket. Open its template and find the logical ID. Rename only the variable and synthesize again. Then rename the construct identifier. Compare the outputs before considering a deployment: which edit changed how CloudFormation identifies the bucket?

Sources & references

Comments

Popular posts from this blog

getting android emulator to work normally on 64 bit linux

specs 2, Scala and maven with IntelliJ 12.1 and getting things right

me, akka and scala