Skip to content

Container mode (two-repository Docker deploy)

Container mode splits build from deploy into two repositories: a CI repository builds and pushes a config-agnostic deployer image, and a config-only CD repository runs that image against as many targets as you like. One image drives N deployments, and rollback is a retag.

Engine support

Container mode is a feature of the default CodePipeline engine (EngineType.CODEPIPELINE). The CDK_PIPELINES and GitHubActions engines deploy stages directly by replaying the app per stage; they do not build or consume a deployer image.

When to use it

Reach for container mode when you want to build the deployable artifact once and promote that exact artifact through stages — including across repositories or teams — rather than re-synthesizing per stage from application source. Because the image bakes the CDK app and its npm dependencies, the deployer container itself needs no npm install or package-registry access. The small Repo 2 CodeBuild wrapper still runs npm ci in the config repository before launching that container, so its wrapper dependency must be available through public npm, codeArtifact, or npmRegistry.

Repo 1 — build the deployer image

The CI repository is your normal CDK app. Add a deployerImage to cicd.config.ts and the pipeline renders as Source → BuildImage with no deploy stages — it builds and pushes an image instead of deploying:

import { defineCICD, Repository, BuildImage, ImageTagStrategy } from '@cdklabs/cdk-cicd-wrapper';

export default defineCICD({
  application: 'my-app',
  repository: Repository.codestarConnection(
    'my-org/my-app',
    'arn:aws:codestar-connections:eu-west-1:111111111111:connection/01234567-89ab-cdef-0123-456789abcdef',
  ),
  // Validation stage: the image build synthesizes it (cdk-nag + config schema) with config/ci.json
  // before pushing. Deployment targets and their configuration live in Repo 2.
  stages: ['ci'],
  deployerImage: BuildImage.docker({
    dockerfile: 'Dockerfile', // default; the image payload is your app + deps, NOT cdk.out
    // repositoryName: 'my-app-deployer', // reference an existing ECR repo; omit to provision one
    // tagStrategy: ImageTagStrategy.GIT_SHA, // default: immutable revision tag; or ImageTagStrategy.LATEST
    // packageVersionTag: true, // also tag the image with package.json's version, e.g. 1.4.2
  }),
});

In deployerImage mode the stages are validation stages, and at least one is required. Before it builds the image, the pipeline synthesizes them with the image's own config/<stage>.json, so cdk-nag and your config schema run in CI. A failure stops the image from being pushed. Use ci.synthStages to validate only some of them. No deployment actions are rendered for these stages.

The deployment targets do not need to be declared here: the deployer container accepts any stage a Repo 2 target defines and uses that target's configuration (see below). Keep a representative config/ci.json in Repo 1 so the validation exercises the same code paths as a real environment.

cdk-cicd deploy-ci provisions the CI pipeline. Its single build project:

  1. runs npm ci and your audit/build/test scripts (CI as a validation gate),
  2. synthesizes the validation stages (cdk-cicd synth, so cdk-nag and the config schema run) and discards the assembly,
  3. logs in to ECR,
  4. docker builds your Dockerfile and pushes the image, tagged by strategy (GIT_SHA by default — the lowercase commit SHA for Git sources or a deterministic SHA-256 of another source revision; LATEST is simplest but not immutable).
  5. with packageVersionTag: true, adds the version from package.json (for example 1.4.2) as a second tag on the same image, so Repo 2 can pin "version": "1.4.2" instead of a commit SHA.

The repository stays immutable with packageVersionTag. ECR immutability stops an existing tag from moving to another image; it does not stop a new tag from being added to an image. So the version tag is added only while that version is unpublished:

  • A retried build whose version already names this image changes nothing.
  • A build whose version is already held by another image keeps only its commit-SHA tag and says so. Bump version in package.json to publish it under a version.
  • A version that is not a valid image tag (semver build metadata such as 1.4.2+7) fails the build.

1.4.2 therefore always names exactly one image, and promoting a release in Repo 2 means setting another target's version to the same value.

If you do not name an existing repository, the pipeline provisions one named <application>-deployer; a disposable pipeline (deploy-ci --disposable) empties and deletes it on teardown.

Why the image, not cdk.out

The image bakes code + dependencies but never cdk.out, so the CD side can synth-and-deploy it offline against any target's config. That is what collapses per-target pipeline sprawl: targets become config rows a single image is run against, not pipeline resources.

Repo 2 — deploy the image

The CD repository is a small, app-agnostic config repository (no CDK code). It declares which image to run and where to deploy it, via defineDeployment in a deploy.config.ts:

Pin the wrapper packages in Repo 2's lockfile and expose the installed CLI through a project script:

{
  "scripts": {
    "cdk-cicd": "cdk-cicd"
  }
}

The generated pipeline runs npm ci followed by npm run cdk-cicd -- deploy .... A missing dependency or script therefore fails deterministically; deployment never asks npx to fetch a registry version.

// deploy.config.ts
import { defineDeployment, Repository } from '@cdklabs/cdk-cicd-wrapper';

export default defineDeployment({
  // Repeat the deployer image's application/qualifier so Repo 2 can scope bootstrap-role IAM.
  application: 'my-app',
  qualifier: 'myapp',

  // The BASE deployer image repository (no tag). The per-stage version is appended at deploy time.
  image: '111111111111.dkr.ecr.eu-west-1.amazonaws.com/my-app-deployer',

  // The config-only source repo this CD pipeline watches (deploy.config.ts + config/<stage>.json).
  // Omit it to use only the local `cdk-cicd deploy --from-image` executor with no CD pipeline.
  repository: Repository.codecommit('my-app-deploy-config'),

  // Targets say WHERE (account/region/role) + gating. The VERSION each runs comes from config/<stage>.json.
  targets: [
    {
      stage: 'dev',
      env: { account: '111111111111', region: 'eu-west-1' },
      complianceLogBucketName: 'my-app-compliance-111111111111-eu-west-1',
    },
    {
      stage: 'int',
      env: { account: '111111111111', region: 'eu-west-1' },
      manualApproval: true,
      complianceLogBucketName: 'my-app-compliance-111111111111-eu-west-1',
    },
    {
      stage: 'prod',
      env: { account: '222222222222', regions: ['eu-west-1', 'us-east-1'] },
      manualApproval: true,
      deployment: { deployRole: 'arn:aws:iam::222222222222:role/automation-deployer' },
    },
  ],
});

application, qualifier, and synthesizer must match the image's cicd.config. Repo 1 may preserve APP_STAGING in the image because it only builds and pushes that image. The generated Repo 2 deployment pipeline rejects APP_STAGING; omit repository and run cdk-cicd deploy --from-image directly if the image requires it. That direct/local path supports a custom qualifier and custom deployment.deployRole / deployment.cfnExecutionRole identities for application stacks. The staging support resources deploy separately with caller/base credentials. A deploy-role ExternalId remains unsupported by the alpha deployment-identity API.

Compliance logging from the deployer container

Repo 2 can preserve application-bucket access logging by naming an existing destination with complianceLogBucketName. Set it on a target, as above, or once at the top level as the default for co-located targets. defineDeployment resolves each logged target to a complete bucket/account/Region triple and fails closed unless the target has a concrete 12-digit account and exactly one matching Region. Reusing one bucket name across different account/Region coordinates is also rejected.

Repo 2 does not create or manage these buckets. The owner must keep the required S3 log-delivery policy, SSE-S3 encryption, and other destination controls in place. At runtime the outer executor forwards CDK_CICD_COMPLIANCE_LOG_BUCKET_NAME, CDK_CICD_COMPLIANCE_LOG_BUCKET_ACCOUNT, and CDK_CICD_COMPLIANCE_LOG_BUCKET_REGION into Docker together; omitting logging explicitly clears all three so image-baked values cannot take control. A multi-Region target cannot use one destination bucket because S3 server access logging cannot cross Regions.

Each stage's version lives in its own config file in the CD repository (a hash or semver) — not baked in the image:

// config/dev.json          config/int.json           config/prod.json
{ "version": "1.5.0" }      { "version": "1.4.2" }     { "version": "1.4.2" }

The deploy resolves image = <base-repo>:<version from config/<stage>.json>, so dev can run a newer version than prod, and the version is plain config, reviewable in a pull request. If the file exists but is unreadable, malformed, or lacks a non-empty string version, deployment fails instead of silently falling back to the base image. Only an autoDeploy target may leave version out (see below).

version takes three forms:

version Deploys
0.2.34 exactly that tag
3aff301… exactly that commit-SHA tag
^0.1.0, ~0.2.0, 0.2.x, >=0.2.0 <0.3.0 the highest semver-tagged image that matches, pinned by digest

A range follows npm's rules: prereleases match only when the range names one, and tags that are not semver versions (commit SHAs, latest) are ignored. Only a value with a range operator or an x/* placeholder is a range, so a short all-digit commit hash stays a literal tag. Use packageVersionTag in Repo 1 so the image carries semver tags.

A range target counts as changed when a newer matching version is published, but the main pipeline runs on deploy-repository commits, so it moves on the next commit. Combine a range with autoDeploy to follow it on every push: the target then runs the newest image within its range, so a dev target on ^0.2.0 never jumps to 0.3.0. Git records the range, not the exact version; the deploy log names the version it resolved.

Account and Region from the config file

A target can leave env out of deploy.config.ts and take its account and Region from its config/<stage>.json:

// config/int.json
{ "version": "^1.4.0", "aws": { "accountId": "222222222222", "region": "eu-west-1" }, "ordersTableName": "orders-int" }
  • A value set in deploy.config.ts still wins. A config file that disagrees with it fails, naming the file and the target, instead of being silently ignored.
  • deploy-ci reads the file when it builds the pipeline, because the account and Region decide the pipeline's IAM grants. Changing them later makes Plan ask you to re-run deploy-ci.
  • aws.region names one Region. Declare a multi-Region target's Regions in deploy.config.ts.
  • A target with compliance logging (complianceLogBucketName, set on it or for the whole deployment) can take its account and Region from the file too. Its bucket is placed in that account and Region once the file is applied, and a target still missing either fails when the deployment is loaded.
  • An invalid aws value fails only its own target. Plan runs that target's stage and its deploy action names the error, while the other targets are planned and deployed as usual. deploy-ci fails on it.

Provision the CD pipeline, or run locally

With a repository set, cdk-cicd deploy-ci provisions the CD pipeline (the deploy-side twin of the CI deploy-ci): a Source stage, a Plan stage, then ordered deployment waves. Adjacent ungated targets share a parallel wave; each gated target gets its own approval/deploy stage. Declaration order is preserved, so a gate blocks that target and every target declared after it. Each deploy action runs cdk-cicd deploy --from-image --target <stage>, which reads that stage's version at run time, pulls <base-repo>:<version>, and synth-and-deploys the stage.

Only changed targets deploy

Every commit to the deploy repository starts the whole pipeline, so the pipeline decides per target whether there is anything to deploy:

  • After each successful deploy, the target's fingerprint is stored in an SSM parameter. The fingerprint is a SHA-256 over the target's deploy.config.ts entry, its image reference and version, the image's ECR digest (so re-pushing a tag counts as a change), the rest of its config/<stage>.json, and the deploy repository's package.json and lockfile.
  • The Plan stage (cdk-cicd pipeline plan) computes every target's fingerprint and compares it with the stored one. Each deployment stage has a CodePipeline entry condition that skips the stage when nothing in it changed. A skipped stage shows as Skipped in the console and runs none of its actions, so nobody is asked to approve a run that would change nothing.
  • A gate also guards the ungated targets declared right after it, up to the next gate. Its stage runs when one of them changed, even if the gated target did not, so they still wait for that approval. The gated target's own deploy action then finds it unchanged and skips it.
  • A target Plan cannot check (for example a malformed config/<stage>.json) counts as changed. Its stage runs, and its deploy action reports the real error.
  • Each deploy action checks the fingerprint once more right before deploying, which covers a deploy that happened while its approval was pending.
  • If deploy.config.ts changes something the pipeline was built from (targets, Regions, roles, registries), Plan fails and asks you to re-run cdk-cicd deploy-ci.

To ask for approval on every run, even when nothing changed, set alwaysApprove on a gated target:

{ stage: 'prod', env: { account: '222222222222', region: 'eu-west-1' }, manualApproval: true, alwaysApprove: true },

The deployer container gets the CodeBuild role's credentials from the container-credentials endpoint. No access key is written into the build's environment or its log.

For an image in an ECR account different from the Repo 2 pipeline, the repository owner must grant the generated Deploy CodeBuild role ecr:BatchGetImage, ecr:GetDownloadUrlForLayer, ecr:BatchCheckLayerAvailability and ecr:DescribeImages, and the generated Plan CodeBuild role ecr:DescribeImages. Both use it to resolve a mutable tag, a range or the newest autoDeploy image to an immutable digest for the change check. Without the Plan grant, Plan cannot check any target that uses such an image from that repository, so those targets' stages and approvals run on every commit. A target pinned by digest needs no lookup. Granting the pipeline account covers both roles. Set crossAccountEcrRepositoryPolicyConfigured: true only after that owner-side policy exists; otherwise pipeline rendering fails closed. This acknowledgement covers the deployer image pulled after the build starts. A private ECR image used as CodeBuild's own environment image must still be in the pipeline Region.

The same executor runs locally without any pipeline:

npm run cdk-cicd -- deploy --from-image           # every target (gated targets require --yes)
npm run cdk-cicd -- deploy --from-image --target dev

On a runner whose default Docker network cannot reach AWS, add --docker-network host. The local executor is fail-closed: it refuses a target with manualApproval: true unless you pass --yes.

Stage configuration from Repo 2

config/<stage>.json in Repo 2 can carry the target's full stage configuration next to its version:

{
  "version": "1.4.2",
  "featureFlags": { "newCheckout": true },
  "tags": { "environment": "int" },
  "ordersTableName": "orders-int"
}

When the file has any key besides version, it is the target's stage configuration:

  • version is reserved for the image tag and is removed before the configuration reaches the app.
  • The rest is mounted read-only into the container and selected with CONFIG_FILE. It replaces any config/<stage>.json baked into the image. The two are never merged.
  • Your app validates it with its own schema (AppConfig.of(this, { schema })) during synth, before any CloudFormation change. An invalid value fails with an error that names the key and the target.
  • Values such as resolve:secretsmanager:<arn> stay references and are resolved inside the container, exactly as for a baked configuration.

A file that holds only version keeps the previous behaviour: the image's baked configuration is used.

To change a target's configuration, commit a new config/<stage>.json. The same image tag redeploys with the new values and no image rebuild. To check every target against the image's schema without deploying, run the preflight. It needs no --yes, because it changes nothing:

npm run cdk-cicd -- deploy --from-image --validate-only
npm run cdk-cicd -- deploy --from-image --validate-only --target int

Deploy a target automatically on every new image

For a dev environment whose configuration does not change between image versions, set autoDeploy on its target. Every successful push to the target's ECR repository then deploys it, with no commit to the deploy repository:

targets: [
  { stage: 'dev', env: { account: '111111111111', region: 'eu-west-1' }, autoDeploy: true },
  { stage: 'int', env: { account: '111111111111', region: 'eu-west-1' }, manualApproval: true },
],
  • cdk-cicd deploy-ci adds a small pipeline for that target. An EventBridge rule on ECR pushes starts it, and it deploys only that target. The main pipeline keeps running on deploy repository commits, so other targets and their approval gates are never touched by an image push.
  • An autoDeploy target always runs the newest tagged image in its repository, from either pipeline. Its config/<stage>.json needs no version: an exact version there is not used, and a range still limits which images it follows. A version that is present must still be a valid non-empty string. The rest of that file is still its stage configuration, and a commit that changes it redeploys the target as usual.
  • The target must have no manual approval, and its ECR repository must be in the CD pipeline's own account and Region (ECR push events are delivered only to the local event bus).
  • If a new image needs a configuration change, its deployment fails at the validation synth, before any CloudFormation change, until config/<stage>.json is updated.
  • The running version of an autoDeploy target is not recorded in Git. To pin it again, remove autoDeploy, set version, and re-run deploy-ci.

Division of authority: WHAT vs WHERE

The image is authoritative for what to deploy: the app code, its stacks, and the schema of its configuration. The deploy repository is authoritative for where and with which configuration. The deploy.config.ts target sets the account, region(s), forced roles and approval, and config/<stage>.json sets the version and stage configuration. Each run pins a single --region, so the CD repository, not the image, decides the deployment topology. An image may still declare stages and bake configuration; Repo 2 values win whenever it supplies them.

Rollback is a retag

To roll back, point a stage's version file at the previous tag (e.g. config/prod.json's version back to 1.4.1) and re-run. Because the image pins code + deps and config supplies the lookups, the same image

  • same config always synthesizes the same template — a deterministic rollback with no rebuild.

See also