AWS CDK ECR Assets

1.204.0 · active · verified Thu Apr 16

The `aws-cdk-aws-ecr-assets` library provides constructs for managing Docker image assets that are deployed to Amazon Elastic Container Registry (ECR). This package specifically targets AWS CDK v1 applications. It simplifies the process of building local Docker images and pushing them to ECR as part of your CDK deployment. The current version is `1.204.0`, following the frequent release cadence of the AWS CDK.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates creating a Docker image asset from a local directory containing a Dockerfile. During `cdk deploy`, this image will be built locally and pushed to an ECR repository. Ensure Docker is running when synthesizing or deploying.

import os
import aws_cdk as cdk
from aws_cdk.aws_ecr_assets import DockerImageAsset

# Create a dummy Dockerfile for the example
docker_context_path = "docker_context"
os.makedirs(docker_context_path, exist_ok=True)
with open(os.path.join(docker_context_path, "Dockerfile"), "w") as f:
    f.write("""
FROM public.ecr.aws/amazonlinux/amazonlinux:2
RUN echo "Hello from Docker!" > /app/hello.txt
CMD ["cat", "/app/hello.txt"]
""")

app = cdk.App()

class MyDockerImageStack(cdk.Stack):
    def __init__(self, scope: cdk.App, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # Creates a Docker image asset from the local 'docker_context' directory.
        # The Dockerfile within this directory will be used to build the image.
        docker_image_asset = DockerImageAsset(
            self, "MyDockerImageAsset",
            directory=docker_context_path,
            # repository_name="my-cdk-ecr-repo" # Optional: specify ECR repo name
        )

        cdk.CfnOutput(self, "ImageUri", value=docker_image_asset.image_uri)

MyDockerImageStack(app, "MyDockerImageStack")
app.synth()

# Optional: Clean up dummy Dockerfile and directory after synthesis/deployment
# os.remove(os.path.join(docker_context_path, "Dockerfile"))
# os.rmdir(docker_context_path)

view raw JSON →