A CDK construct to build and push Docker images to an ECR repository using CodeBuild and Lambda custom resources, then retrieve the final image tag so that ECS/Lambda references use the exact digest.
import { TokenInjectableDockerBuilder } from 'token-injectable-docker-builder'
new TokenInjectableDockerBuilder(scope: Construct, id: string, props: TokenInjectableDockerBuilderProps)| Name | Type | Description |
|---|---|---|
scope |
constructs.Construct |
The scope in which to define this construct. |
id |
string |
The scoped construct ID. |
props |
TokenInjectableDockerBuilderProps |
Configuration for building and pushing the Docker image. |
- Type: constructs.Construct
The scope in which to define this construct.
- Type: string
The scoped construct ID.
Configuration for building and pushing the Docker image.
| Name | Description |
|---|---|
toString |
Returns a string representation of this construct. |
with |
Applies one or more mixins to this construct. |
public toString(): stringReturns a string representation of this construct.
public with(mixins: ...IMixin[]): IConstructApplies one or more mixins to this construct.
Mixins are applied in order. The list of constructs is captured at the
start of the call, so constructs added by a mixin will not be visited.
Use multiple with() calls if subsequent mixins should apply to added
constructs.
- Type: ...constructs.IMixin[]
The mixins to apply.
| Name | Description |
|---|---|
isConstruct |
Checks if x is a construct. |
import { TokenInjectableDockerBuilder } from 'token-injectable-docker-builder'
TokenInjectableDockerBuilder.isConstruct(x: any)Checks if x is a construct.
Use this method instead of instanceof to properly detect Construct
instances, even when the construct library is symlinked.
Explanation: in JavaScript, multiple copies of the constructs library on
disk are seen as independent, completely different libraries. As a
consequence, the class Construct in each copy of the constructs library
is seen as a different class, and an instance of one class will not test as
instanceof the other class. npm install will not create installations
like this, but users may manually symlink construct libraries together or
use a monorepo tool: in those cases, multiple copies of the constructs
library can be accidentally installed, and instanceof will behave
unpredictably. It is safest to avoid using instanceof, and using
this type-testing method instead.
- Type: any
Any object.
| Name | Type | Description |
|---|---|---|
node |
constructs.Node |
The tree node. |
containerImage |
aws-cdk-lib.aws_ecs.ContainerImage |
An ECS-compatible container image referencing the tag of the built Docker image. |
dockerImageCode |
aws-cdk-lib.aws_lambda.DockerImageCode |
A Lambda-compatible DockerImageCode referencing the tag of the built Docker image. |
public readonly node: Node;- Type: constructs.Node
The tree node.
public readonly containerImage: ContainerImage;- Type: aws-cdk-lib.aws_ecs.ContainerImage
An ECS-compatible container image referencing the tag of the built Docker image.
public readonly dockerImageCode: DockerImageCode;- Type: aws-cdk-lib.aws_lambda.DockerImageCode
A Lambda-compatible DockerImageCode referencing the tag of the built Docker image.
Shared provider for TokenInjectableDockerBuilder instances.
Creates the onEvent and isComplete Lambda functions once per stack. Each builder instance registers its CodeBuild project ARN so the shared Lambdas have permission to start builds and read logs.
| Name | Description |
|---|---|
toString |
Returns a string representation of this construct. |
with |
Applies one or more mixins to this construct. |
registerProject |
Grant the shared Lambdas permission to start builds for a specific CodeBuild project and pull/push to its ECR repository. |
public toString(): stringReturns a string representation of this construct.
public with(mixins: ...IMixin[]): IConstructApplies one or more mixins to this construct.
Mixins are applied in order. The list of constructs is captured at the
start of the call, so constructs added by a mixin will not be visited.
Use multiple with() calls if subsequent mixins should apply to added
constructs.
- Type: ...constructs.IMixin[]
The mixins to apply.
public registerProject(project: Project, ecrRepo: Repository, encryptionKey?: Key): voidGrant the shared Lambdas permission to start builds for a specific CodeBuild project and pull/push to its ECR repository.
- Type: aws-cdk-lib.aws_codebuild.Project
- Type: aws-cdk-lib.aws_ecr.Repository
- Type: aws-cdk-lib.aws_kms.Key
| Name | Description |
|---|---|
isConstruct |
Checks if x is a construct. |
getOrCreate |
Get or create the singleton provider for this stack. |
import { TokenInjectableDockerBuilderProvider } from 'token-injectable-docker-builder'
TokenInjectableDockerBuilderProvider.isConstruct(x: any)Checks if x is a construct.
Use this method instead of instanceof to properly detect Construct
instances, even when the construct library is symlinked.
Explanation: in JavaScript, multiple copies of the constructs library on
disk are seen as independent, completely different libraries. As a
consequence, the class Construct in each copy of the constructs library
is seen as a different class, and an instance of one class will not test as
instanceof the other class. npm install will not create installations
like this, but users may manually symlink construct libraries together or
use a monorepo tool: in those cases, multiple copies of the constructs
library can be accidentally installed, and instanceof will behave
unpredictably. It is safest to avoid using instanceof, and using
this type-testing method instead.
- Type: any
Any object.
import { TokenInjectableDockerBuilderProvider } from 'token-injectable-docker-builder'
TokenInjectableDockerBuilderProvider.getOrCreate(scope: Construct, props?: TokenInjectableDockerBuilderProviderProps)Get or create the singleton provider for this stack.
All TokenInjectableDockerBuilder instances in the same stack
share a single pair of Lambda functions.
- Type: constructs.Construct
| Name | Type | Description |
|---|---|---|
node |
constructs.Node |
The tree node. |
serviceToken |
string |
The service token used by CustomResource instances. |
public readonly node: Node;- Type: constructs.Node
The tree node.
public readonly serviceToken: string;- Type: string
The service token used by CustomResource instances.
Properties for the TokenInjectableDockerBuilder construct.
import { TokenInjectableDockerBuilderProps } from 'token-injectable-docker-builder'
const tokenInjectableDockerBuilderProps: TokenInjectableDockerBuilderProps = { ... }| Name | Type | Description |
|---|---|---|
path |
string |
The path to the directory containing the Dockerfile or source code. |
buildArgs |
{[ key: string ]: string} |
Build arguments to pass to the Docker build process. |
buildLogGroup |
aws-cdk-lib.aws_logs.ILogGroup |
CloudWatch log group for CodeBuild build logs. |
cacheDisabled |
boolean |
When true, disables Docker layer caching. |
completenessQueryInterval |
aws-cdk-lib.Duration |
The query interval for checking if the CodeBuild project has completed. |
dockerLoginSecretArn |
string |
The ARN of the AWS Secrets Manager secret containing Docker login credentials. |
ecrPullThroughCachePrefixes |
string[] |
ECR pull-through cache repository prefixes to grant pull access to. |
exclude |
string[] |
A list of file paths in the Docker directory to exclude from build. |
file |
string |
The name of the Dockerfile to use for the build. |
installCommands |
string[] |
Custom commands to run during the install phase of CodeBuild. |
kmsEncryption |
boolean |
Whether to enable KMS encryption for the ECR repository. |
maxImageCount |
number |
Maximum number of tagged images to retain in the ECR repository. |
platform |
string |
Target platform for the Docker image. |
preBuildCommands |
string[] |
Custom commands to run during the pre_build phase of CodeBuild. |
provider |
TokenInjectableDockerBuilderProvider |
Shared provider for the custom resource Lambdas. |
retainBuildLogs |
boolean |
When true, creates a CloudWatch log group outside of CloudFormation (/docker-builder/<projectName>) and directs CodeBuild output there. |
securityGroups |
aws-cdk-lib.aws_ec2.ISecurityGroup[] |
The security groups to attach to the CodeBuild project. |
subnetSelection |
aws-cdk-lib.aws_ec2.SubnetSelection |
The subnet selection to specify which subnets to use within the VPC. |
vpc |
aws-cdk-lib.aws_ec2.IVpc |
The VPC in which the CodeBuild project will be deployed. |
public readonly path: string;- Type: string
The path to the directory containing the Dockerfile or source code.
public readonly buildArgs: {[ key: string ]: string};- Type: {[ key: string ]: string}
Build arguments to pass to the Docker build process.
These are transformed into --build-arg KEY=VALUE flags.
Example
{
TOKEN: 'my-secret-token',
ENV: 'production'
}public readonly buildLogGroup: ILogGroup;- Type: aws-cdk-lib.aws_logs.ILogGroup
- Default: CodeBuild default logging (logs are deleted on rollback)
CloudWatch log group for CodeBuild build logs.
When provided with a RETAIN removal policy, build logs survive rollbacks and stack deletion for debugging.
public readonly cacheDisabled: boolean;- Type: boolean
- Default: false
When true, disables Docker layer caching.
Every build runs from scratch. Use for debugging, corrupted cache, or major dependency changes.
public readonly completenessQueryInterval: Duration;- Type: aws-cdk-lib.Duration
- Default: Duration.seconds(30)
The query interval for checking if the CodeBuild project has completed.
This determines how frequently the custom resource polls for build completion.
public readonly dockerLoginSecretArn: string;- Type: string
The ARN of the AWS Secrets Manager secret containing Docker login credentials.
This secret should store a JSON object with the following structure:
{
"username": "my-docker-username",
"password": "my-docker-password"
}If not provided (or not needed), the construct will skip Docker Hub login.
Note: The secret must be in the same region as the stack.
Example
'arn:aws:secretsmanager:us-east-1:123456789012:secret:DockerLoginSecret'public readonly ecrPullThroughCachePrefixes: string[];- Type: string[]
- Default: No pull-through cache access
ECR pull-through cache repository prefixes to grant pull access to.
Use when your Dockerfile references base images from ECR pull-through cache (e.g. docker-hub/library/node:20-slim, ghcr/org/image:tag). The CodeBuild role will be granted ecr:BatchGetImage, ecr:GetDownloadUrlForLayer, and ecr:BatchCheckLayerAvailability on repositories matching each prefix.
Example
['docker-hub', 'ghcr']public readonly exclude: string[];- Type: string[]
- Default: No file path exclusions
A list of file paths in the Docker directory to exclude from build.
Will use paths in .dockerignore file if present.
public readonly file: string;- Type: string
- Default: 'Dockerfile'
The name of the Dockerfile to use for the build.
Passed as --file to docker build.
Example
'Dockerfile.production'public readonly installCommands: string[];- Type: string[]
- Default: No additional install commands.
Custom commands to run during the install phase of CodeBuild.
Example:
installCommands: [
'echo "Updating package lists..."',
'apt-get update -y',
'echo "Installing required packages..."',
'apt-get install -y curl dnsutils',
],public readonly kmsEncryption: boolean;- Type: boolean
- Default: false
Whether to enable KMS encryption for the ECR repository.
If true, a KMS key will be created for encrypting ECR images.
If false, the repository will use AES-256 encryption.
public readonly maxImageCount: number;- Type: number
- Default: undefined - no count-based expiration; only untagged-after-30-days
Maximum number of tagged images to retain in the ECR repository.
WARNING: Lambda functions pin images by digest internally even when referenced by tag. Setting this can delete images that Lambda functions (and ECS tasks) are still pinned to, breaking the next configuration update with "Image ID cannot be found".
Leave undefined (the default) for production use. Untagged images are always cleaned up after 30 days regardless of this setting.
public readonly platform: string;- Type: string
- Default: 'linux/amd64'
Target platform for the Docker image.
When set to 'linux/arm64', the construct uses a native ARM/Graviton
CodeBuild instance for fast builds without emulation.
public readonly preBuildCommands: string[];- Type: string[]
- Default: No additional pre-build commands.
Custom commands to run during the pre_build phase of CodeBuild.
Example:
preBuildCommands: [
'echo "Fetching configuration from private API..."',
'curl -o config.json https://api.example.com/config',
],public readonly provider: TokenInjectableDockerBuilderProvider;- Type: TokenInjectableDockerBuilderProvider
- Default: A new provider is created per builder instance
Shared provider for the custom resource Lambdas.
Use TokenInjectableDockerBuilderProvider.getOrCreate(this) to create
a singleton that is shared across all builders in the same stack.
When omitted, each builder creates its own Lambdas (original behavior).
public readonly retainBuildLogs: boolean;- Type: boolean
- Default: false
When true, creates a CloudWatch log group outside of CloudFormation (/docker-builder/<projectName>) and directs CodeBuild output there.
Because the log group is managed imperatively (not by CloudFormation), it survives stack rollbacks and preserves full build logs for debugging. A 7-day retention policy is applied so old logs auto-expire.
Set to false after debugging to delete the log group and clean up.
public readonly securityGroups: ISecurityGroup[];- Type: aws-cdk-lib.aws_ec2.ISecurityGroup[]
- Default: No security groups are attached.
The security groups to attach to the CodeBuild project.
These define the network access rules for the CodeBuild project.
public readonly subnetSelection: SubnetSelection;- Type: aws-cdk-lib.aws_ec2.SubnetSelection
- Default: All subnets in the VPC are used.
The subnet selection to specify which subnets to use within the VPC.
Allows the user to select private, public, or isolated subnets.
public readonly vpc: IVpc;- Type: aws-cdk-lib.aws_ec2.IVpc
- Default: No VPC is attached, and the CodeBuild project will use public internet.
The VPC in which the CodeBuild project will be deployed.
If provided, the CodeBuild project will be launched within the specified VPC.
Options for creating a TokenInjectableDockerBuilderProvider.
import { TokenInjectableDockerBuilderProviderProps } from 'token-injectable-docker-builder'
const tokenInjectableDockerBuilderProviderProps: TokenInjectableDockerBuilderProviderProps = { ... }| Name | Type | Description |
|---|---|---|
queryInterval |
aws-cdk-lib.Duration |
How often the provider polls for build completion. |
public readonly queryInterval: Duration;- Type: aws-cdk-lib.Duration
- Default: Duration.seconds(30)
How often the provider polls for build completion.