AWSCDK::ECR

1 namespaces · 33 types

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.

repository = AWSCDK::ECR::Repository.new(self, "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 image_scan_on_push in the properties.

repository = AWSCDK::ECR::Repository.new(self, "Repo", {
    image_scan_on_push: true,
})

To create an on_image_scan_completed event rule and trigger the event target

repository = nil # AWSCDK::ECR::Repository
target = nil


repository.on_image_scan_completed("ImageScanComplete").add_target(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.

user = AWSCDK::IAM::User.new(self, "User")
AWSCDK::ECR::AuthorizationToken.grant_read(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.

user = AWSCDK::IAM::User.new(self, "User")
AWSCDK::ECR::PublicGalleryAuthorizationToken.grant_read(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:

Here is an example of granting a user push permissions:

repository = nil # AWSCDK::ECR::Repository


role = AWSCDK::IAM::Role.new(self, "Role", {
    assumed_by: AWSCDK::IAM::ServicePrincipal.new("codebuild.amazonaws.com"),
})
repository.grant_push(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:

repository = nil # AWSCDK::ECR::Repository


role = AWSCDK::IAM::Role.new(self, "Role", {
    assumed_by: AWSCDK::IAM::ServicePrincipal.new("codebuild.amazonaws.com"),
})
repository.grant_pull(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:

repository = nil # AWSCDK::ECR::Repository


role = AWSCDK::IAM::Role.new(self, "Role", {
    assumed_by: AWSCDK::IAM::ServicePrincipal.new("codebuild.amazonaws.com"),
})
repository.grant_pull_push(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 image_tag_mutability construct prop.

AWSCDK::ECR::Repository.new(self, "Repo", {image_tag_mutability: AWSCDK::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:

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

# Make all tags immutable except for those starting with 'dev-' or 'test-'
AWSCDK::ECR::Repository.new(self, "Repo", {
    image_tag_mutability: AWSCDK::ECR::TagMutability::IMMUTABLE_WITH_EXCLUSION,
    image_tag_mutability_exclusion_filters: [
        AWSCDK::ECR::ImageTagMutabilityExclusionFilter.wildcard("dev-*"),
        AWSCDK::ECR::ImageTagMutabilityExclusionFilter.wildcard("test-*"),
    ],
})
# Make all tags mutable except for production releases
AWSCDK::ECR::Repository.new(self, "Repo", {
    image_tag_mutability: AWSCDK::ECR::TagMutability::MUTABLE_WITH_EXCLUSION,
    image_tag_mutability_exclusion_filters: [
        AWSCDK::ECR::ImageTagMutabilityExclusionFilter.wildcard("prod-*"),
        AWSCDK::ECR::ImageTagMutabilityExclusionFilter.wildcard("release-v*"),
    ],
})
Exclusion filter pattern rules

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 encryption_key property.

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

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

AWSCDK::ECR::Repository.new(self, "Repo", {
    encryption: AWSCDK::ECR::RepositoryEncryption.KMS,
})

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

require 'aws-cdk-lib'


AWSCDK::ECR::Repository.new(self, "Repo", {
    encryption_key: AWSCDK::KMS::Key.new(self, "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):

repository = nil # AWSCDK::ECR::Repository

repository.add_lifecycle_rule({tag_prefix_list: ["prod"], max_image_count: 9999})
repository.add_lifecycle_rule({max_image_age: AWSCDK::Duration.days(30)})

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

repository = nil # AWSCDK::ECR::Repository

repository.add_lifecycle_rule({tag_pattern_list: ["prod*"], max_image_count: 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 empty_on_delete option as well as setting the removal policy to RemovalPolicy.DESTROY.

repository = AWSCDK::ECR::Repository.new(self, "MyTempRepo", {
    removal_policy: AWSCDK::RemovalPolicy::DESTROY,
    empty_on_delete: true,
})

Managing the Resource Policy

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

repository = nil # AWSCDK::ECR::Repository

repository.add_to_resource_policy(AWSCDK::IAM::PolicyStatement.new({
    actions: ["ecr:GetDownloadUrlForLayer"],
    # resources: ['*'], // not currently allowed!
    principals: [AWSCDK::IAM::AnyPrincipal.new],
}))

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.

# import using repository name
repository_from_name = AWSCDK::ECR::Repository.from_repository_name(self, "ImportedRepoByName", "my-repo-name")

# import using repository ARN
repository_from_arn = AWSCDK::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 = AWSCDK::ECR::Repository.from_lookup(self, "ImportedRepoByLookup", {
    repository_arn: "arn:aws:ecr:us-east-1:123456789012:repository/my-repo-name",
    repository_name: "my-repo-name",
})

CloudWatch event rules

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

require 'aws-cdk-lib'


repo = AWSCDK::ECR::Repository.new(self, "Repo")
lambda_handler = AWSCDK::Lambda::Function.new(self, "LambdaFunction", {
    runtime: AWSCDK::Lambda::Runtime.PYTHON_3_12,
    code: AWSCDK::Lambda::Code.from_inline("# dummy func"),
    handler: "index.handler",
})

repo.on_event("OnEventTargetLambda", {
    target: AWSCDK::EventsTargets::LambdaFunction.new(lambda_handler),
})

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:

AWSCDK::ECR::CfnRepository.new(self, "Repo").with(AWSCDK::ECR::Mixins::RepositoryAutoDeleteImages.new)

API Reference

Namespaces 1

Mixins

Classes 15

AuthorizationTokenAuthorization token to access private ECR repositories in the current environment via Dock CfnPublicRepositoryThe `AWS::ECR::PublicRepository` resource specifies an Amazon Elastic Container Registry P CfnPullThroughCacheRuleThe `AWS::ECR::PullThroughCacheRule` resource creates or updates a pull through cache rule CfnPullTimeUpdateExclusionThe ARN of the IAM principal to remove from the pull time update exclusion list. CfnRegistryPolicyThe `AWS::ECR::RegistryPolicy` resource creates or updates the permissions policy for a pr CfnRegistryScanningConfigurationThe scanning configuration for a private registry. CfnReplicationConfigurationThe `AWS::ECR::ReplicationConfiguration` resource creates or updates the replication confi CfnRepositoryThe `AWS::ECR::Repository` resource specifies an Amazon Elastic Container Registry (Amazon CfnRepositoryCreationTemplateThe details of the repository creation template associated with the request. CfnSigningConfigurationThe signing configuration for a registry, which specifies rules for automatically signing ImageTagMutabilityExclusionFilterRepresents an image tag mutability exclusion filter for ECR repository. PublicGalleryAuthorizationTokenAuthorization token to access the global public ECR Gallery via Docker CLI. RepositoryDefine an ECR repository. RepositoryBaseBase class for ECR repository. RepositoryEncryptionIndicates whether server-side encryption is enabled for the object, and whether that encry

Interfaces 16

CfnPublicRepositoryPropsProperties for defining a `CfnPublicRepository`. CfnPullThroughCacheRulePropsProperties for defining a `CfnPullThroughCacheRule`. CfnPullTimeUpdateExclusionPropsProperties for defining a `CfnPullTimeUpdateExclusion`. CfnRegistryPolicyPropsProperties for defining a `CfnRegistryPolicy`. CfnRegistryScanningConfigurationPropsProperties for defining a `CfnRegistryScanningConfiguration`. CfnReplicationConfigurationPropsProperties for defining a `CfnReplicationConfiguration`. CfnRepositoryCreationTemplatePropsProperties for defining a `CfnRepositoryCreationTemplate`. CfnRepositoryPropsProperties for defining a `CfnRepository`. CfnSigningConfigurationPropsProperties for defining a `CfnSigningConfiguration`. IRepositoryRepresents an ECR repository. LifecycleRuleAn ECR life cycle rule. OnCloudTrailImagePushedOptionsOptions for the onCloudTrailImagePushed method. OnImageScanCompletedOptionsOptions for the OnImageScanCompleted method. RepositoryAttributes RepositoryLookupOptionsProperties for looking up an existing Repository. RepositoryProps

Enums 2

TagMutabilityThe tag mutability setting for your repository. TagStatusSelect images based on tags.