'Build Once, Deploy Anywhere' with CDK/CloudFormation

I’ve been trying to solve this problem across three companies so far, and further I go, I get more confused, especially at how much the engineering community doesn’t seem to care about this principle.

As the title says, I’m trying to implement the ‘Build Once, Deploy Anywhere’ principle. In other words, I want to be sure whatever I have on a lower environment (e.g. test or acceptance) can be replicated exactly as-is on a higher environment (e.g. production), which is called a promotion.

The main problem with CDK is that it synthesizes an environment-specific template. Basically, there’s no way to parameterise a produced template, in order for it to be reusable. Basically, it’s against their philosophy:

Using parameters requires you to be mindful of how the code you’re writing behaves at deployment time, and also at synthesis time. This makes it harder to understand and reason about your AWS CDK application, in many cases for little benefit.

Generally, it’s better to have your CDK app accept necessary information in a well-defined way and use it directly to declare constructs in your CDK app. An ideal AWS CDK-generated AWS CloudFormation template is concrete, with no values remaining to be specified at deployment time.

What I’m missing, though, is the reasoning behind this, and any suggested alternatives. Sure, AWS is a proprietary service, they have the right to be opinionated, so we can’t really expect AWS to come up with a reason.

As for the alternatives, how do large organisations using CDK deploy? Do they all just trust CDK to be idempotent and generate the same template given the same parameters? CDK also encourages creating reusable constructs. Should we just trust the pinning mechanisms of our package managers to make sure of idempotency?

I feel like I’m stuck in a loop here, or maybe missing something really obvious. How to deploy with CDK without praying that nothing breaks?

Infrastructure unlike normal code, can be mutated by users, other api calls? Things can be deprecated etc

The concept of build once and promote doesn’t make sense to me in that context.

I agree with AWS here, it needs to be evaluated in each environment, and you can encapsulate checks in your deployment to make sure it operates and is deployed as expected and roll it back if not.

It’s not dissimilar from installer packages for software, they prepare the installation as a transaction, react to the enviro it’s being installed into and roll back if something went wrong

They want you to use reusable components multiple times with different parameters. You can then choose which stacks to deploy or diff.

For example, you can have AppStack initialized the times. Once for development, once for staging, and once for production. In production you also pass an override for bigger instance size.

When a new developer comes in, they immediately know all deploy targets with cdk ls. When you want to see diff based on changes, you can use just one cdk diff command. When you read the code, you immediately know what it deploys.

The CDK itself doesn’t read the current state of resources, CloudFormation does. CloudFormation is like an installer package that is reactive to the changes in the environment, while CDK is like an installer factory. That’s why it doesn’t make sense to me that why would CDK care about the target environment.

That still means I have to pin/trust all the dependencies I have to be behave the same, `aws-cdk-lib` for example, or any in-house constructs installed from a registry.

Is what you described an AWS official best practice?

A few strategies here…

Look at the CDK assertion libraries for unit testing. You can create unit tests to ensure the proper resources are generated.

I also frequently will use a snapshot test against the generated CloudFormation. This helps bring any changes to the surface as you update CDK to newer versions. There are plenty of times I have noticed a new IAM policy or some detail change after updating CDK version.

You can also do a CDK diff command to preview what will change when you redeploy an existing stack. This can become part of your CI pipeline.

The CDK itself doesn’t read the current state of resources, CloudFormation does.

The CDK will read state occasionally and store as context in ‘cdk.context.json’.

That still means I have to pin/trust all the dependencies I have to be behave the same, aws-cdk-lib for example, or any in-house constructs installed from a registry.

You only need to validate that the outputs are the same. Meaning that it’s going to generate the same CloudFormation (or Cloud Assembly, really).

If the outputs are environment dependent, how can two outputs for two different environments be the same?

This helps bring any changes to the surface as you update CDK to newer versions.

That is exactly my concern! The purpose of DTAP is make sure your changes are well-tested before going on production. But if you can’t predict what’s gonna go on production, how are you supposed to manage the changes? If I can’t promote the same exact template, how else I should know that the newly generated template that’s about to go on production is correct or not?

Testing (unit or snapshot) would catch a broken template before it gets deployed, but isn’t point of DevOps reducing redundancies? Shouldn’t testing be part of the CI process, so it won’t have to be repeated during CD?

Occasionally? How frequently? And how is that helpful on an ephemeral environment such as a pipeline?

It happens when you import a resource outside of the current stack. For example you might import a VPC or DynamoDB Resource that was created elsewhere. Most of these happen as static functions like ‘Table.fromName()’ so you will know when it’s happening. I typically only allow the import locally, then commit the json file to git and disallow CDK to update it in CI. That way you know the value won’t change in pipeline.

The docs have a lot of information like this in them. There is also a book (https://www.thecdkbook.com) which is still very relevant and goes into great detail about some of the concepts you are asking about.

One approach is to automate package upgrades as a CI pipeline that creates a branch, updates packages, then runs all tests. If any snapshots change the tests will fail and a human can take a look. This is essentially DependaBot.

A well designed test will mock those critical dependencies. If an environment variable is important in the stack then mock it in your tests. Same as any other testing strategy.

IMO the thing that you are missing is that everything reusable should be a Construct.

You can build a Construct that encapsulates your entire infrastructure, and takes environment specific arguments to the constructor.

My stack files are very thin. They are constants declaring the environment specific values the Stack class, and its constructor contains my high level constructs that wrap up large pieces of infra into a single (or a few, it depends) object(s).

Docs on the Runtime Context

Edit: Added Runtime for clarity

It’s only applicable in the cases where you’re trying to resolve an already-existing resource outside of the stack. For the sake of argument, let’s leave them out of the discussion.

Context is irrelevant here, because context is injected during synthesise time.

The problem can be ignored in small teams, since the constructs are usually thin. When the team grows, and the number of reusable constructs grow, it’s essentially impossible to guarantee the synthisastion outcome of stacks using those constructs, unless they’re pinned and locked using a package manager, which, from a semantic perspective, is delegating the preservation of metadata to an unrelated system.

I’m trying to see how that it’s acceptable compared to the upsides CDK brings to the table.

I’m literally linking you to the docs with the answer to the question you asked.