Sub topic 18
Deploying with CDK Pipelines
This chapter assumes you can run cdk synth and cdk deploy, and that your target environments are bootstrapped. It also assumes you know what a stack and a construct are.
Why a pipeline
Running cdk deploy from a laptop is fine for learning. In a team it is hard to audit and depends on one person's credentials. CDK Pipelines is a construct library that builds an AWS CodePipeline from your CDK code. The pipeline synthesizes the app, deploys it stage by stage, and updates itself when you change the pipeline definition. This last behavior is called self-mutation.
A minimal pipeline
A stage (cdk.Stage) groups the stacks that deploy together into one environment. The pipeline deploys one stage per target.
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { CodePipeline, CodePipelineSource, ShellStep } from 'aws-cdk-lib/pipelines';
import { AppStack } from './app-stack';
class AppStage extends cdk.Stage {
constructor(scope: Construct, id: string, props?: cdk.StageProps) {
super(scope, id, props);
new AppStack(this, 'AppStack');
}
}
export class PipelineStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const pipeline = new CodePipeline(this, 'Pipeline', {
synth: new ShellStep('Synth', {
input: CodePipelineSource.connection('my-org/my-repo', 'main', {
connectionArn: 'arn:aws:codestar-connections:us-east-1:123456789012:connection/EXAMPLE',
}),
commands: ['npm ci', 'npm run build', 'npx cdk synth'],
}),
});
pipeline.addStage(new AppStage(this, 'Prod', {
env: { account: '123456789012', region: 'us-east-1' },
}));
}
}You deploy the PipelineStack manually once. After that, every push to main runs the pipeline.
Cross-account deployments need extra bootstrap setup. Bootstrap each target account with --trust set to the pipeline's account, so the pipeline can assume the deployment roles.
Best practices
- Keep stateful resources safe. Set removal policies explicitly on buckets and databases, as you did with
RemovalPolicy.RETAIN. - Prefer L2 constructs and grant methods. Hand-written IAM policies drift and tend to be too broad.
- Commit
cdk.context.json. Cached lookups keep synthesis the same on every machine and in the pipeline. - Test before you deploy. Assertion tests on the synthesized template run in the synth step and catch regressions early.
- Run
cdk diffbefore deploy. Review IAM and replacement changes in particular. - Pass values through props. Share them across stacks with properties, not hard-coded names.
Common pitfalls
| Pitfall | Effect | Fix |
|---|---|---|
| Changing a logical ID by renaming or moving a construct | CloudFormation replaces the resource, which can destroy data | Check `cdk diff` and keep IDs stable |
| Branching on a token's value at synth time | The value is not known yet, so the code behaves wrongly | Use CloudFormation conditions or resolve the value at deploy time |
| Hard-coding names on stateful resources | Replacements fail because the name already exists | Let CDK generate names |
| Deploying to an environment that is not bootstrapped | Deploy fails for missing assets or roles | Run `cdk bootstrap` first |
Exercise
A teammate renames the construct ID of a database from 'Db' to 'Database' and pushes to the pipeline. Why is this risky, and how do you find out before it reaches production?
Show answer
The construct ID feeds the logical ID, so CloudFormation sees a new resource and may delete and recreate the old one, losing data. Run cdk diff, or review the template changes, to see the replacement. A RETAIN removal policy also protects the data.