Sub topic 19
Deploying with CDK Pipelines
This chapter covers how CDK Pipelines automates cdk deploy. It assumes you can already run cdk synth, cdk diff and cdk deploy, and that you understand bootstrapping, environments and stacks. You should also know basic Git workflows and what AWS CodePipeline is.
What CDK Pipelines is
CDK Pipelines is a CDK module (aws-cdk-lib/pipelines) that defines a continuous delivery pipeline as constructs. By default it creates an AWS CodePipeline pipeline, and CodeBuild projects run the build steps.
Running cdk deploy from a laptop works for learning. For a team it has problems:
- The deployer needs broad credentials for every account.
- Nothing guarantees that the tests ran.
- Nobody can easily tell which commit is in production.
A pipeline fixes these by making a Git push the only way to change an environment. The pipeline's own definition is also CDK code, so it lives in the same repository as the application.
How a pipeline run works
Every run follows the same fixed sequence of phases.
- Source fetches the commit from a Git provider such as GitHub, CodeCommit or Bitbucket.
- Build runs your install, build, test and
cdk synthcommands. The resultingcdk.outdirectory is the pipeline's artifact. Every later phase deploys this one cloud assembly, so what you tested is what you ship. - UpdatePipeline is the self-mutation step. The pipeline runs
cdk deployon its own stack. If the pipeline definition changed, the run restarts with the new definition. - Assets publishes Lambda bundles, Docker images and other files to the bootstrapped bucket and repository of each target environment.
- Stages deploy your application. Each stage deploys its stacks through CloudFormation.
Wrapping your stacks in a Stage
A pipeline deploys Stage constructs, not individual stacks. A stage is a group of stacks deployed together, and you instantiate it once per environment. This is how the same infrastructure reaches beta and prod with different accounts.
The AppStack below is the one from earlier chapters. Remove the new cdk.App() lines at the bottom of that file, because the entry point now creates the app.
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import {
CodePipeline,
CodePipelineSource,
ManualApprovalStep,
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', {
crossAccountKeys: true,
synth: new ShellStep('Synth', {
input: CodePipelineSource.connection('my-org/my-repo', 'main', {
connectionArn:
'arn:aws:codestar-connections:us-east-1:222222222222:connection/EXAMPLE',
}),
commands: ['npm ci', 'npm run build', 'npm test', 'npx cdk synth'],
}),
});
pipeline.addStage(
new AppStage(this, 'Beta', {
env: { account: '111111111111', region: 'us-east-1' },
}),
);
pipeline.addStage(
new AppStage(this, 'Prod', {
env: { account: '333333333333', region: 'us-east-1' },
}),
{ pre: [new ManualApprovalStep('PromoteToProd')] },
);
}
}
const app = new cdk.App();
new PipelineStack(app, 'PipelineStack', {
env: { account: '222222222222', region: 'us-east-1' },
});
app.synth();Points to note in this code:
- The synth step.
ShellStepruns ordinary shell commands in CodeBuild. Puttingnpm testbeforecdk synthmakes a failing test block every deployment. The last command must producecdk.out. Pipelines finds it automatically for a standard project layout. - The source.
CodePipelineSource.connectionuses an AWS CodeConnections (formerly CodeStar Connections) connection. You create that connection once in the console and authorize it with your Git provider. The ARN above is a placeholder. - The environments. The pipeline stack needs a concrete account and region. An environment-agnostic stack cannot set up cross-account deployment.
- The approval step.
preruns the step before the stage deploys. Usepostfor steps that run afterward, such as integration tests. - The Python version. It uses the same constructs with snakecase names:
CodePipeline,ShellStep, `addstage, andpre=[...]`.
Bootstrapping for pipelines
The pipeline deploys by assuming roles that bootstrapping created in each target environment. Those roles must trust the pipeline's account, or deployments fail with access errors.
# The pipeline account
cdk bootstrap aws://222222222222/us-east-1
# Each target account trusts the pipeline account
cdk bootstrap aws://111111111111/us-east-1 \
--trust 222222222222 \
--cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess
cdk bootstrap aws://333333333333/us-east-1 \
--trust 222222222222 \
--cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccessRun each command with credentials for the account being bootstrapped. The --cloudformation-execution-policies option sets the permissions CloudFormation has when it creates your resources. AdministratorAccess is used here to keep the example short. In real accounts, supply a narrower managed policy.
First deployment and self-mutation
Deploy the pipeline stack by hand once:
cdk deploy PipelineStackFrom then on, every push to main runs the pipeline. If you add a stage or change a build command, the UpdatePipeline phase applies that change before anything else. You never run cdk deploy on the pipeline again, except in cases like the one in the warning below.
If you want the pipeline never to modify itself, for example when a security policy requires manual review of pipeline changes, pass selfMutation: false. You then deploy pipeline changes by hand.
Gotchas and failure modes
- Missing
crossAccountKeys. The artifact bucket must be encrypted with a key the target accounts can use. WithoutcrossAccountKeys: true, cross-account deployments fail. The key costs a small monthly fee, so leave it off only for single-account pipelines. - Hard-coded environments. Stages with
envset deploy to that environment regardless of which credentials run the pipeline. Make sure the account IDs are correct before the first run. - Context lookups. A lookup such as
Vpc.fromLookupneeds the values incdk.context.json, and that file must be committed. The synth step in CodeBuild has no permission to look up resources in the target accounts. - Stateful resources. A pipeline deploys on every push, so a careless change can replace a resource. Keep
RemovalPolicy.RETAINon buckets and databases, and review thecdk diffoutput before merging. - Pipeline cost and time. Each pipeline run starts CodeBuild projects for synth, self-mutation and asset publishing. Many small stages make a run slower, so group related stacks into one stage.
Exercise
A pipeline deploys to a prod account in another AWS account. The Assets phase fails with an access denied error when it publishes files to prod. Name two things to check.
Show answer
First, check that the prod account was bootstrapped with --trust set to the pipeline account's ID, so the bootstrap roles can be assumed. Second, check that the pipeline sets crossAccountKeys: true, so the target account can decrypt the artifacts.
Exercise
Why does the pipeline deploy the cdk.out produced in the Build phase instead of running cdk synth again in each stage?
Show answer
Deploying one synthesized cloud assembly guarantees that every stage receives exactly the same templates and assets that were built and tested. Re-synthesizing in each stage could produce different output if dependencies or context changed between runs.