Skip to content

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

fix(cloudformation): delete the resources a nested stack's update drops (#1858)

iot-rockete72dbb8ce8d3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6f2aacb5..021ae158 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **Lambda — Docker executor honors timeouts above 300 seconds** — pass the configured `Timeout` to AWS RIE through `AWS_LAMBDA_FUNCTION_TIMEOUT`, preventing its default 300-second limit from ending longer invocations early. Timeout updates recycle warm containers so the RIE deadline follows the new configuration (#1844).
- **KMS — `GenerateDataKey` returns `KeyMaterialId`** — requests without `Recipient` now include the identifier of the wrapping key material. The identifier remains stable across requests and persistence reloads, and changes when the wrapping material changes. Fixes #1853.
+- **CloudFormation — a nested stack's update deletes the resources its template drops** — a resource removed from the child template, or created by a failed child update that was rolled back, stayed in its service and in the nested stack's resource list. Contributed by @iot-rocket.
### Added
- **KMS — grants** — `CreateGrant`, `RevokeGrant` and `RetireGrant`, and `ListGrants` returns the grants they create instead of always an empty list. `CreateGrant` returns a `GrantId` and a `GrantToken`, follows the key state (`DisabledException` for a disabled key, `KMSInvalidStateException` pending deletion, replica deletion or import), rejects operations the key cannot perform (`Sign` / `Verify` / `GenerateMac` / `VerifyMac` on a symmetric encryption key, data key operations on an asymmetric key, anything but `GenerateMac` / `VerifyMac` / `DescribeKey` / `CreateGrant` / `RetireGrant` on an HMAC key) with `ValidationException`, and with a `Name` a retry with identical parameters returns the original `GrantId` with a new token. `ListGrants` filters by `GrantId` and `GranteePrincipal` and pages with `Limit` (1 to 100, default 50) and `Marker`. `RetireGrant` takes a `GrantToken`, or a `KeyId` and `GrantId`. All three honour `DryRun`, and grants persist with the key. Grants are recorded but not evaluated when authorizing other calls, as with key policies. Contributed by @DaviReisVieira.
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index f9dd6434..6adb63c1 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -4022,8 +4022,9 @@ def _cfn_nested_stack_deploy(logical_id, props, parent_stack_name, *,
f"{status_prefix}_COMPLETE", physical_id=physical_id)
if is_update:
- for stale_id in set(prev_resources) - set(provisioned):
+ for stale_id in set(prev_resources) - set(ordered):
old = prev_resources[stale_id]
+ provisioned.pop(stale_id, None)
try:
_delete_resource(old.get("ResourceType", ""),
old.get("PhysicalResourceId", ""),
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 6673d751..5e6be157 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -22603,6 +22603,59 @@ def test_cfn_nested_stack_child_reads_its_own_update_replace_policy(monkeypatch)
_ssm._parameters.pop(name, None)
[email protected]("updated, status, kept, gone", [
+ (["Keep"], "UPDATE_COMPLETE", ["Keep"], "Drop"),
+ (["Keep", "Drop", "New", "Bad"], "UPDATE_ROLLBACK_COMPLETE", ["Drop", "Keep"], "New"),
+], ids=["dropped", "rolled-back"])
+def test_cfn_nested_stack_update_deletes_what_the_child_no_longer_has(
+ cfn, s3, ssm, updated, status, kept, gone):
+ """A child resource the nested stack's update drops or rolls back is deleted and unlisted."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ bucket = f"cfn-nested-prune-{suffix}"
+ names = {lid: f"/cfn-nested-prune-{suffix}/{lid}" for lid in ("Keep", "Drop", "New")}
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")
+
+ def child(ids):
+ return json.dumps({"Resources": {
+ lid: {**_FAILING_RESOURCE, "DependsOn": "New"} if lid == "Bad" else {
+ "Type": "AWS::SSM::Parameter",
+ "Properties": {"Name": names[lid], "Type": "String", "Value": "v"}}
+ for lid in ids}})
+
+ def parent(key):
+ return json.dumps({
+ "Resources": {"Nested": {
+ "Type": "AWS::CloudFormation::Stack",
+ "Properties": {"TemplateURL": f"{endpoint}/{bucket}/{key}"}}},
+ "Outputs": {"NestedId": {"Value": {"Ref": "Nested"}}},
+ })
+
+ stack_name = f"cfn-nested-prune-{suffix}"
+ s3.create_bucket(Bucket=bucket)
+ try:
+ s3.put_object(Bucket=bucket, Key="v1.json", Body=child(["Keep", "Drop"]).encode())
+ s3.put_object(Bucket=bucket, Key="v2.json", Body=child(updated).encode())
+ cfn.create_stack(StackName=stack_name, TemplateBody=parent("v1.json"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ nested_id = _output(stack, "NestedId")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=parent("v2.json"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == status, stack.get("StackStatusReason")
+ listed = cfn.describe_stack_resources(StackName=nested_id)["StackResources"]
+ assert sorted(r["LogicalResourceId"] for r in listed) == kept
+ for lid in kept:
+ ssm.get_parameter(Name=names[lid])
+ with pytest.raises(ClientError, match="ParameterNotFound"):
+ ssm.get_parameter(Name=names[gone])
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ for key in ("v1.json", "v2.json"):
+ s3.delete_object(Bucket=bucket, Key=key)
+ s3.delete_bucket(Bucket=bucket)
+
+
def test_cfn_apigw_api_key_rename_replaces_it(cfn, apigw_v1):
"""Name is Replacement on AWS::ApiGateway::ApiKey: the renamed key is
created before the old one is removed, so Ref moves to a new key id and