Skip to content

CDK Early Days: Infrastructure in a Programming Language

With the CDK, infrastructure moves into the same toolchain as application code, which means tests, reviews, and logical identities suddenly decide whether production data survives.

≈ 11 min readSoftwareAWSCloud

CDK Early Days: Infrastructure in a Programming Language

The AWS Cloud Development Kit has been available as a developer preview for a few weeks now, and it noticeably changes how I think about infrastructure. Instead of writing YAML and hoping the indentation is right, I write TypeScript. I get types, autocompletion, loops, functions, and classes. That sounds like a pure convenience upgrade, but it is a shift in responsibility. If you describe infrastructure in a real programming language, you inherit all the tools of that language. But you also inherit its classes of bugs.

Editorial note (July 2026): The CDK is not a programming language of its own but a framework for defining infrastructure in existing languages and provisioning it through CloudFormation. The code shows the developer preview and later CDK v1: separate @aws-cdk/* packages and the Lambda runtimes of that time. CDK v2 bundles the stable Construct Library in aws-cdk-lib; new projects should therefore not copy the examples verbatim. The same applies to the deployment action further down: current GitHub Actions workflows should connect to AWS via OIDC and short-lived role credentials, not via long-lived access keys in repository secrets.

In what follows, I use a small, plausible stack as the common thread: an S3 bucket that users upload files into, and a Lambda function that processes those files. This example shows the interesting architecture question better than a list of features would.

From template to program#

Anyone who has worked with AWS for a while knows CloudFormation. You describe the target state declaratively, and the service reconciles it. The model is robust, but the format is tedious. Repetition can only be expressed through parameters and mappings, and as soon as a template grows beyond a thousand lines, you lose track of which resource actually depends on which.

The CDK reverses the direction. I write code, and in the end this code generates a CloudFormation template again. This step is called synthesis. What matters is that CloudFormation is still doing the work underneath. The CDK doesn’t replace the provisioning mechanism; it puts a programming layer on top of it. The advantage is obvious: abstraction, reuse, type checking. The price is that there is now a translation step between my source code and the real resources, and I should know its result.

In the current preview release, the library is split up by service. There is a core package and one package per AWS service. If you use S3 and Lambda, you install exactly those packages. That is unusually granular, but it has the effect of keeping your own dependencies small.

The three levels: App, Stack, Construct#

The model has three layers, and it pays to keep them cleanly apart, because each has a different job.

At the very bottom are the constructs. A construct is a building block. It encapsulates one or more CloudFormation resources along with sensible defaults. An S3 bucket is a construct, a Lambda function is a construct, and a self-written module that combines both into an upload processor is one as well. Constructs can be nested, and that is exactly where reusability comes from.

One level above is the stack. It is the unit that gets deployed and corresponds one to one to a CloudFormation stack. Whatever is in a stack is rolled out together and, in case of an error, rolled back together.

At the very top sits the app. It is the entry point and bundles one or more stacks. When the app runs, a template is generated for each stack.

flowchart TD
  App["App (entry point)"] --> Stack["Stack (deployment unit)"]
  Stack --> C1["Construct: S3 bucket"]
  Stack --> C2["Construct: Lambda function"]
  C1 --> Synth["Synthesis"]
  C2 --> Synth
  Synth --> CFN["CloudFormation template"]
  CFN --> AWS["Resources in the cloud"]

This hierarchy is not an end in itself. It determines what can be changed independently and what can’t. Two things in the same stack share their fate during a rollback. Two things in separate stacks can be updated separately, but then they have to express their connection explicitly through references.

The stack as code#

This is what the upload processor I mentioned looks like in the current library. Deliberately kept small so that the decision stays visible and doesn’t disappear in the trimmings.

import cdk = require("@aws-cdk/core");
import s3 = require("@aws-cdk/aws-s3");
import lambda = require("@aws-cdk/aws-lambda");

class UploadStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // Storage for incoming files.
    // RETAIN keeps the bucket even when the stack is deleted.
    const uploads = new s3.Bucket(this, "Uploads", {
      removalPolicy: cdk.RemovalPolicy.RETAIN
    });

    const handler = new lambda.Function(this, "ProcessUpload", {
      runtime: lambda.Runtime.NODEJS_10_X,
      handler: "index.handler",
      code: lambda.Code.fromAsset("dist/handler"),
      environment: {
        // The bucket name is resolved at runtime, not hard-coded.
        BUCKET_NAME: uploads.bucketName
      }
    });

    // Instead of writing an IAM policy by hand:
    // the construct grants the necessary permissions and nothing more.
    uploads.grantReadWrite(handler);
  }
}

const app = new cdk.App();
new UploadStack(app, "UploadStack");
app.synth();

Three places deserve a second look. The call uploads.grantReadWrite(handler) doesn’t write a policy by hand; it derives from the relationship between the two constructs which actions the function needs on the bucket. That is more than convenience, because it makes the principle of least privilege the default path instead of the exception. The line BUCKET_NAME: uploads.bucketName shows that at synthesis time, bucketName is not a finished string but a reference that CloudFormation resolves later. And removalPolicy: RETAIN is the small, inconspicuous line I will come back to shortly, because leaving it out gets expensive.

What stands out here: it is regular code. I can refactor it, extract it into a function, iterate over a list of environments. That is exactly the appeal. And that is exactly where the responsibility begins.

What you take on with a programming language#

As long as infrastructure lives in YAML, it is static and boring, but easy to oversee. As soon as it is code, the laws of code apply. A typo in a loop doesn’t create one wrong resource but fifty. A changed constant takes effect everywhere it is read. An abstraction that hides too much also hides costs and permissions from whoever reviews the stack.

This shifts what diligence means here: when infrastructure becomes programmable, it has to be treated like application code. It needs tests, it needs reviews, and it needs an understanding of what happens when you change it. That is not a burden the CDK imposes on us, but the honest consequence of using a real language.

Tests are not an add-on here. The library already ships an assertion module that lets you check the synthesized result without deploying at all:

import { expect, haveResource } from "@aws-cdk/assert";

test("Bucket survives deletion of the stack", () => {
  const app = new cdk.App();
  const stack = new UploadStack(app, "TestStack");

  expect(stack).to(haveResource("AWS::S3::Bucket", {
    DeletionPolicy: "Retain"
  }, undefined, true));
});

This test deploys nothing. It checks the generated template. That lets you pin down a rule that otherwise only exists in the head of an experienced colleague: this bucket must not disappear by accident. Checks like these are exactly what separate a stack that survives a demo from one that survives a change in staff.

The mistake that actually happens#

The most dangerous mistake in the CDK is not a syntax error, because the compiler catches those. It has to do with the logical identity of resources, and it is so treacherous because the code looks perfectly fine afterward.

CloudFormation identifies every resource by a logical ID. The CDK generates this ID from the construct’s path in the tree, so essentially from the second argument of the constructor, the name. In my example, the bucket is called "Uploads". Suppose someone finds this name unattractive and renames it purely for cosmetic reasons:

const uploads = new s3.Bucket(this, "UploadBucket", {
  removalPolicy: cdk.RemovalPolicy.RETAIN
});

Functionally, nothing changes. The code compiles, and the tests for the function’s behavior keep passing. But the logical ID has changed. For CloudFormation, that doesn’t mean the same resource with a new name. It means the old resource is gone and a new one has been added. So on the next deployment, a new, empty bucket is created, and the application then points to this empty storage. The deletion or replacement policy applies to the old resource.

This is where the inconspicuous line from before saves you. If removalPolicy: RETAIN is in the code, the old bucket is not deleted but released from the stack and remains as an orphaned resource. The data survives, even if the application can no longer find it, until someone cleans up manually. If this policy is missing, CloudFormation tries to remove the old resource. CloudFormation doesn’t silently empty a non-empty S3 bucket in the process; the deletion fails as long as it contains objects, unless a mechanism such as autoDeleteObjects has also been set up. That doesn’t make the rename harmless: the application already points to a new, empty bucket, and with other deletable resources or explicit automatic emptying, the replacement can actually destroy data.

The crucial point is not the individual policy. The point is that a harmless rename in the code triggers a destructive operation in the infrastructure, and that this consequence is not visible in the source code. It only becomes visible in cdk diff, which marks a replacement as such. If you read the diff before deploying, you see the damage coming. If you skip it because the last deployment went through just fine, you see it afterward.

$ cdk diff
Resources
[-] AWS::S3::Bucket Uploads      destroy
[+] AWS::S3::Bucket UploadBucket  create

This leads to a concrete operating rule: for stacks with state, the diff is not an optional intermediate step but part of the review. And stateful resources – buckets, databases, tables – get an explicit removal policy so that deleting or replacing a stack never silently takes data with it.

Abstraction is a decision, not a free convenience#

The grantReadWrite call is a good example of a successful abstraction, because it removes repetition and enforces a safe default. But there is the other kind, too. A self-written construct that encapsulates an entire microservice with a database, queue, function, and alarm is tempting. It keeps the calling code short. But it also makes invisible which twelve resources and which permissions come into being.

A good abstraction in the CDK reduces repetition and encapsulates reasonable defaults without obscuring what it costs and which permissions it hands out. The touchstone for your own construct is therefore not its elegance. It is the question of whether someone in the review still understands what they are buying into. If the only answer is that it works, the abstraction isn’t mature yet.

It helps to look at the result of the synthesis now and then. A cdk synth writes the finished template to the console. For an inconspicuous stack, that quickly adds up to a few hundred lines, and it is worth consciously noticing this ratio between short code and an extensive template. It is the most honest indicator of how much the abstraction is doing for you right now.

How this fits into a pipeline#

Infrastructure as code only shows its value when nobody deploys by hand anymore. In 2019, I built a small GitHub Action for this that installs the CDK in a container and runs deploy with AWS credentials from repository secrets. This credential pattern is historical; for new workflows, I use OIDC and a time-limited AWS role. What has remained is the appeal of the same mechanism shipping both application code and infrastructure. A pull request then changes not only the service but also its foundation, and both go through the same review.

This is exactly where the circle closes back to responsibility. If a merge is enough to change production infrastructure, then the review is the last place where a human can step in. The diff belongs in that review. The tests run before deployment. And for rules that are non-negotiable, such as that no bucket may be publicly readable, an automated check of the synthesized template pays off – a kind of policy as code for your own CDK output. That way, knowledge that otherwise depends on the reviewer’s form on the day moves into a check that is always equally strict.

What I take away from the first weeks#

The CDK is still young, the API is moving, and some things will change before the stable version. Still, the direction is clear, and it convinces me. Infrastructure becomes testable, reusable, and refactorable. That is a real gain over handwritten YAML.

But the gain is tied to an attitude. If you program infrastructure, you have to treat it like software, with everything that goes with it: small, verifiable building blocks, a test for every assumption that would be expensive if it broke, a diff that gets read before every deployment, and a conscious decision about what an abstraction may hide and what it may not. The logical ID and the removal policy are not footnotes here; they are the places where it is decided whether a refactoring stays harmless or costs data.

So the tool switch from YAML to TypeScript is the smaller part of the story. The bigger part is that operations and code quality are now the same topic. If you embrace that, you get infrastructure that you can read, check, and change with confidence. If you ignore it, all you end up with is the old mistakes in a new language.

Further reading#

Revised and translated from German with the help of AI.