Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat(cloudformation): replace an ECR repository when its encryption changes (#1951)

iot-rocket965c0aa4d272
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5851871d..fef21e9d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Added
+- **CloudFormation — ECR repositories are replaced** — an `EncryptionConfiguration` change on `AWS::ECR::Repository` replaces the repository under a new generated name (generated names now carry the usual suffix) and is refused for an explicit `RepositoryName`, where it used to be ignored.
+- **CloudFormation — IAM roles and managed policies are replaced** — a `Path` change on `AWS::IAM::Role` and a `Path` or `Description` change on `AWS::IAM::ManagedPolicy` replace the resource under a new generated name, a named role refuses it as a custom-named replacement, a named policy fails with the IAM duplicate-name error as on AWS, also when only its `Path` changes, generated policy names get the suffix other generated names have, and both ARNs include the `Path`.
+- **CloudFormation — stack updates replace resources** — a change to a property the change set reports as `RequiresRecreation: Always` now creates a new resource under a new generated name, points its dependents at it and deletes the old one after the update succeeds (a rollback deletes the new one instead). With an explicit, unchanged name the update fails with the AWS message naming the physical id; this now also covers `AWS::Lambda::Function`. A named SQS queue or SNS topic fails with AWS's already-exists error instead and keeps its messages or subscriptions.
- **CloudFormation — IAM roles and managed policies are replaced** — a `Path` change on `AWS::IAM::Role` and a `Path` or `Description` change on `AWS::IAM::ManagedPolicy` replace the resource under a new generated name, a named role refuses it as a custom-named replacement, a named policy fails with the IAM duplicate-name error as on AWS, also when only its `Path` changes, generated policy names get the suffix other generated names have, and both ARNs include the `Path`.
- **CloudFormation — stack updates replace resources** — a change to a property the change set reports as `RequiresRecreation: Always` now creates a new resource under a new generated name, points its dependents at it and deletes the old one after the update succeeds (a rollback deletes the new one instead). With an explicit, unchanged name the update fails with the AWS message naming the physical id; this now also covers `AWS::Lambda::Function`. A named SQS queue or SNS topic fails with AWS's already-exists error instead and keeps its messages or subscriptions.
- **CloudFormation — `IMPORT` change sets execute** — existing SQS queues, SSM parameters, S3 buckets, DynamoDB tables, IAM roles, log groups, Lambda functions, IoT policies, IoT CA certificates and Cognito user pools are adopted into a new or existing stack without being changed (`IMPORT_IN_PROGRESS` to `IMPORT_COMPLETE`, or a rollback when a resource is gone), and an import that changes `Outputs` or stack tags is refused, as on AWS.
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index fcc25351..58fd252f 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -740,6 +740,7 @@ _CUSTOM_NAME_REPLACEMENT = {
"name": "ManagedPolicyName",
"exists": "A policy called {name} already exists. Duplicate names are not allowed.",
},
+ "AWS::ECR::Repository": {"name": "RepositoryName"},
"AWS::IoT::ProvisioningTemplate": {
"name": "TemplateName",
"requires_replacement": lambda old, new: (
@@ -6955,7 +6956,8 @@ def _ecr_repo_apply_policies(name, props):
def _ecr_repo_create(logical_id, props, stack_name):
- name = props.get("RepositoryName", f"{stack_name}-{logical_id}".lower())
+ name = props.get("RepositoryName") or _physical_name(
+ stack_name, logical_id, lowercase=True, max_len=256)
api = _ecr_cfn_to_api(props)
if name in _ecr._repositories:
# The create has always overwritten an existing record; refusing the
@@ -12543,19 +12545,13 @@ def _kinesis_stream_update(physical_id, old_props, new_props, stack_name):
return physical_id, {"Arn": stream["StreamARN"]}
-def _ecr_repo_update(physical_id, old_props, new_props, stack_name):
+def _ecr_repo_update(physical_id, old_props, new_props, stack_name, logical_id=None):
repo = _ecr._repositories.get(physical_id)
- new_name = new_props.get("RepositoryName")
- if repo is None or (new_name and new_name != physical_id):
- # A new name is a replacement: create the new repository, then delete
- # the old one through DeleteRepository, unless the template retains it.
- result = _ecr_repo_create(physical_id, new_props, stack_name)
- if repo is not None:
- _delete_predecessor(_ecr_repo_delete, physical_id, old_props)
- return result
+ if repo is None:
+ return _ecr_repo_create(logical_id or physical_id, new_props, stack_name)
# ImageTagMutability, ImageScanningConfiguration, LifecyclePolicy,
- # RepositoryPolicyText and Tags update in place; EncryptionConfiguration
- # requires replacement and stays as it is.
+ # RepositoryPolicyText and Tags update in place; RepositoryName and
+ # EncryptionConfiguration are replaced in _update_resource.
api = _ecr_cfn_to_api(new_props)
repo["imageTagMutability"] = api["imageTagMutability"]
repo["imageScanningConfiguration"] = api["imageScanningConfiguration"]
@@ -12767,6 +12763,7 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {
"AWS::IAM::InstanceProfile": ("InstanceProfileName", "Path"),
"AWS::IAM::Role": ("RoleName", "Path"),
"AWS::IAM::ManagedPolicy": ("ManagedPolicyName", "Description", "Path"),
+ "AWS::ECR::Repository": ("RepositoryName", "EncryptionConfiguration"),
"AWS::IoT::ProvisioningTemplate": ("TemplateName", "TemplateType"),
"AWS::ElasticLoadBalancingV2::LoadBalancer": ("Name", "Scheme", "Type"),
"AWS::ElasticLoadBalancingV2::TargetGroup": (
@@ -13279,7 +13276,12 @@ _RESOURCE_HANDLERS = {
"delete": _cognito_identity_pool_delete,
},
"AWS::Cognito::UserPoolDomain": {"create": _cognito_user_pool_domain_create, "delete": _cognito_user_pool_domain_delete},
- "AWS::ECR::Repository": {"create": _ecr_repo_create, "update": _ecr_repo_update, "delete": _ecr_repo_delete},
+ "AWS::ECR::Repository": {
+ "create": _ecr_repo_create,
+ "update": _ecr_repo_update,
+ "update_with_logical_id": True,
+ "delete": _ecr_repo_delete,
+ },
"AWS::CertificateManager::Certificate": {
"create": _acm_certificate_create,
"update": _acm_certificate_update,
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 293ee4b3..6085eff2 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -5819,6 +5819,55 @@ def test_cfn_ecr_repository_rename_deletes_the_old_repository(cfn, ecr):
pass
+def _cfn_ecr_encryption_template(encryption, name=None):
+ props = {"EncryptionConfiguration": {"EncryptionType": encryption}}
+ if name:
+ props["RepositoryName"] = name
+ return json.dumps({"Resources": {"Repo": {"Type": "AWS::ECR::Repository", "Properties": props}},
+ "Outputs": {"Repo": {"Value": {"Ref": "Repo"}}}})
+
+
+def test_cfn_ecr_repository_encryption_change_replaces_a_generated_name(cfn, ecr):
+ """EncryptionConfiguration is create-only: under a generated name the
+ change creates a repository with a new name and deletes the old one."""
+ stack_name = f"cfn-ecr-enc-{_uuid_mod.uuid4().hex[:8]}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_ecr_encryption_template("AES256"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", _stack_event_reasons(cfn, stack_name)
+ old_name = _output(stack, "Repo")
+ assert old_name.startswith(f"{stack_name}-repo-")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_ecr_encryption_template("KMS"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", _stack_event_reasons(cfn, stack_name)
+ new_name = _output(stack, "Repo")
+ assert new_name != old_name
+ repo = ecr.describe_repositories(repositoryNames=[new_name])["repositories"][0]
+ assert repo["encryptionConfiguration"]["encryptionType"] == "KMS"
+ with pytest.raises(ClientError):
+ ecr.describe_repositories(repositoryNames=[old_name])
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ecr_repository_encryption_change_under_custom_name_is_refused(cfn, ecr):
+ """Under an explicit, unchanged RepositoryName the replacement is refused."""
+ name = f"cfn-ecr-enc-named-{_uuid_mod.uuid4().hex[:8]}"
+ cfn.create_stack(StackName=name, TemplateBody=_cfn_ecr_encryption_template("AES256", name))
+ try:
+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
+ cfn.update_stack(StackName=name, TemplateBody=_cfn_ecr_encryption_template("KMS", name))
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ assert (f"requires replacing. Rename {name} and update the stack again."
+ in _stack_event_reasons(cfn, name))
+ repo = ecr.describe_repositories(repositoryNames=[name])["repositories"][0]
+ assert repo["encryptionConfiguration"]["encryptionType"] == "AES256"
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
def test_cfn_ec2_launch_template(cfn, ec2):
"""CloudFormation should provision and delete an EC2 LaunchTemplate."""
template = {