Chrysolites Tech Academy

Infrastructure as Code: Pulumi, Terraform and the AWS CDK · Course book

Chapter 3: Infrastructure in a Programming Language

Pairs with Lesson 3: The AWS Cloud Development Kit

AWS has long offered CloudFormation, a service that creates infrastructure from JSON or YAML templates. Templates for real systems run to thousands of lines and offer no loops, functions or reuse. The AWS Cloud Development Kit, CDK, lets you write the same infrastructure in a general-purpose programming language such as TypeScript or Python, then turns your program into a CloudFormation template automatically. This chapter explains the CDK's building blocks, the three levels of abstraction its constructs offer, what happens when a CDK app is synthesised and deployed, and how to write, reuse and test your own constructs, using a small serverless application as the running example.

Apps, stacks and constructs

A CDK project has a simple hierarchy. At the top is the app, the program as a whole. The app contains one or more stacks, each of which becomes a CloudFormation stack, a unit that is deployed and deleted together. A stack contains constructs, and constructs can contain other constructs, forming a tree.

A construct is any piece of cloud infrastructure represented as an object in your code: a storage bucket, a function, a database table, or a whole pattern combining many of them. You create one by calling its class with three arguments: the scope, meaning the construct it belongs to, usually this; an id that is unique within that scope; and props, the settings.

const table = new dynamodb.Table(this, 'Hits', {
  partitionKey: { name: 'path', type: dynamodb.AttributeType.STRING },
});

Because constructs are ordinary objects, the whole power of the language is available: loops to create one queue per customer, functions that return standard configurations, classes that bundle several resources into a reusable component, and the editor's auto-completion and type checking to catch misspelled settings before anything is deployed.

The id matters more than it looks. The CDK combines the ids along each construct's path through the tree to produce a unique logical name for the resource in the generated template, and CloudFormation uses that logical name to recognise the same resource from one deployment to the next. Choosing short, meaningful ids, and keeping them stable, therefore keeps both the template readable and the resources safe from accidental replacement.

A typical project layout reflects the hierarchy. A bin folder holds the entry point that creates the app and its stacks, a lib folder holds the stack definitions and custom constructs, a test folder holds tests, and a cdk.json file tells the command-line tool how to run the app. Creating a new project with cdk init produces all of this, ready to deploy.

Three levels of construct

The CDK's construct library offers each AWS service at up to three levels of abstraction.

LevelWhat it isExampleTrade-off
Level 1 (L1)A direct, one-to-one mapping of a CloudFormation resource, named with a Cfn prefixCfnBucketComplete control; you must set every detail yourself
Level 2 (L2)A curated resource with sensible defaults and helper methodsBucket, Function, TableConcise and safe for most uses; the usual choice
Level 3 (L3)A pattern combining several resources for a common taskA load-balanced container serviceVery little code; less flexibility if your needs differ

L2 constructs earn their place through helpers that encode good practice. For example, table.grantReadWriteData(fn) gives a function permission to read and write one table and nothing else, generating the exact permission policy that would take many lines to write by hand and is easy to get dangerously wrong. L3 patterns go further: one construct can create a container service, its cluster, a load balancer, security groups and the networking between them.

From code to cloud: synthesis and deployment

A CDK app does not talk to AWS while it runs. Running cdk synth executes your program, which builds the construct tree, and then synthesises it: every construct produces its part of a CloudFormation template, written out as a file. cdk deploy then hands that template to CloudFormation, which creates, updates or deletes resources to match, rolling back automatically and safely if anything fails part-way.

CDK codeTypeScript, Pythoncdk synthbuilds the treeTemplateCloudFormationAWS resourcesvia cdk deploy assets uploaded to thebootstrap bucket
Figure 3.1 — From CDK code to running resources. The CDK writes the template; CloudFormation does the creating, and assets travel separately.

Some constructs need files as well as settings, for instance the code of a Lambda function or a Docker image. These are assets. During deployment the CDK uploads them to an S3 bucket and a container registry, and the template refers to their uploaded copies. Those storage locations must exist before the first deployment in each account and region, which is what the one-time command cdk bootstrap sets up for you. Before deploying a change, cdk diff compares your code with what is currently deployed and lists the differences, the CDK's equivalent of a plan.

The gap between what you write and what is generated is often striking. A few lines of L2 code for a function behind an API can synthesise into a template of a hundred or more lines, including permissions and configuration you never had to think about. Reading the generated template once is a good way to learn what the defaults actually do, and to understand exactly what you are about to deploy.

The workshop application: an API with a hit counter

A classic introductory project builds a small serverless application in stages. First, a Lambda function, a piece of code that AWS runs on demand with no server to manage, returns a greeting. An API Gateway in front of it gives it a public web address, so a request to any path returns the greeting.

Next comes a custom construct, a hit counter. It wraps any function: each incoming request first goes to a second function, which adds 1 to a count for that path in a DynamoDB table and then calls the original function. Packaging this as a class called HitCounter, with a property for the function to wrap, makes it reusable in any stack. Inside, it creates the table and the counting function, and grants the counting function permission to update the table and to call the wrapped function.

User API Gateway Hit counterfunction DynamoDBcount per path Hellofunction 1. add 12. call The HitCounter construct packages the counting function, the table and their permissions.
Figure 3.2 — The hit counter. A reusable construct sits in front of any function, counting requests per path before passing them on.

The construct's interface is small by design: callers pass in the function to wrap and receive back the new counting function and the table, which they can use elsewhere, for example to grant another component permission to read the counts. Everything else, including the permissions between the parts, stays hidden inside the construct. That is the same principle as a well-designed function in ordinary code: a clear interface in front of hidden details.

If the root path is requested 3 times and the path /hello twice, the table holds two items: / with a count of 3 and /hello with a count of 2. To see those counts without opening the console, the workshop adds a ready-made construct from a public library that publishes a simple web page displaying any table's contents, showing how constructs written by others plug in with a line or two of code.

Testing and good practice

Because infrastructure is now code, it can be tested like code. CDK's assertions library synthesises a stack in a test and checks the resulting template. A fine-grained assertion checks a specific fact, such as "the template contains exactly one DynamoDB table" or "that table has encryption enabled". A snapshot test saves the whole template and fails if a later change alters it unexpectedly, prompting a deliberate review. Validation can also be built into constructs themselves: the HitCounter might refuse a requested number of read units outside a sensible range, raising an error at synthesis time instead of failing in the cloud.

Keep stateful resources safe. Changing a construct's id makes CloudFormation treat it as a new resource, replacing the old one. For tables and buckets that hold data, keep ids stable, and set a retention policy so that deleting the stack does not delete the data.

Tests run in seconds without touching AWS, because they inspect only the synthesised template. That makes them cheap enough to run on every change in a CI pipeline, catching mistakes such as a missing permission or a table accidentally left unencrypted long before anything is deployed.

Larger projects separate stateful resources such as databases into their own stacks, deploy through pipelines instead of from laptops, and share organisation-wide constructs, such as "a bucket with our required security settings", as internal libraries so every team gets the same defaults.

Check your understanding

  • What are the three arguments passed when creating a construct?
  • Give an example of an L1, an L2 and an L3 construct, and say when you would use each.
  • What does cdk synth produce, and what does cdk deploy do with it?
  • Why must an account be bootstrapped before the first deployment?
  • Requests arrive for /, /, /about, / and /about. What does the hit counter table contain? (Answer: / with 3 and /about with 2.)
  • What is the difference between a fine-grained assertion and a snapshot test?
  • Why is changing the id of a database table construct risky?

Install Chrysolites Tech Academy

Android / Chrome / Edge: open the browser menu and choose Install app or Add to Home screen.

iPhone / iPad (Safari): tap the Share button, then Add to Home Screen.