Skip to content

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

fix(cloudformation): replace multi-region access points and launch configurations on update (#1936)

iot-rocket95a6432be7d1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1e1d98dd..e459d459 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Fixed
+- **CloudFormation — `AWS::S3::MultiRegionAccessPoint` and `AWS::AutoScaling::LaunchConfiguration` are replaced on update** — every property of both types is create-only, so a change now creates the resource under a new generated name and deletes the old one after the update (a `Regions` change was dropped and the stack reported the alias as the physical id, a launch configuration was overwritten under its old name), fails with the custom-named-resource error when the name is explicit, and is reported as `Replacement: True` in a change set.
- **CloudFormation — `AWS::SQS::Queue` with `FifoQueue` gets a generated `.fifo` name** — `FifoQueue: true` without a `QueueName` creates a FIFO queue with a generated `.fifo` name instead of a standard queue, and a `QueueName` whose `.fifo` suffix disagrees with `FifoQueue` fails the resource. Contributed by @iot-rocket.
- **RDS — `DescribeDBClusterSnapshotAttributes`** — was unimplemented (`InvalidAction: Unknown RDS action`), so Terraform's `aws_db_cluster_snapshot` resource failed on read (`reading RDS DB Cluster Snapshot … attribute`) after creating the snapshot. Returns the `restore` attribute with no shared accounts (the manual-snapshot default); `ModifyDBClusterSnapshotAttribute` is not implemented. Unknown snapshot ids answer `DBClusterSnapshotNotFoundFault`.
- **Lambda — Docker executor under `USE_SSL=1` when MiniStack runs in a container** — the gateway certificate, CA bundle and Java truststore were bind-mounted into every Lambda container from MiniStack's own filesystem (`MINISTACK_SSL_CERT`, or the generated `ministack-tls/server.crt` under the temp directory), paths the host Docker daemon cannot see, so every invocation failed with `bind source path does not exist`. In a container they are now copied into the Lambda container, as function code already is.
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 4e1cdb02..fed4fec7 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -71,7 +71,8 @@ _MINISTACK_HOST = os.environ.get("MINISTACK_HOST", "localhost")
def _physical_name(stack_name: str, logical_id: str, *,
- lowercase: bool = False, max_len: int = 128) -> str:
+ lowercase: bool = False, max_len: int = 128,
+ replacing: str = "") -> str:
"""Generate an AWS-style physical resource name: {stack}-{logicalId}-{SUFFIX}.
Matches the pattern AWS CloudFormation uses for auto-named resources so that
@@ -91,7 +92,9 @@ def _physical_name(stack_name: str, logical_id: str, *,
orphaning the real one — and anything referencing it via Ref/Fn::GetAtt
picked up that new (wrong) identity the moment it was reprocessed later in
the same update. Resource *replacement* (a property change real AWS can't
- apply in place) isn't specially detected here — same as before this fix.
+ apply in place) is not detected here: a handler that replaces passes
+ ``replacing`` (the predecessor's physical id), so the replacement gets a
+ name of its own.
Truncates the `{stack}-{logicalId}-` prefix, never the suffix: a naive
`base[:max_len]` on the full concatenated string drops whatever falls past
@@ -108,7 +111,8 @@ def _physical_name(stack_name: str, logical_id: str, *,
cut, since the suffix alone (hashed from stack_name *and* logical_id) is
what actually guarantees uniqueness here.
"""
- suffix = hashlib.sha256(f"{stack_name}:{logical_id}".encode()).hexdigest()[:13].upper()
+ seed = f"{stack_name}:{logical_id}" + (f":{replacing}" if replacing else "")
+ suffix = hashlib.sha256(seed.encode()).hexdigest()[:13].upper()
prefix = f"{stack_name}-{logical_id}-"
available = max(max_len - len(suffix), 0)
base = prefix[:available] + suffix
@@ -677,6 +681,15 @@ _CUSTOM_NAME_REPLACEMENT = {
"name": "TrackerName",
"requires_replacement": lambda old, new: old.get("KmsKeyId") != new.get("KmsKeyId"),
},
+ # Every property of these two types is create-only.
+ "AWS::S3::MultiRegionAccessPoint": {
+ "name": "Name",
+ "requires_replacement": lambda old, new: old != new,
+ },
+ "AWS::AutoScaling::LaunchConfiguration": {
+ "name": "LaunchConfigurationName",
+ "requires_replacement": lambda old, new: old != new,
+ },
"AWS::IAM::InstanceProfile": {
"name": "InstanceProfileName",
"requires_replacement": lambda old, new: old.get("Path", "/") != new.get("Path", "/"),
@@ -850,6 +863,18 @@ def _delete_predecessor(delete_fn, *args, **kwargs):
delete_fn(*args, **kwargs)
+def _replacing_update(create_fn, delete_fn):
+ """An update handler for a type whose every property is create-only."""
+ def update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ # An unchanged custom name was refused above the handler; a generated
+ # name gets a new one, so the predecessor survives until cleanup.
+ created = create_fn(logical_id or physical_id, new_props, stack_name,
+ replacing=physical_id)
+ _delete_predecessor(delete_fn, physical_id, old_props)
+ return created
+ return update
+
+
def _update_resource(resource_type: str, physical_id: str, old_props: dict,
new_props: dict, stack_name: str,
logical_id: str | None = None,
@@ -1249,7 +1274,7 @@ def _s3_apply_notification(name, notif):
# S3 Multi-Region Access Point
# ---------------------------------------------------------------------------
-def _s3_mrap_create(logical_id, props, stack_name):
+def _s3_mrap_create(logical_id, props, stack_name, replacing=""):
"""Provision an AWS::S3::MultiRegionAccessPoint.
On AWS this is asynchronous — `CreateMultiRegionAccessPoint` returns a
@@ -1260,7 +1285,8 @@ def _s3_mrap_create(logical_id, props, stack_name):
`Regions` is a list of `{Bucket}`; the member names are kept so the data
plane can resolve the alias to one of them.
"""
- name = props.get("Name") or _physical_name(stack_name, logical_id, lowercase=True, max_len=50)
+ name = props.get("Name") or _physical_name(
+ stack_name, logical_id, lowercase=True, max_len=50, replacing=replacing)
buckets = [
r.get("Bucket") for r in (props.get("Regions") or [])
if isinstance(r, dict) and r.get("Bucket")
@@ -10371,8 +10397,9 @@ def _asg_delete(physical_id, props):
_asg._delete_group_policies(physical_id)
-def _asg_lc_create(logical_id, props, stack_name):
- name = props.get("LaunchConfigurationName") or _physical_name(stack_name, logical_id, max_len=255)
+def _asg_lc_create(logical_id, props, stack_name, replacing=""):
+ name = props.get("LaunchConfigurationName") or _physical_name(
+ stack_name, logical_id, max_len=255, replacing=replacing)
arn = f"arn:aws:autoscaling:{get_region()}:{get_account_id()}:launchConfiguration:{new_uuid()}:launchConfigurationName/{name}"
_asg._launch_configs[name] = {
"LaunchConfigurationName": name,
@@ -12425,6 +12452,14 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {
"AWS::IoT::ThingType": ("ThingTypeName",),
"AWS::Backup::BackupVault": ("BackupVaultName", "EncryptionKeyArn"),
"AWS::Location::Tracker": ("TrackerName", "KmsKeyId"),
+ "AWS::S3::MultiRegionAccessPoint": ("Name", "PublicAccessBlockConfiguration", "Regions"),
+ "AWS::AutoScaling::LaunchConfiguration": (
+ "AssociatePublicIpAddress", "BlockDeviceMappings", "ClassicLinkVPCId",
+ "ClassicLinkVPCSecurityGroups", "EbsOptimized", "IamInstanceProfile", "ImageId",
+ "InstanceId", "InstanceMonitoring", "InstanceType", "KernelId", "KeyName",
+ "LaunchConfigurationName", "MetadataOptions", "PlacementTenancy", "RamDiskId",
+ "SecurityGroups", "SpotPrice", "UserData",
+ ),
"AWS::IAM::InstanceProfile": ("InstanceProfileName", "Path"),
"AWS::IoT::ProvisioningTemplate": ("TemplateName", "TemplateType"),
"AWS::ElasticLoadBalancingV2::LoadBalancer": ("Name", "Scheme", "Type"),
@@ -12496,7 +12531,12 @@ _RESOURCE_HANDLERS = {
"delete": _opensearch_domain_delete,
},
"AWS::S3::Bucket": {"create": _s3_create, "update": _s3_update, "delete": _s3_delete},
- "AWS::S3::MultiRegionAccessPoint": {"create": _s3_mrap_create, "delete": _s3_mrap_delete},
+ "AWS::S3::MultiRegionAccessPoint": {
+ "create": _s3_mrap_create,
+ "update": _replacing_update(_s3_mrap_create, _s3_mrap_delete),
+ "update_with_logical_id": True,
+ "delete": _s3_mrap_delete,
+ },
"AWS::S3::BucketPolicy": {
"create": _s3_bucket_policy_create,
"update": _s3_bucket_policy_update,
@@ -13241,7 +13281,12 @@ _RESOURCE_HANDLERS = {
"update_with_logical_id": True,
"delete": _asg_delete,
},
- "AWS::AutoScaling::LaunchConfiguration": {"create": _asg_lc_create, "delete": _asg_lc_delete},
+ "AWS::AutoScaling::LaunchConfiguration": {
+ "create": _asg_lc_create,
+ "update": _replacing_update(_asg_lc_create, _asg_lc_delete),
+ "update_with_logical_id": True,
+ "delete": _asg_lc_delete,
+ },
"AWS::AutoScaling::ScalingPolicy": {
"create": _asg_policy_create,
"update": _asg_policy_update,
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index babbd6ef..337d02c1 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -12698,6 +12698,105 @@ def test_s3_mrap_alias_matches_the_documented_pattern():
assert pattern.fullmatch(alias), alias
+def _mrap_replace_template(bucket, name=None, fail=False):
+ props = {"Regions": [{"Bucket": bucket}]}
+ if name:
+ props["Name"] = name
+ body = json.dumps({
+ "Resources": {"Mrap": {"Type": "AWS::S3::MultiRegionAccessPoint", "Properties": props}},
+ "Outputs": {"Ref": {"Value": {"Ref": "Mrap"}},
+ "Alias": {"Value": {"Fn::GetAtt": ["Mrap", "Alias"]}}},
+ })
+ return _cfn_with_failing_resource(body, "Mrap") if fail else body
+
+
+def _mrap_buckets(s3, uid):
+ """Two buckets, each holding its own name under the key who.txt."""
+ buckets = [f"cfn-mrap-{uid}-one", f"cfn-mrap-{uid}-two"]
+ for bucket in buckets:
+ s3.create_bucket(Bucket=bucket)
+ s3.put_object(Bucket=bucket, Key="who.txt", Body=bucket.encode())
+ return buckets
+
+
+def test_cfn_s3_mrap_change_under_generated_name_replaces_it(cfn, s3):
+ """Every property is create-only: a Regions change is a replacement. The
+ new access point gets a new name and alias, and the old one is removed."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-mrap-gen-{uid}"
+ one, two = _mrap_buckets(s3, uid)
+ cfn.create_stack(StackName=stack_name, TemplateBody=_mrap_replace_template(one))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ old_ref, old_alias = _output(stack, "Ref"), _output(stack, "Alias")
+
+ cfn.create_change_set(StackName=stack_name, ChangeSetName="regions",
+ TemplateBody=_mrap_replace_template(two))
+ change = cfn.describe_change_set(StackName=stack_name, ChangeSetName="regions")
+ assert change["Changes"][0]["ResourceChange"]["Replacement"] == "True"
+ cfn.execute_change_set(StackName=stack_name, ChangeSetName="regions")
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ new_ref, new_alias = _output(stack, "Ref"), _output(stack, "Alias")
+ assert new_ref != old_ref and new_alias != old_alias
+ assert _mrap_get(new_alias, "who.txt") == (200, two)
+ with pytest.raises(urllib.error.HTTPError):
+ _mrap_get(old_alias, "who.txt")
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_s3_mrap_change_under_custom_name_fails_loudly(cfn, s3):
+ """With an explicit Name the replacement is refused and the access point
+ keeps its alias and its buckets."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-mrap-named-{uid}"
+ one, two = _mrap_buckets(s3, uid)
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_mrap_replace_template(one, name=f"mrap-{uid}"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ alias = _output(stack, "Alias")
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=_mrap_replace_template(two, name=f"mrap-{uid}"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ assert "custom-named resource requires replacing" in \
+ _stack_event_reasons(cfn, stack_name)
+ assert (_output(stack, "Ref"), _output(stack, "Alias")) == (f"mrap-{uid}", alias)
+ assert _mrap_get(alias, "who.txt") == (200, one)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_s3_mrap_replacement_rolls_back(cfn, s3):
+ """When a later resource fails, the replacement is deleted and the
+ original access point is still the one the stack reports."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-mrap-rb-{uid}"
+ one, two = _mrap_buckets(s3, uid)
+ cfn.create_stack(StackName=stack_name, TemplateBody=_mrap_replace_template(one))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ before = (_output(stack, "Ref"), _output(stack, "Alias"))
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=_mrap_replace_template(two, fail=True))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ assert (_output(stack, "Ref"), _output(stack, "Alias")) == before
+ assert _mrap_get(before[1], "who.txt") == (200, one)
+ events = _all_pages(cfn, "describe_stack_events", "StackEvents", StackName=stack_name)
+ assert any(e["LogicalResourceId"] == "Mrap" and e["ResourceStatus"] == "DELETE_COMPLETE"
+ and e["PhysicalResourceId"] not in ("", *before) for e in events)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
def test_cfn_auto_named_s3_bucket_stable_across_updates(cfn, s3):
"""Regression: auto-named S3 buckets (no explicit BucketName) must keep
the same physical resource ID across stack updates. Before the fix,
@@ -26772,6 +26871,104 @@ def test_cfn_asg_update_keeps_arn_and_created_time(cfn, autoscaling):
_delete_cfn_test_stack(cfn, stack_name)
+def _cfn_lc_template(image, name=None, fail=False):
+ props = {"ImageId": image, "InstanceType": "t3.micro"}
+ if name:
+ props["LaunchConfigurationName"] = name
+ body = json.dumps({
+ "Resources": {
+ "LC": {"Type": "AWS::AutoScaling::LaunchConfiguration", "Properties": props},
+ "ASG": {"Type": "AWS::AutoScaling::AutoScalingGroup", "Properties": {
+ "LaunchConfigurationName": {"Ref": "LC"}, "MinSize": "0", "MaxSize": "1",
+ "AvailabilityZones": ["us-east-1a"]}},
+ },
+ "Outputs": {"LC": {"Value": {"Ref": "LC"}}, "ASG": {"Value": {"Ref": "ASG"}}},
+ })
+ return _cfn_with_failing_resource(body, "ASG") if fail else body
+
+
+def _cfn_lc_images(autoscaling, *names):
+ return [lc["ImageId"] for lc in autoscaling.describe_launch_configurations(
+ LaunchConfigurationNames=list(names))["LaunchConfigurations"]]
+
+
+def _cfn_asg_lc_name(autoscaling, group):
+ return autoscaling.describe_auto_scaling_groups(
+ AutoScalingGroupNames=[group])["AutoScalingGroups"][0]["LaunchConfigurationName"]
+
+
+def test_cfn_launch_configuration_change_under_generated_name_replaces_it(cfn, autoscaling):
+ """Every property is create-only: an ImageId change creates a launch
+ configuration under a new name, the group moves to it, and the old one
+ is removed."""
+ stack_name = f"cfn-lc-gen-{_uuid_mod.uuid4().hex[:8]}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_lc_template("ami-11111111"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ old = _output(stack, "LC")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_lc_template("ami-22222222"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ new = _output(stack, "LC")
+ assert new != old and new.startswith(f"{stack_name}-LC-")
+ assert _cfn_asg_lc_name(autoscaling, _output(stack, "ASG")) == new
+ assert _cfn_lc_images(autoscaling, new) == ["ami-22222222"]
+ assert _cfn_lc_images(autoscaling, old) == []
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_launch_configuration_change_under_custom_name_fails_loudly(cfn, autoscaling):
+ """With an explicit LaunchConfigurationName the replacement is refused."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-lc-named-{uid}"
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_lc_template("ami-11111111", name=f"lc-{uid}"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=_cfn_lc_template("ami-22222222", name=f"lc-{uid}"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ assert "custom-named resource requires replacing" in \
+ _stack_event_reasons(cfn, stack_name)
+ assert _cfn_lc_images(autoscaling, f"lc-{uid}") == ["ami-11111111"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_launch_configuration_replacement_rolls_back(cfn, autoscaling):
+ """When a later resource fails, the group goes back to the original
+ launch configuration, which kept its properties, and the replacement is
+ deleted."""
+ stack_name = f"cfn-lc-rb-{_uuid_mod.uuid4().hex[:8]}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_lc_template("ami-11111111"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ old = _output(stack, "LC")
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=_cfn_lc_template("ami-22222222", fail=True))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ assert _output(stack, "LC") == old
+ assert _cfn_asg_lc_name(autoscaling, _output(stack, "ASG")) == old
+ names = [lc["LaunchConfigurationName"] for lc in _all_pages(
+ autoscaling, "describe_launch_configurations", "LaunchConfigurations")]
+ assert [n for n in names if n.startswith(f"{stack_name}-LC-")] == [old]
+ assert _cfn_lc_images(autoscaling, old) == ["ami-11111111"]
+ events = _all_pages(cfn, "describe_stack_events", "StackEvents", StackName=stack_name)
+ assert any(e["LogicalResourceId"] == "LC" and e["ResourceStatus"] == "DELETE_COMPLETE"
+ and e["PhysicalResourceId"] not in ("", old) for e in events)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
def test_cfn_asg_scaling_policy_update_keeps_arn(cfn, autoscaling):
"""A policy update keeps its ARN."""
suffix = _uuid_mod.uuid4().hex[:8]