Skip to content

EcrBuilder

Bases: AbstractAWSResourceBuilder['EcrBuilder', EcrConfig]

Builder for creating AWS ECR repositories with organizational standards.

Creates secure ECR repositories with optional KMS encryption, automatic image scanning, and cross-account access policies. Supports lifecycle management and Parameter Store integration for cross-stack references.

Source code in mare_aws_common_lib/builders/ecr_builder.py
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
class EcrBuilder(AbstractAWSResourceBuilder["EcrBuilder", EcrConfig]):
    """Builder for creating AWS ECR repositories with organizational standards.

    Creates secure ECR repositories with optional KMS encryption, automatic image
    scanning, and cross-account access policies. Supports lifecycle management
    and Parameter Store integration for cross-stack references.
    """

    _resource_type : AWSResourceType = AWSResourceType.ECR

    def reset(self) -> None:
        """Reset the builder to its initial state.

        Clears all internal state including repository instance, KMS key,
        and repository base name. Called internally to prepare for a new build.
        """
        super().reset()
        self._ecr_repo_base_name: str = None
        self._repo: ecr.Repository = None
        self._repo_kms_key: kms.Key = None

    def set_ecr_repo_base_name(self, name: str) -> 'EcrBuilder': 
        """Set the base name for the ECR repository.

        The base name will be used to construct the final repository name
        following organizational naming conventions.

        Args:
            name: Base name for the repository (e.g., 'my-app', 'data-processor')

        Returns:
            Self for method chaining
        """
        self._ecr_repo_base_name = name
        return self

    def build(self, scope : Construct) -> ecr.Repository:
        """Build and return the configured ECR repository.

        Creates an ECR repository with optional KMS encryption, cross-account
        access policies, and lifecycle rules. Automatically stores repository
        references in Parameter Store.

        Args:
            scope: CDK construct scope where the repository will be created

        Returns:
            Configured ECR Repository instance

        Raises:
            ValidationError: If repository configuration validation fails
            ValueError: If required repository base name is not set
        """
        super().build()
        self._repo, self._repo_kms_key = self._create_repo_from_config(scope)

        principals = self._get_principals()
        self._create_cross_account_policy_for_ecr_repos(principals)
        if self._repo_kms_key is not None:
            # TODO we still might need to add a policy for cross-account (uncomment the line below), maybe related with DescribeKey, to be checked
            # self._create_cross_account_policy_for_ecr_kms_key(principals)
            self._grant_encrypt_decrypt_for_kms_key(principals)

        if self._tags:
            self._tag_resource(self._repo)

        return self._repo

    def _create_repo_from_config(self, scope: Construct) -> Tuple[ecr.Repository, kms.Key]:
        """Create ECR repository and optional KMS key from configuration.

        Creates the repository with encryption, lifecycle policies, and Parameter
        Store entries. Returns both the repository and KMS key (if created).

        Args:
            scope: CDK construct scope

        Returns:
            Tuple of (ECR Repository, KMS Key or None)
        """
        kms_key: kms.Key = None

        if self._config.use_kms_key:
            kms_key = self._create_kms_key(scope, f"{self._config.ecr_repo_base_name}")

        ecr_repo_name = self._get_name_for_resource(self._config.ecr_repo_base_name, max_length=AWSResourceNameLength.ECR_REPOSITORY.value)
        ecr_repo = self._create_ecr_repo(scope, ecr_repo_name, kms_key)

        if self._config.images_retained is not None:
            self._add_image_retention_policy(ecr_repo)

        # Store the repository uri and name in the store parameter in order to be available to other stacks
        self._application_helper.store_parameter(scope, 
                                                f"ECR_{self._config.ecr_repo_base_name.replace("-", "_")}_arn", 
                                                ecr_repo.repository_arn)
        self._application_helper.store_parameter(scope, 
                                                f"ECR_{self._config.ecr_repo_base_name.replace("-", "_")}_name", 
                                                ecr_repo_name)
        if kms_key is not None:
            # Store the repository encryption key arn in the store parameter in order to be available to other stacks
            self._application_helper.store_parameter(scope, 
                                                f"ECR_{self._config.ecr_repo_base_name.replace("-", "_")}_kms_key_arn", 
                                                kms_key.key_arn)

        self._tag_resource(ecr_repo)

        return ecr_repo, kms_key

    def _create_kms_key(self, scope: Construct, name: str) -> kms.Key:
        """Create a KMS key for ECR repository encryption.

        Creates a customer-managed KMS key with proper alias and tagging
        for encrypting ECR repository images.

        Args:
            scope: CDK construct scope
            name: Base name for the KMS key alias

        Returns:
            Configured KMS Key instance
        """
        # Create a KMS key for encryption
        kms_key = kms.Key(
            scope, self._get_cfn_logical_id(f"kms-key-{name}"),
            alias = self._get_name_for_resource(name, max_length=AWSResourceNameLength.KMS_ALIAS.value),
            enable_key_rotation=False,
            removal_policy=RemovalPolicy.DESTROY
        )
        self._tag_resource(kms_key)

        return kms_key

    def _create_ecr_repo(self, scope: Construct, repo_name: str, kms_key: kms.Key = None) -> ecr.Repository:
        """Create the ECR repository with security best practices.

        Creates repository with image scanning enabled, proper removal policy,
        and optional KMS encryption.

        Args:
            scope: CDK construct scope
            repo_name: Full repository name
            kms_key: Optional KMS key for encryption

        Returns:
            Configured ECR Repository instance
        """
        # Create the ECR repository
        repo: ecr.Repository = ecr.Repository(
            scope, self._get_cfn_logical_id(self._config.ecr_repo_base_name),
            repository_name=repo_name,
            removal_policy=RemovalPolicy.DESTROY,
            image_scan_on_push=True,
            empty_on_delete=True,
            encryption_key=kms_key
        )

        return repo

    def _add_image_retention_policy(self, repo: ecr.Repository) -> None:
        """Add lifecycle rule to limit retained images.

        Adds a lifecycle policy to keep only the specified number of
        most recent images, automatically cleaning up older images.

        Args:
            repo: ECR repository to add the policy to
        """
        # Add max docker images retention policy
        repo.add_lifecycle_rule(
            max_image_count=self._config.images_retained,
            rule_priority=1,
            description=f"Retain the latest {self._config.images_retained} images only"
        )

    def _get_principals(self) -> List[iam.ArnPrincipal]:
        """Get IAM principals for cross-account access policies.

        Returns account root principals based on sharing configuration.
        Either current account only or all environment accounts.

        Returns:
            List of IAM principals for policy statements
        """
        principals = []
        if self._config.shareable_with_all_envs:
            all_envs_config: Dict[str, Any] = self._application_helper.get_all_envs()
            all_envs_names: List[str] = all_envs_config.keys()
            for env_name in Environment.list():
                if env_name.lower() in all_envs_names:
                    principals.append(iam.ArnPrincipal(f"arn:aws:iam::{all_envs_config[env_name.lower()]["account_id"]}:root"))
        else:
            principals.append(iam.ArnPrincipal(f"arn:aws:iam::{self._application_helper.get_from_env("account_id")}:root"))

        return principals

    def _create_cross_account_policy_for_ecr_repos(self, principals: List[iam.ArnPrincipal]) -> None:
        """Add cross-account read access policy to the ECR repository.

        Grants specified principals permissions to pull images and
        access repository metadata across accounts.

        Args:
            principals: List of IAM principals to grant access to
        """
        policy = iam.PolicyStatement(
            sid=self._get_cfn_logical_id("app-repo-cross-account-policy"),
            effect=iam.Effect.ALLOW,
            principals=principals,
            actions=[
                "ecr:BatchCheckLayerAvailability",
                "ecr:BatchGetImage",
                "ecr:BatchGetRepositoryScanningConfiguration",
                "ecr:Describe*",
                "ecr:Get*",
                "ecr:List*"
            ]
        )

        self._repo.add_to_resource_policy(policy)

    def _create_cross_account_policy_for_ecr_kms_key(self, principals: List[iam.ArnPrincipal]) -> None:
        """Add cross-account decrypt policy to the KMS key.

        Grants specified principals permissions to decrypt images
        encrypted with the repository's KMS key.

        Args:
            principals: List of IAM principals to grant access to
        """
        policy = iam.PolicyStatement(
            sid=self._get_cfn_logical_id("kms-cross-account-policy"),
            effect=iam.Effect.ALLOW,
            principals=principals,
            actions=[
                "kms:Decrypt",
                "kms:DescribeKey"
            ],
            resources=["*"]
        )

        self._repo_kms_key.add_to_resource_policy(policy)

    def _grant_encrypt_decrypt_for_kms_key(self, principals: List[iam.ArnPrincipal]) -> None:
        """Grant encrypt/decrypt permissions on KMS key to principals.

        Uses CDK's built-in grant methods to provide comprehensive
        KMS access for image encryption operations.

        Args:
            principals: List of IAM principals to grant access to
        """
        for principal in principals:
            self._repo_kms_key.grant_encrypt_decrypt(principal)

    def _set_config(self) -> None:
        """Create and validate the ECR repository configuration.

        Merges the base builder configuration with ECR-specific parameters
        to create a validated EcrConfig object. The configuration includes
        repository naming, KMS encryption settings, image retention policies,
        cross-account sharing options, and other ECR-specific parameters
        required for repository creation.

        The method combines:
            - Base configuration from self._builder_config (tags, environment, etc.)
            - ECR-specific parameter: ecr_repo_base_name from self._ecr_repo_base_name

        Raises:
            ValidationError: If the EcrConfig validation fails.
            ValueError: If ecr_repo_base_name has not been set via set_ecr_repo_base_name()

        Side Effects:
            Sets self._config to a validated EcrConfig instance that can be
            accessed through the config property after this method completes.
        """
        try:
            self._config = EcrConfig(**{
                **self._builder_config,
                "ecr_repo_base_name": self._ecr_repo_base_name
            })
        except ValidationError as e:
            self._log_validation_error(e, EcrConfig)
            raise

    def _control_consistency(self) -> None:
        """Validate builder configuration and internal state consistency.

        Ensures repository base name is set and validates the complete
        configuration using the EcrConfig model.

        Raises:
            ValueError: If repository base name is not set
            ValidationError: If configuration validation fails
        """
        super()._control_consistency()

        if not self._ecr_repo_base_name:
            raise ValueError("ECR repo base name must be set before building")

        self._set_config()

Attributes

_resource_type = AWSResourceType.ECR class-attribute instance-attribute

Functions

_add_image_retention_policy(repo)

Add lifecycle rule to limit retained images.

Adds a lifecycle policy to keep only the specified number of most recent images, automatically cleaning up older images.

Parameters:

Name Type Description Default
repo Repository

ECR repository to add the policy to

required
Source code in mare_aws_common_lib/builders/ecr_builder.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def _add_image_retention_policy(self, repo: ecr.Repository) -> None:
    """Add lifecycle rule to limit retained images.

    Adds a lifecycle policy to keep only the specified number of
    most recent images, automatically cleaning up older images.

    Args:
        repo: ECR repository to add the policy to
    """
    # Add max docker images retention policy
    repo.add_lifecycle_rule(
        max_image_count=self._config.images_retained,
        rule_priority=1,
        description=f"Retain the latest {self._config.images_retained} images only"
    )

_control_consistency()

Validate builder configuration and internal state consistency.

Ensures repository base name is set and validates the complete configuration using the EcrConfig model.

Raises:

Type Description
ValueError

If repository base name is not set

ValidationError

If configuration validation fails

Source code in mare_aws_common_lib/builders/ecr_builder.py
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
def _control_consistency(self) -> None:
    """Validate builder configuration and internal state consistency.

    Ensures repository base name is set and validates the complete
    configuration using the EcrConfig model.

    Raises:
        ValueError: If repository base name is not set
        ValidationError: If configuration validation fails
    """
    super()._control_consistency()

    if not self._ecr_repo_base_name:
        raise ValueError("ECR repo base name must be set before building")

    self._set_config()

_create_cross_account_policy_for_ecr_kms_key(principals)

Add cross-account decrypt policy to the KMS key.

Grants specified principals permissions to decrypt images encrypted with the repository's KMS key.

Parameters:

Name Type Description Default
principals List[ArnPrincipal]

List of IAM principals to grant access to

required
Source code in mare_aws_common_lib/builders/ecr_builder.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
def _create_cross_account_policy_for_ecr_kms_key(self, principals: List[iam.ArnPrincipal]) -> None:
    """Add cross-account decrypt policy to the KMS key.

    Grants specified principals permissions to decrypt images
    encrypted with the repository's KMS key.

    Args:
        principals: List of IAM principals to grant access to
    """
    policy = iam.PolicyStatement(
        sid=self._get_cfn_logical_id("kms-cross-account-policy"),
        effect=iam.Effect.ALLOW,
        principals=principals,
        actions=[
            "kms:Decrypt",
            "kms:DescribeKey"
        ],
        resources=["*"]
    )

    self._repo_kms_key.add_to_resource_policy(policy)

_create_cross_account_policy_for_ecr_repos(principals)

Add cross-account read access policy to the ECR repository.

Grants specified principals permissions to pull images and access repository metadata across accounts.

Parameters:

Name Type Description Default
principals List[ArnPrincipal]

List of IAM principals to grant access to

required
Source code in mare_aws_common_lib/builders/ecr_builder.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
def _create_cross_account_policy_for_ecr_repos(self, principals: List[iam.ArnPrincipal]) -> None:
    """Add cross-account read access policy to the ECR repository.

    Grants specified principals permissions to pull images and
    access repository metadata across accounts.

    Args:
        principals: List of IAM principals to grant access to
    """
    policy = iam.PolicyStatement(
        sid=self._get_cfn_logical_id("app-repo-cross-account-policy"),
        effect=iam.Effect.ALLOW,
        principals=principals,
        actions=[
            "ecr:BatchCheckLayerAvailability",
            "ecr:BatchGetImage",
            "ecr:BatchGetRepositoryScanningConfiguration",
            "ecr:Describe*",
            "ecr:Get*",
            "ecr:List*"
        ]
    )

    self._repo.add_to_resource_policy(policy)

_create_ecr_repo(scope, repo_name, kms_key=None)

Create the ECR repository with security best practices.

Creates repository with image scanning enabled, proper removal policy, and optional KMS encryption.

Parameters:

Name Type Description Default
scope Construct

CDK construct scope

required
repo_name str

Full repository name

required
kms_key Key

Optional KMS key for encryption

None

Returns:

Type Description
Repository

Configured ECR Repository instance

Source code in mare_aws_common_lib/builders/ecr_builder.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
def _create_ecr_repo(self, scope: Construct, repo_name: str, kms_key: kms.Key = None) -> ecr.Repository:
    """Create the ECR repository with security best practices.

    Creates repository with image scanning enabled, proper removal policy,
    and optional KMS encryption.

    Args:
        scope: CDK construct scope
        repo_name: Full repository name
        kms_key: Optional KMS key for encryption

    Returns:
        Configured ECR Repository instance
    """
    # Create the ECR repository
    repo: ecr.Repository = ecr.Repository(
        scope, self._get_cfn_logical_id(self._config.ecr_repo_base_name),
        repository_name=repo_name,
        removal_policy=RemovalPolicy.DESTROY,
        image_scan_on_push=True,
        empty_on_delete=True,
        encryption_key=kms_key
    )

    return repo

_create_kms_key(scope, name)

Create a KMS key for ECR repository encryption.

Creates a customer-managed KMS key with proper alias and tagging for encrypting ECR repository images.

Parameters:

Name Type Description Default
scope Construct

CDK construct scope

required
name str

Base name for the KMS key alias

required

Returns:

Type Description
Key

Configured KMS Key instance

Source code in mare_aws_common_lib/builders/ecr_builder.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def _create_kms_key(self, scope: Construct, name: str) -> kms.Key:
    """Create a KMS key for ECR repository encryption.

    Creates a customer-managed KMS key with proper alias and tagging
    for encrypting ECR repository images.

    Args:
        scope: CDK construct scope
        name: Base name for the KMS key alias

    Returns:
        Configured KMS Key instance
    """
    # Create a KMS key for encryption
    kms_key = kms.Key(
        scope, self._get_cfn_logical_id(f"kms-key-{name}"),
        alias = self._get_name_for_resource(name, max_length=AWSResourceNameLength.KMS_ALIAS.value),
        enable_key_rotation=False,
        removal_policy=RemovalPolicy.DESTROY
    )
    self._tag_resource(kms_key)

    return kms_key

_create_repo_from_config(scope)

Create ECR repository and optional KMS key from configuration.

Creates the repository with encryption, lifecycle policies, and Parameter Store entries. Returns both the repository and KMS key (if created).

Parameters:

Name Type Description Default
scope Construct

CDK construct scope

required

Returns:

Type Description
Tuple[Repository, Key]

Tuple of (ECR Repository, KMS Key or None)

Source code in mare_aws_common_lib/builders/ecr_builder.py
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def _create_repo_from_config(self, scope: Construct) -> Tuple[ecr.Repository, kms.Key]:
    """Create ECR repository and optional KMS key from configuration.

    Creates the repository with encryption, lifecycle policies, and Parameter
    Store entries. Returns both the repository and KMS key (if created).

    Args:
        scope: CDK construct scope

    Returns:
        Tuple of (ECR Repository, KMS Key or None)
    """
    kms_key: kms.Key = None

    if self._config.use_kms_key:
        kms_key = self._create_kms_key(scope, f"{self._config.ecr_repo_base_name}")

    ecr_repo_name = self._get_name_for_resource(self._config.ecr_repo_base_name, max_length=AWSResourceNameLength.ECR_REPOSITORY.value)
    ecr_repo = self._create_ecr_repo(scope, ecr_repo_name, kms_key)

    if self._config.images_retained is not None:
        self._add_image_retention_policy(ecr_repo)

    # Store the repository uri and name in the store parameter in order to be available to other stacks
    self._application_helper.store_parameter(scope, 
                                            f"ECR_{self._config.ecr_repo_base_name.replace("-", "_")}_arn", 
                                            ecr_repo.repository_arn)
    self._application_helper.store_parameter(scope, 
                                            f"ECR_{self._config.ecr_repo_base_name.replace("-", "_")}_name", 
                                            ecr_repo_name)
    if kms_key is not None:
        # Store the repository encryption key arn in the store parameter in order to be available to other stacks
        self._application_helper.store_parameter(scope, 
                                            f"ECR_{self._config.ecr_repo_base_name.replace("-", "_")}_kms_key_arn", 
                                            kms_key.key_arn)

    self._tag_resource(ecr_repo)

    return ecr_repo, kms_key

_get_principals()

Get IAM principals for cross-account access policies.

Returns account root principals based on sharing configuration. Either current account only or all environment accounts.

Returns:

Type Description
List[ArnPrincipal]

List of IAM principals for policy statements

Source code in mare_aws_common_lib/builders/ecr_builder.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def _get_principals(self) -> List[iam.ArnPrincipal]:
    """Get IAM principals for cross-account access policies.

    Returns account root principals based on sharing configuration.
    Either current account only or all environment accounts.

    Returns:
        List of IAM principals for policy statements
    """
    principals = []
    if self._config.shareable_with_all_envs:
        all_envs_config: Dict[str, Any] = self._application_helper.get_all_envs()
        all_envs_names: List[str] = all_envs_config.keys()
        for env_name in Environment.list():
            if env_name.lower() in all_envs_names:
                principals.append(iam.ArnPrincipal(f"arn:aws:iam::{all_envs_config[env_name.lower()]["account_id"]}:root"))
    else:
        principals.append(iam.ArnPrincipal(f"arn:aws:iam::{self._application_helper.get_from_env("account_id")}:root"))

    return principals

_grant_encrypt_decrypt_for_kms_key(principals)

Grant encrypt/decrypt permissions on KMS key to principals.

Uses CDK's built-in grant methods to provide comprehensive KMS access for image encryption operations.

Parameters:

Name Type Description Default
principals List[ArnPrincipal]

List of IAM principals to grant access to

required
Source code in mare_aws_common_lib/builders/ecr_builder.py
256
257
258
259
260
261
262
263
264
265
266
def _grant_encrypt_decrypt_for_kms_key(self, principals: List[iam.ArnPrincipal]) -> None:
    """Grant encrypt/decrypt permissions on KMS key to principals.

    Uses CDK's built-in grant methods to provide comprehensive
    KMS access for image encryption operations.

    Args:
        principals: List of IAM principals to grant access to
    """
    for principal in principals:
        self._repo_kms_key.grant_encrypt_decrypt(principal)

_set_config()

Create and validate the ECR repository configuration.

Merges the base builder configuration with ECR-specific parameters to create a validated EcrConfig object. The configuration includes repository naming, KMS encryption settings, image retention policies, cross-account sharing options, and other ECR-specific parameters required for repository creation.

The method combines
  • Base configuration from self._builder_config (tags, environment, etc.)
  • ECR-specific parameter: ecr_repo_base_name from self._ecr_repo_base_name

Raises:

Type Description
ValidationError

If the EcrConfig validation fails.

ValueError

If ecr_repo_base_name has not been set via set_ecr_repo_base_name()

Side Effects

Sets self._config to a validated EcrConfig instance that can be accessed through the config property after this method completes.

Source code in mare_aws_common_lib/builders/ecr_builder.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
def _set_config(self) -> None:
    """Create and validate the ECR repository configuration.

    Merges the base builder configuration with ECR-specific parameters
    to create a validated EcrConfig object. The configuration includes
    repository naming, KMS encryption settings, image retention policies,
    cross-account sharing options, and other ECR-specific parameters
    required for repository creation.

    The method combines:
        - Base configuration from self._builder_config (tags, environment, etc.)
        - ECR-specific parameter: ecr_repo_base_name from self._ecr_repo_base_name

    Raises:
        ValidationError: If the EcrConfig validation fails.
        ValueError: If ecr_repo_base_name has not been set via set_ecr_repo_base_name()

    Side Effects:
        Sets self._config to a validated EcrConfig instance that can be
        accessed through the config property after this method completes.
    """
    try:
        self._config = EcrConfig(**{
            **self._builder_config,
            "ecr_repo_base_name": self._ecr_repo_base_name
        })
    except ValidationError as e:
        self._log_validation_error(e, EcrConfig)
        raise

build(scope)

Build and return the configured ECR repository.

Creates an ECR repository with optional KMS encryption, cross-account access policies, and lifecycle rules. Automatically stores repository references in Parameter Store.

Parameters:

Name Type Description Default
scope Construct

CDK construct scope where the repository will be created

required

Returns:

Type Description
Repository

Configured ECR Repository instance

Raises:

Type Description
ValidationError

If repository configuration validation fails

ValueError

If required repository base name is not set

Source code in mare_aws_common_lib/builders/ecr_builder.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def build(self, scope : Construct) -> ecr.Repository:
    """Build and return the configured ECR repository.

    Creates an ECR repository with optional KMS encryption, cross-account
    access policies, and lifecycle rules. Automatically stores repository
    references in Parameter Store.

    Args:
        scope: CDK construct scope where the repository will be created

    Returns:
        Configured ECR Repository instance

    Raises:
        ValidationError: If repository configuration validation fails
        ValueError: If required repository base name is not set
    """
    super().build()
    self._repo, self._repo_kms_key = self._create_repo_from_config(scope)

    principals = self._get_principals()
    self._create_cross_account_policy_for_ecr_repos(principals)
    if self._repo_kms_key is not None:
        # TODO we still might need to add a policy for cross-account (uncomment the line below), maybe related with DescribeKey, to be checked
        # self._create_cross_account_policy_for_ecr_kms_key(principals)
        self._grant_encrypt_decrypt_for_kms_key(principals)

    if self._tags:
        self._tag_resource(self._repo)

    return self._repo

reset()

Reset the builder to its initial state.

Clears all internal state including repository instance, KMS key, and repository base name. Called internally to prepare for a new build.

Source code in mare_aws_common_lib/builders/ecr_builder.py
24
25
26
27
28
29
30
31
32
33
def reset(self) -> None:
    """Reset the builder to its initial state.

    Clears all internal state including repository instance, KMS key,
    and repository base name. Called internally to prepare for a new build.
    """
    super().reset()
    self._ecr_repo_base_name: str = None
    self._repo: ecr.Repository = None
    self._repo_kms_key: kms.Key = None

set_ecr_repo_base_name(name)

Set the base name for the ECR repository.

The base name will be used to construct the final repository name following organizational naming conventions.

Parameters:

Name Type Description Default
name str

Base name for the repository (e.g., 'my-app', 'data-processor')

required

Returns:

Type Description
EcrBuilder

Self for method chaining

Source code in mare_aws_common_lib/builders/ecr_builder.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def set_ecr_repo_base_name(self, name: str) -> 'EcrBuilder': 
    """Set the base name for the ECR repository.

    The base name will be used to construct the final repository name
    following organizational naming conventions.

    Args:
        name: Base name for the repository (e.g., 'my-app', 'data-processor')

    Returns:
        Self for method chaining
    """
    self._ecr_repo_base_name = name
    return self