Skip to content

Latest commit

 

History

History
775 lines (488 loc) · 29.6 KB

File metadata and controls

775 lines (488 loc) · 29.6 KB

API Reference

Constructs

TokenInjectableDockerBuilder

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.

Initializers

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.

scopeRequired
  • Type: constructs.Construct

The scope in which to define this construct.


idRequired
  • Type: string

The scoped construct ID.


propsRequired

Configuration for building and pushing the Docker image.


Methods

Name Description
toString Returns a string representation of this construct.
with Applies one or more mixins to this construct.

toString
public toString(): string

Returns a string representation of this construct.

with
public with(mixins: ...IMixin[]): IConstruct

Applies 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.

mixinsRequired
  • Type: ...constructs.IMixin[]

The mixins to apply.


Static Functions

Name Description
isConstruct Checks if x is a construct.

isConstruct
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.

xRequired
  • Type: any

Any object.


Properties

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.

nodeRequired
public readonly node: Node;
  • Type: constructs.Node

The tree node.


containerImageRequired
public readonly containerImage: ContainerImage;
  • Type: aws-cdk-lib.aws_ecs.ContainerImage

An ECS-compatible container image referencing the tag of the built Docker image.


dockerImageCodeRequired
public readonly dockerImageCode: DockerImageCode;
  • Type: aws-cdk-lib.aws_lambda.DockerImageCode

A Lambda-compatible DockerImageCode referencing the tag of the built Docker image.


TokenInjectableDockerBuilderProvider

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.

Methods

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.

toString
public toString(): string

Returns a string representation of this construct.

with
public with(mixins: ...IMixin[]): IConstruct

Applies 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.

mixinsRequired
  • Type: ...constructs.IMixin[]

The mixins to apply.


registerProject
public registerProject(project: Project, ecrRepo: Repository, encryptionKey?: Key): void

Grant the shared Lambdas permission to start builds for a specific CodeBuild project and pull/push to its ECR repository.

projectRequired
  • Type: aws-cdk-lib.aws_codebuild.Project

ecrRepoRequired
  • Type: aws-cdk-lib.aws_ecr.Repository

encryptionKeyOptional
  • Type: aws-cdk-lib.aws_kms.Key

Static Functions

Name Description
isConstruct Checks if x is a construct.
getOrCreate Get or create the singleton provider for this stack.

isConstruct
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.

xRequired
  • Type: any

Any object.


getOrCreate
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.

scopeRequired
  • Type: constructs.Construct

propsOptional

Properties

Name Type Description
node constructs.Node The tree node.
serviceToken string The service token used by CustomResource instances.

nodeRequired
public readonly node: Node;
  • Type: constructs.Node

The tree node.


serviceTokenRequired
public readonly serviceToken: string;
  • Type: string

The service token used by CustomResource instances.


Structs

TokenInjectableDockerBuilderProps

Properties for the TokenInjectableDockerBuilder construct.

Initializer

import { TokenInjectableDockerBuilderProps } from 'token-injectable-docker-builder'

const tokenInjectableDockerBuilderProps: TokenInjectableDockerBuilderProps = { ... }

Properties

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.

pathRequired
public readonly path: string;
  • Type: string

The path to the directory containing the Dockerfile or source code.


buildArgsOptional
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'
}
buildLogGroupOptional
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.


cacheDisabledOptional
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.


completenessQueryIntervalOptional
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.


dockerLoginSecretArnOptional
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'
ecrPullThroughCachePrefixesOptional
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']
excludeOptional
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.


fileOptional
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'
installCommandsOptional
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',
],

kmsEncryptionOptional
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.


maxImageCountOptional
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.


platformOptional
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.


preBuildCommandsOptional
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',
],

providerOptional
public readonly provider: TokenInjectableDockerBuilderProvider;

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).


retainBuildLogsOptional
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.


securityGroupsOptional
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.


subnetSelectionOptional
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.


vpcOptional
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.


TokenInjectableDockerBuilderProviderProps

Options for creating a TokenInjectableDockerBuilderProvider.

Initializer

import { TokenInjectableDockerBuilderProviderProps } from 'token-injectable-docker-builder'

const tokenInjectableDockerBuilderProviderProps: TokenInjectableDockerBuilderProviderProps = { ... }

Properties

Name Type Description
queryInterval aws-cdk-lib.Duration How often the provider polls for build completion.

queryIntervalOptional
public readonly queryInterval: Duration;
  • Type: aws-cdk-lib.Duration
  • Default: Duration.seconds(30)

How often the provider polls for build completion.