Skip to content
v2.273.0

Amazon ECR Construct Library ​

This package contains constructs for working with Amazon Elastic Container Registry.

Repositories ​

Define a repository by creating a new instance of Repository. A repository holds multiple versions of a single container image.

ts
const repository = new ecr.Repository(this, 'Repository');
python
repository = ecr.Repository(self, "Repository")
java
Repository repository = new Repository(this, "Repository");
csharp
var repository = new Repository(this, "Repository");
go
repository := ecr.NewRepository(this, jsii.String("Repository"))

Image scanning ​

Amazon ECR image scanning helps in identifying software vulnerabilities in your container images. You can manually scan container images stored in Amazon ECR, or you can configure your repositories to scan images when you push them to a repository. To create a new repository to scan on push, simply enable imageScanOnPush in the properties.

ts
const repository = new ecr.Repository(this, 'Repo', {
  imageScanOnPush: true,
});
python
repository = ecr.Repository(self, "Repo",
    image_scan_on_push=True
)
java
Repository repository = Repository.Builder.create(this, "Repo")
        .imageScanOnPush(true)
        .build();
csharp
var repository = new Repository(this, "Repo", new RepositoryProps {
    ImageScanOnPush = true
});
go
repository := ecr.NewRepository(this, jsii.String("Repo"), &RepositoryProps{
	ImageScanOnPush: jsii.Boolean(true),
})

To create an onImageScanCompleted event rule and trigger the event target

ts
declare const repository: ecr.Repository;
declare const target: SomeTarget;

repository.onImageScanCompleted('ImageScanComplete')
  .addTarget(target);
python
# repository: ecr.Repository
# target: SomeTarget


repository.on_image_scan_completed("ImageScanComplete").add_target(target)
java
Repository repository;
SomeTarget target;


repository.onImageScanCompleted("ImageScanComplete").addTarget(target);
csharp
Repository repository;
SomeTarget target;


repository.OnImageScanCompleted("ImageScanComplete").AddTarget(target);
go
var repository Repository
var target someTarget


repository.OnImageScanCompleted(jsii.String("ImageScanComplete")).AddTarget(target)

Authorization Token ​

Besides the Amazon ECR APIs, ECR also allows the Docker CLI or a language-specific Docker library to push and pull images from an ECR repository. However, the Docker CLI does not support native IAM authentication methods and additional steps must be taken so that Amazon ECR can authenticate and authorize Docker push and pull requests. More information can be found at Registry Authentication.

A Docker authorization token can be obtained using the GetAuthorizationToken ECR API. The following code snippets grants an IAM user access to call this API.

ts
const user = new iam.User(this, 'User');
ecr.AuthorizationToken.grantRead(user);
python
user = iam.User(self, "User")
ecr.AuthorizationToken.grant_read(user)
java
User user = new User(this, "User");
AuthorizationToken.grantRead(user);
csharp
var user = new User(this, "User");
AuthorizationToken.GrantRead(user);
go
user := iam.NewUser(this, jsii.String("User"))
ecr.AuthorizationToken_GrantRead(user)

If you access images in the Public ECR Gallery as well, it is recommended you authenticate to the registry to benefit from higher rate and bandwidth limits.

See Pricing in https://aws.amazon.com/blogs/aws/amazon-ecr-public-a-new-public-container-registry/ and Service quotas.

The following code snippet grants an IAM user access to retrieve an authorization token for the public gallery.

ts
const user = new iam.User(this, 'User');
ecr.PublicGalleryAuthorizationToken.grantRead(user);
python
user = iam.User(self, "User")
ecr.PublicGalleryAuthorizationToken.grant_read(user)
java
User user = new User(this, "User");
PublicGalleryAuthorizationToken.grantRead(user);
csharp
var user = new User(this, "User");
PublicGalleryAuthorizationToken.GrantRead(user);
go
user := iam.NewUser(this, jsii.String("User"))
ecr.PublicGalleryAuthorizationToken_GrantRead(user)

This user can then proceed to login to the registry using one of the authentication methods.

Other Grantee ​

grantPush ​

The grantPush method grants the specified IAM entity (the grantee) permission to push images to the ECR repository. Specifically, it grants permissions for the following actions:

  • 'ecr:CompleteLayerUpload'
  • 'ecr:UploadLayerPart'
  • 'ecr:InitiateLayerUpload'
  • 'ecr:BatchCheckLayerAvailability'
  • 'ecr:PutImage'
  • 'ecr:GetAuthorizationToken'

Here is an example of granting a user push permissions:

ts
declare const repository: ecr.Repository;

const role = new iam.Role(this, 'Role', {
  assumedBy: new iam.ServicePrincipal('codebuild.amazonaws.com'),
});
repository.grantPush(role);
python
# repository: ecr.Repository


role = iam.Role(self, "Role",
    assumed_by=iam.ServicePrincipal("codebuild.amazonaws.com")
)
repository.grant_push(role)
java
Repository repository;


Role role = Role.Builder.create(this, "Role")
        .assumedBy(new ServicePrincipal("codebuild.amazonaws.com"))
        .build();
repository.grantPush(role);
csharp
Repository repository;


var role = new Role(this, "Role", new RoleProps {
    AssumedBy = new ServicePrincipal("codebuild.amazonaws.com")
});
repository.GrantPush(role);
go
var repository Repository


role := iam.NewRole(this, jsii.String("Role"), &RoleProps{
	AssumedBy: iam.NewServicePrincipal(jsii.String("codebuild.amazonaws.com")),
})
repository.GrantPush(role)

grantPull ​

The grantPull method grants the specified IAM entity (the grantee) permission to pull images from the ECR repository. Specifically, it grants permissions for the following actions:

  • 'ecr:BatchCheckLayerAvailability'
  • 'ecr:GetDownloadUrlForLayer'
  • 'ecr:BatchGetImage'
  • 'ecr:GetAuthorizationToken'
ts
declare const repository: ecr.Repository;

const role = new iam.Role(this, 'Role', {
  assumedBy: new iam.ServicePrincipal('codebuild.amazonaws.com'),
});
repository.grantPull(role);
python
# repository: ecr.Repository


role = iam.Role(self, "Role",
    assumed_by=iam.ServicePrincipal("codebuild.amazonaws.com")
)
repository.grant_pull(role)
java
Repository repository;


Role role = Role.Builder.create(this, "Role")
        .assumedBy(new ServicePrincipal("codebuild.amazonaws.com"))
        .build();
repository.grantPull(role);
csharp
Repository repository;


var role = new Role(this, "Role", new RoleProps {
    AssumedBy = new ServicePrincipal("codebuild.amazonaws.com")
});
repository.GrantPull(role);
go
var repository Repository


role := iam.NewRole(this, jsii.String("Role"), &RoleProps{
	AssumedBy: iam.NewServicePrincipal(jsii.String("codebuild.amazonaws.com")),
})
repository.GrantPull(role)

grantPullPush ​

The grantPullPush method grants the specified IAM entity (the grantee) permission to both pull and push images from/to the ECR repository. Specifically, it grants permissions for all the actions required for pull and push permissions.

Here is an example of granting a user both pull and push permissions:

ts
declare const repository: ecr.Repository;

const role = new iam.Role(this, 'Role', {
  assumedBy: new iam.ServicePrincipal('codebuild.amazonaws.com'),
});
repository.grantPullPush(role);
python
# repository: ecr.Repository


role = iam.Role(self, "Role",
    assumed_by=iam.ServicePrincipal("codebuild.amazonaws.com")
)
repository.grant_pull_push(role)
java
Repository repository;


Role role = Role.Builder.create(this, "Role")
        .assumedBy(new ServicePrincipal("codebuild.amazonaws.com"))
        .build();
repository.grantPullPush(role);
csharp
Repository repository;


var role = new Role(this, "Role", new RoleProps {
    AssumedBy = new ServicePrincipal("codebuild.amazonaws.com")
});
repository.GrantPullPush(role);
go
var repository Repository


role := iam.NewRole(this, jsii.String("Role"), &RoleProps{
	AssumedBy: iam.NewServicePrincipal(jsii.String("codebuild.amazonaws.com")),
})
repository.GrantPullPush(role)

By using these methods, you can grant specific operational permissions on the ECR repository to IAM entities. This allows for proper management of access to the repository and ensures security.

Image tag immutability ​

You can set tag immutability on images in your repository using the imageTagMutability construct prop.

ts
new ecr.Repository(this, 'Repo', { imageTagMutability: ecr.TagMutability.IMMUTABLE });
python
ecr.Repository(self, "Repo", image_tag_mutability=ecr.TagMutability.IMMUTABLE)
java
Repository.Builder.create(this, "Repo").imageTagMutability(TagMutability.IMMUTABLE).build();
csharp
new Repository(this, "Repo", new RepositoryProps { ImageTagMutability = TagMutability.IMMUTABLE });
go
ecr.NewRepository(this, jsii.String("Repo"), &RepositoryProps{
	ImageTagMutability: ecr.TagMutability_IMMUTABLE,
})

Image tag mutability with exclusion filters ​

ECR supports more granular control over image tag mutability by allowing you to specify exclusion filters. This enables you to make your repository immutable while allowing specific tag patterns to remain mutable (or vice versa).

There are two new mutability options that work with exclusion filters:

  • MUTABLE_WITH_EXCLUSION: Tags are mutable by default, except those matching the exclusion filters
  • IMMUTABLE_WITH_EXCLUSION: Tags are immutable by default, except those matching the exclusion filters

Use ImageTagMutabilityExclusionFilter.wildcard() to create filters with wildcard patterns:

ts
// Make all tags immutable except for those starting with 'dev-' or 'test-'
new ecr.Repository(this, 'Repo', {
  imageTagMutability: ecr.TagMutability.IMMUTABLE_WITH_EXCLUSION,
  imageTagMutabilityExclusionFilters: [
    ecr.ImageTagMutabilityExclusionFilter.wildcard('dev-*'),
    ecr.ImageTagMutabilityExclusionFilter.wildcard('test-*'),
  ],
});
python
# Make all tags immutable except for those starting with 'dev-' or 'test-'
ecr.Repository(self, "Repo",
    image_tag_mutability=ecr.TagMutability.IMMUTABLE_WITH_EXCLUSION,
    image_tag_mutability_exclusion_filters=[
        ecr.ImageTagMutabilityExclusionFilter.wildcard("dev-*"),
        ecr.ImageTagMutabilityExclusionFilter.wildcard("test-*")
    ]
)
java
// Make all tags immutable except for those starting with 'dev-' or 'test-'
// Make all tags immutable except for those starting with 'dev-' or 'test-'
Repository.Builder.create(this, "Repo")
        .imageTagMutability(TagMutability.IMMUTABLE_WITH_EXCLUSION)
        .imageTagMutabilityExclusionFilters(List.of(ImageTagMutabilityExclusionFilter.wildcard("dev-*"), ImageTagMutabilityExclusionFilter.wildcard("test-*")))
        .build();
csharp
// Make all tags immutable except for those starting with 'dev-' or 'test-'
// Make all tags immutable except for those starting with 'dev-' or 'test-'
new Repository(this, "Repo", new RepositoryProps {
    ImageTagMutability = TagMutability.IMMUTABLE_WITH_EXCLUSION,
    ImageTagMutabilityExclusionFilters = new [] { ImageTagMutabilityExclusionFilter.Wildcard("dev-*"), ImageTagMutabilityExclusionFilter.Wildcard("test-*") }
});
go
// Make all tags immutable except for those starting with 'dev-' or 'test-'
// Make all tags immutable except for those starting with 'dev-' or 'test-'
ecr.NewRepository(this, jsii.String("Repo"), &RepositoryProps{
	ImageTagMutability: ecr.TagMutability_IMMUTABLE_WITH_EXCLUSION,
	ImageTagMutabilityExclusionFilters: []ImageTagMutabilityExclusionFilter{
		ecr.ImageTagMutabilityExclusionFilter_Wildcard(jsii.String("dev-*")),
		ecr.ImageTagMutabilityExclusionFilter_*Wildcard(jsii.String("test-*")),
	},
})
ts
// Make all tags mutable except for production releases
new ecr.Repository(this, 'Repo', {
  imageTagMutability: ecr.TagMutability.MUTABLE_WITH_EXCLUSION,
  imageTagMutabilityExclusionFilters: [
    ecr.ImageTagMutabilityExclusionFilter.wildcard('prod-*'),
    ecr.ImageTagMutabilityExclusionFilter.wildcard('release-v*'),
  ],
});
python
# Make all tags mutable except for production releases
ecr.Repository(self, "Repo",
    image_tag_mutability=ecr.TagMutability.MUTABLE_WITH_EXCLUSION,
    image_tag_mutability_exclusion_filters=[
        ecr.ImageTagMutabilityExclusionFilter.wildcard("prod-*"),
        ecr.ImageTagMutabilityExclusionFilter.wildcard("release-v*")
    ]
)
java
// Make all tags mutable except for production releases
// Make all tags mutable except for production releases
Repository.Builder.create(this, "Repo")
        .imageTagMutability(TagMutability.MUTABLE_WITH_EXCLUSION)
        .imageTagMutabilityExclusionFilters(List.of(ImageTagMutabilityExclusionFilter.wildcard("prod-*"), ImageTagMutabilityExclusionFilter.wildcard("release-v*")))
        .build();
csharp
// Make all tags mutable except for production releases
// Make all tags mutable except for production releases
new Repository(this, "Repo", new RepositoryProps {
    ImageTagMutability = TagMutability.MUTABLE_WITH_EXCLUSION,
    ImageTagMutabilityExclusionFilters = new [] { ImageTagMutabilityExclusionFilter.Wildcard("prod-*"), ImageTagMutabilityExclusionFilter.Wildcard("release-v*") }
});
go
// Make all tags mutable except for production releases
// Make all tags mutable except for production releases
ecr.NewRepository(this, jsii.String("Repo"), &RepositoryProps{
	ImageTagMutability: ecr.TagMutability_MUTABLE_WITH_EXCLUSION,
	ImageTagMutabilityExclusionFilters: []ImageTagMutabilityExclusionFilter{
		ecr.ImageTagMutabilityExclusionFilter_Wildcard(jsii.String("prod-*")),
		ecr.ImageTagMutabilityExclusionFilter_*Wildcard(jsii.String("release-v*")),
	},
})
Exclusion filter pattern rules ​
  • Patterns can contain alphanumeric characters, dots (.), underscores (_), hyphens (-), and asterisks (*) as wildcards
  • Maximum pattern length is 128 characters
  • You can specify up to 5 exclusion filters per repository

Encryption ​

By default, Amazon ECR uses server-side encryption with Amazon S3-managed encryption keys which encrypts your data at rest using an AES-256 encryption algorithm. For more control over the encryption for your Amazon ECR repositories, you can use server-side encryption with KMS keys stored in AWS Key Management Service (AWS KMS). Read more about this feature in the ECR Developer Guide.

When you use AWS KMS to encrypt your data, you can either use the default AWS managed key, which is managed by Amazon ECR, by specifying RepositoryEncryption.KMS in the encryption property. Or specify your own customer managed KMS key, by specifying the encryptionKey property.

When encryptionKey is set, the encryption property must be KMS or empty.

In the case encryption is set to KMS but no encryptionKey is set, an AWS managed KMS key is used.

ts
new ecr.Repository(this, 'Repo', {
  encryption: ecr.RepositoryEncryption.KMS
});
python
ecr.Repository(self, "Repo",
    encryption=ecr.RepositoryEncryption.KMS
)
java
Repository.Builder.create(this, "Repo")
        .encryption(RepositoryEncryption.KMS)
        .build();
csharp
new Repository(this, "Repo", new RepositoryProps {
    Encryption = RepositoryEncryption.KMS
});
go
ecr.NewRepository(this, jsii.String("Repo"), &RepositoryProps{
	Encryption: ecr.RepositoryEncryption_KMS(),
})

Otherwise, a customer-managed KMS key is used if encryptionKey was set and encryption was optionally set to KMS.

ts
import * as kms from 'aws-cdk-lib/aws-kms';

new ecr.Repository(this, 'Repo', {
  encryptionKey: new kms.Key(this, 'Key'),
});
python
import aws_cdk.aws_kms as kms


ecr.Repository(self, "Repo",
    encryption_key=kms.Key(self, "Key")
)
java
import software.amazon.awscdk.services.kms.*;


Repository.Builder.create(this, "Repo")
        .encryptionKey(new Key(this, "Key"))
        .build();
csharp
using Amazon.CDK.AWS.KMS;


new Repository(this, "Repo", new RepositoryProps {
    EncryptionKey = new Key(this, "Key")
});
go
import kms "github.com/aws/aws-cdk-go/awscdk"


ecr.NewRepository(this, jsii.String("Repo"), &RepositoryProps{
	EncryptionKey: kms.NewKey(this, jsii.String("Key")),
})

Automatically clean up repositories ​

You can set life cycle rules to automatically clean up old images from your repository. The first life cycle rule that matches an image will be applied against that image. For example, the following deletes images older than 30 days, while keeping all images tagged with prod (note that the order is important here):

ts
declare const repository: ecr.Repository;
repository.addLifecycleRule({ tagPrefixList: ['prod'], maxImageCount: 9999 });
repository.addLifecycleRule({ maxImageAge: Duration.days(30) });
python
# repository: ecr.Repository

repository.add_lifecycle_rule(tag_prefix_list=["prod"], max_image_count=9999)
repository.add_lifecycle_rule(max_image_age=Duration.days(30))
java
Repository repository;

repository.addLifecycleRule(LifecycleRule.builder().tagPrefixList(List.of("prod")).maxImageCount(9999).build());
repository.addLifecycleRule(LifecycleRule.builder().maxImageAge(Duration.days(30)).build());
csharp
Repository repository;

repository.AddLifecycleRule(new LifecycleRule { TagPrefixList = new [] { "prod" }, MaxImageCount = 9999 });
repository.AddLifecycleRule(new LifecycleRule { MaxImageAge = Duration.Days(30) });
go
var repository Repository

repository.AddLifecycleRule(&LifecycleRule{
	TagPrefixList: []*string{
		jsii.String("prod"),
	},
	MaxImageCount: jsii.Number(9999),
})
repository.AddLifecycleRule(&LifecycleRule{
	MaxImageAge: awscdk.Duration_Days(jsii.Number(30)),
})

When using tagPatternList, an image is successfully matched if it matches the wildcard filter.

ts
declare const repository: ecr.Repository;
repository.addLifecycleRule({ tagPatternList: ['prod*'], maxImageCount: 9999 });
python
# repository: ecr.Repository

repository.add_lifecycle_rule(tag_pattern_list=["prod*"], max_image_count=9999)
java
Repository repository;

repository.addLifecycleRule(LifecycleRule.builder().tagPatternList(List.of("prod*")).maxImageCount(9999).build());
csharp
Repository repository;

repository.AddLifecycleRule(new LifecycleRule { TagPatternList = new [] { "prod*" }, MaxImageCount = 9999 });
go
var repository Repository

repository.AddLifecycleRule(&LifecycleRule{
	TagPatternList: []*string{
		jsii.String("prod*"),
	},
	MaxImageCount: jsii.Number(9999),
})

Repository deletion ​

When a repository is removed from a stack (or the stack is deleted), the ECR repository will be removed according to its removal policy (which by default will simply orphan the repository and leave it in your AWS account). If the removal policy is set to RemovalPolicy.DESTROY, the repository will be deleted as long as it does not contain any images.

To override this and force all images to get deleted during repository deletion, enable the emptyOnDelete option as well as setting the removal policy to RemovalPolicy.DESTROY.

ts
const repository = new ecr.Repository(this, 'MyTempRepo', {
      removalPolicy: RemovalPolicy.DESTROY,
      emptyOnDelete: true,
});
python
repository = ecr.Repository(self, "MyTempRepo",
    removal_policy=RemovalPolicy.DESTROY,
    empty_on_delete=True
)
java
Repository repository = Repository.Builder.create(this, "MyTempRepo")
        .removalPolicy(RemovalPolicy.DESTROY)
        .emptyOnDelete(true)
        .build();
csharp
var repository = new Repository(this, "MyTempRepo", new RepositoryProps {
    RemovalPolicy = RemovalPolicy.DESTROY,
    EmptyOnDelete = true
});
go
repository := ecr.NewRepository(this, jsii.String("MyTempRepo"), &RepositoryProps{
	RemovalPolicy: awscdk.RemovalPolicy_DESTROY,
	EmptyOnDelete: jsii.Boolean(true),
})

Managing the Resource Policy ​

You can add statements to the resource policy of the repository using the addToResourcePolicy method. However, be advised that you must not include a resources section in the PolicyStatement.

ts
declare const repository: ecr.Repository;
repository.addToResourcePolicy(new iam.PolicyStatement({
  actions: ['ecr:GetDownloadUrlForLayer'],
  // resources: ['*'], // not currently allowed!
  principals: [new iam.AnyPrincipal()],
}));
python
# repository: ecr.Repository

repository.add_to_resource_policy(iam.PolicyStatement(
    actions=["ecr:GetDownloadUrlForLayer"],
    # resources: ['*'], // not currently allowed!
    principals=[iam.AnyPrincipal()]
))
java
Repository repository;

repository.addToResourcePolicy(PolicyStatement.Builder.create()
        .actions(List.of("ecr:GetDownloadUrlForLayer"))
        // resources: ['*'], // not currently allowed!
        .principals(List.of(new AnyPrincipal()))
        .build());
csharp
Repository repository;

repository.AddToResourcePolicy(new PolicyStatement(new PolicyStatementProps {
    Actions = new [] { "ecr:GetDownloadUrlForLayer" },
    // resources: ['*'], // not currently allowed!
    Principals = new [] { new AnyPrincipal() }
}));
go
var repository Repository

repository.AddToResourcePolicy(iam.NewPolicyStatement(&PolicyStatementProps{
	Actions: []*string{
		jsii.String("ecr:GetDownloadUrlForLayer"),
	},
	// resources: ['*'], // not currently allowed!
	Principals: []IPrincipal{
		iam.NewAnyPrincipal(),
	},
}))

Import existing repository ​

You can import an existing repository into your CDK app using the Repository.fromRepositoryArn, Repository.fromRepositoryName or Repository.fromLookup method. These methods take the ARN or the name of the repository and returns an IRepository object.

ts
// import using repository name
const repositoryFromName = ecr.Repository.fromRepositoryName(this, 'ImportedRepoByName', 'my-repo-name');

// import using repository ARN
const repositoryFromArn = ecr.Repository.fromRepositoryArn(this, 'ImportedRepoByArn', 'arn:aws:ecr:us-east-1:123456789012:repository/my-repo-name');

// import using repository lookup
// You have to provide either `repositoryArn` or `repositoryName` to lookup the repository
const repositoryFromLookup = ecr.Repository.fromLookup(this, 'ImportedRepoByLookup', {
  repositoryArn: 'arn:aws:ecr:us-east-1:123456789012:repository/my-repo-name',
  repositoryName: 'my-repo-name',
});
python
# import using repository name
repository_from_name = ecr.Repository.from_repository_name(self, "ImportedRepoByName", "my-repo-name")

# import using repository ARN
repository_from_arn = ecr.Repository.from_repository_arn(self, "ImportedRepoByArn", "arn:aws:ecr:us-east-1:123456789012:repository/my-repo-name")

# import using repository lookup
# You have to provide either `repositoryArn` or `repositoryName` to lookup the repository
repository_from_lookup = ecr.Repository.from_lookup(self, "ImportedRepoByLookup",
    repository_arn="arn:aws:ecr:us-east-1:123456789012:repository/my-repo-name",
    repository_name="my-repo-name"
)
java
// import using repository name
IRepository repositoryFromName = Repository.fromRepositoryName(this, "ImportedRepoByName", "my-repo-name");

// import using repository ARN
IRepository repositoryFromArn = Repository.fromRepositoryArn(this, "ImportedRepoByArn", "arn:aws:ecr:us-east-1:123456789012:repository/my-repo-name");

// import using repository lookup
// You have to provide either `repositoryArn` or `repositoryName` to lookup the repository
IRepository repositoryFromLookup = Repository.fromLookup(this, "ImportedRepoByLookup", RepositoryLookupOptions.builder()
        .repositoryArn("arn:aws:ecr:us-east-1:123456789012:repository/my-repo-name")
        .repositoryName("my-repo-name")
        .build());
csharp
// import using repository name
var repositoryFromName = Repository.FromRepositoryName(this, "ImportedRepoByName", "my-repo-name");

// import using repository ARN
var repositoryFromArn = Repository.FromRepositoryArn(this, "ImportedRepoByArn", "arn:aws:ecr:us-east-1:123456789012:repository/my-repo-name");

// import using repository lookup
// You have to provide either `repositoryArn` or `repositoryName` to lookup the repository
var repositoryFromLookup = Repository.FromLookup(this, "ImportedRepoByLookup", new RepositoryLookupOptions {
    RepositoryArn = "arn:aws:ecr:us-east-1:123456789012:repository/my-repo-name",
    RepositoryName = "my-repo-name"
});
go
// import using repository name
repositoryFromName := ecr.Repository_FromRepositoryName(this, jsii.String("ImportedRepoByName"), jsii.String("my-repo-name"))

// import using repository ARN
repositoryFromArn := ecr.Repository_FromRepositoryArn(this, jsii.String("ImportedRepoByArn"), jsii.String("arn:aws:ecr:us-east-1:123456789012:repository/my-repo-name"))

// import using repository lookup
// You have to provide either `repositoryArn` or `repositoryName` to lookup the repository
repositoryFromLookup := ecr.Repository_FromLookup(this, jsii.String("ImportedRepoByLookup"), &RepositoryLookupOptions{
	RepositoryArn: jsii.String("arn:aws:ecr:us-east-1:123456789012:repository/my-repo-name"),
	RepositoryName: jsii.String("my-repo-name"),
})

CloudWatch event rules ​

You can publish repository events to a CloudWatch event rule with onEvent:

ts
import * as lambda from 'aws-cdk-lib/aws-lambda';
import { LambdaFunction } from 'aws-cdk-lib/aws-events-targets';

const repo = new ecr.Repository(this, 'Repo');
const lambdaHandler = new lambda.Function(this, 'LambdaFunction', {
  runtime: lambda.Runtime.PYTHON_3_12,
  code: lambda.Code.fromInline('# dummy func'),
  handler: 'index.handler',
});

repo.onEvent('OnEventTargetLambda', {
  target: new LambdaFunction(lambdaHandler),
});
python
import aws_cdk.aws_lambda as lambda_
from aws_cdk.aws_events_targets import LambdaFunction


repo = ecr.Repository(self, "Repo")
lambda_handler = lambda_.Function(self, "LambdaFunction",
    runtime=lambda_.Runtime.PYTHON_3_12,
    code=lambda_.Code.from_inline("# dummy func"),
    handler="index.handler"
)

repo.on_event("OnEventTargetLambda",
    target=LambdaFunction(lambda_handler)
)
java
import software.amazon.awscdk.services.lambda.*;
import software.amazon.awscdk.services.events.targets.LambdaFunction;


Repository repo = new Repository(this, "Repo");
Function lambdaHandler = Function.Builder.create(this, "LambdaFunction")
        .runtime(Runtime.PYTHON_3_12)
        .code(Code.fromInline("# dummy func"))
        .handler("index.handler")
        .build();

repo.onEvent("OnEventTargetLambda", OnEventOptions.builder()
        .target(new LambdaFunction(lambdaHandler))
        .build());
csharp
using Amazon.CDK.AWS.Lambda;
using Amazon.CDK.AWS.Events.Targets;


var repo = new Repository(this, "Repo");
var lambdaHandler = new Function(this, "LambdaFunction", new FunctionProps {
    Runtime = Runtime.PYTHON_3_12,
    Code = Code.FromInline("# dummy func"),
    Handler = "index.handler"
});

repo.OnEvent("OnEventTargetLambda", new OnEventOptions {
    Target = new LambdaFunction(lambdaHandler)
});
go
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"


repo := ecr.NewRepository(this, jsii.String("Repo"))
lambdaHandler := lambda.NewFunction(this, jsii.String("LambdaFunction"), &FunctionProps{
	Runtime: lambda.Runtime_PYTHON_3_12(),
	Code: lambda.Code_FromInline(jsii.String("# dummy func")),
	Handler: jsii.String("index.handler"),
})

repo.OnEvent(jsii.String("OnEventTargetLambda"), &OnEventOptions{
	Target: awscdk.NewLambdaFunction(lambdaHandler),
})

Mixins ​

ECR provides mixins that can be applied to L1 and L2 constructs.

RepositoryAutoDeleteImages ​

Automatically deletes all images from a repository when it is removed from the stack or when the stack is deleted. Requires the repository's removal policy to be set to DESTROY:

ts
new ecr.CfnRepository(this, 'Repo')
  .with(new ecr.mixins.RepositoryAutoDeleteImages());
python
ecr.CfnRepository(self, "Repo").with(ecr.mixins.RepositoryAutoDeleteImages())
java
new CfnRepository(this, "Repo").with(new RepositoryAutoDeleteImages());
csharp
new CfnRepository(this, "Repo").With(new Mixins.RepositoryAutoDeleteImages());
go
ecr.NewCfnRepository(this, jsii.String("Repo")).With(mixins.NewRepositoryAutoDeleteImages())

Types ​

NameKindSummary
RepositoryConstruct (L2)Define an ECR repository.
RepositoryBaseConstruct (L2)Base class for ECR repository.
CfnPublicRepositoryConstruct (L1)The AWS::ECR::PublicRepository resource specifies an Amazon Elastic Container Registry Public (Amazon ECR Public) repository, where users can push and pull Docker images, Open Container Initiative (OCI) images, and OCI compatible artifacts.
CfnPullThroughCacheRuleConstruct (L1)The AWS::ECR::PullThroughCacheRule resource creates or updates a pull through cache rule.
CfnPullTimeUpdateExclusionConstruct (L1)The ARN of the IAM principal to remove from the pull time update exclusion list.
CfnRegistryPolicyConstruct (L1)The AWS::ECR::RegistryPolicy resource creates or updates the permissions policy for a private registry.
CfnRegistryScanningConfigurationConstruct (L1)The scanning configuration for a private registry.
CfnReplicationConfigurationConstruct (L1)The AWS::ECR::ReplicationConfiguration resource creates or updates the replication configuration for a private registry.
CfnRepositoryConstruct (L1)The AWS::ECR::Repository resource specifies an Amazon Elastic Container Registry (Amazon ECR) repository, where users can push and pull Docker images, Open Container Initiative (OCI) images, and OCI compatible artifacts.
CfnRepositoryCreationTemplateConstruct (L1)The details of the repository creation template associated with the request.
CfnSigningConfigurationConstruct (L1)The signing configuration for a registry, which specifies rules for automatically signing images when pushed.
AuthorizationTokenClassAuthorization token to access private ECR repositories in the current environment via Docker CLI.
CfnPublicRepository.RepositoryCatalogDataPropertyStructThe details about the repository that are publicly visible in the Amazon ECR Public Gallery.
CfnPublicRepositoryPropsStructProperties for defining a CfnPublicRepository.
CfnPullThroughCacheRulePropsStructProperties for defining a CfnPullThroughCacheRule.
CfnPullTimeUpdateExclusionPropsStructProperties for defining a CfnPullTimeUpdateExclusion.
CfnRegistryPolicyPropsStructProperties for defining a CfnRegistryPolicy.
CfnRegistryScanningConfiguration.RepositoryFilterPropertyStructThe filter settings used with image replication.
CfnRegistryScanningConfiguration.ScanningRulePropertyStructThe scanning rules associated with the registry.
CfnRegistryScanningConfigurationPropsStructProperties for defining a CfnRegistryScanningConfiguration.
CfnReplicationConfiguration.ReplicationConfigurationPropertyStructThe replication configuration for a registry.
CfnReplicationConfiguration.ReplicationDestinationPropertyStructAn array of objects representing the destination for a replication rule.
CfnReplicationConfiguration.ReplicationRulePropertyStructAn array of objects representing the replication destinations and repository filters for a replication configuration.
CfnReplicationConfiguration.RepositoryFilterPropertyStructThe filter settings used with image replication.
CfnReplicationConfigurationPropsStructProperties for defining a CfnReplicationConfiguration.
CfnRepository.EncryptionConfigurationPropertyStructThe encryption configuration for the repository. This determines how the contents of your repository are encrypted at rest.
CfnRepository.ImageScanningConfigurationPropertyStructThe image scanning configuration for a repository.
CfnRepository.ImageTagMutabilityExclusionFilterPropertyStructA filter that specifies which image tags should be excluded from the repository's image tag mutability setting.
CfnRepository.LifecyclePolicyPropertyStructThe LifecyclePolicy property type specifies a lifecycle policy.
CfnRepositoryCreationTemplate.EncryptionConfigurationPropertyStructThe encryption configuration for the repository. This determines how the contents of your repository are encrypted at rest.
CfnRepositoryCreationTemplate.ImageTagMutabilityExclusionFilterPropertyStructA filter that specifies which image tags should be excluded from the repository's image tag mutability setting.
CfnRepositoryCreationTemplatePropsStructProperties for defining a CfnRepositoryCreationTemplate.
CfnRepositoryPropsStructProperties for defining a CfnRepository.
CfnSigningConfiguration.RepositoryFilterPropertyStructA repository filter used to determine which repositories have their images automatically signed on push.
CfnSigningConfiguration.RulePropertyStructA signing rule that specifies a signing profile and optional repository filters.
CfnSigningConfigurationPropsStructProperties for defining a CfnSigningConfiguration.
ImageTagMutabilityExclusionFilterClassRepresents an image tag mutability exclusion filter for ECR repository.
IRepositoryInterfaceRepresents an ECR repository.
LifecycleRuleStructAn ECR life cycle rule.
OnCloudTrailImagePushedOptionsStructOptions for the onCloudTrailImagePushed method.
OnImageScanCompletedOptionsStructOptions for the OnImageScanCompleted method.
PublicGalleryAuthorizationTokenClassAuthorization token to access the global public ECR Gallery via Docker CLI.
RepositoryAttributesStruct
RepositoryEncryptionClassIndicates whether server-side encryption is enabled for the object, and whether that encryption is from the AWS Key Management Service (AWS KMS) or from Amazon S3 managed encryption (SSE-S3).
RepositoryLookupOptionsStructProperties for looking up an existing Repository.
RepositoryPropsStruct
TagMutabilityEnumThe tag mutability setting for your repository.
TagStatusEnumSelect images based on tags.