Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(cloudformation): honour DeletionPolicy and UpdateReplacePolicy (#1646)
iot-rocket89de85035a2d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f5091a15..81f138af 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,14 @@ All notable changes to MiniStack will be documented here.Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).Versioning follows [Semantic Versioning](https://semver.org/).+## [Unreleased]++### Fixed+- **CloudFormation — a change set sees `DeletionPolicy`, `UpdateReplacePolicy` and `Metadata` edits** — the diff compared `Properties` only, so a change set that only changed a resource's removal policy (a CDK `removalPolicy` edit) ended `FAILED` with "didn't contain changes" and the policy never reached the stack. Those attributes now count as a `Modify` with `Replacement: False` and are reported in `Scope` and `Details` with the target attribute, as the API reference defines them; a property change lists the property names. A `DependsOn`-only edit stays a no-change set, as on AWS. Contributed by @iot-rocket.++### Added+- **CloudFormation — `DeletionPolicy` and `UpdateReplacePolicy` are honoured** — neither attribute was read, so a `Retain` resource was deleted with its stack, when it was dropped from the template, and when a replacement retired it. A retained resource now stays and leaves the stack's scope with a `DELETE_SKIPPED` event, on stack delete, on removal and on replacement; `RetainExceptOnCreate` (the policy and the API parameter of the same name on CreateStack, UpdateStack and ExecuteChangeSet) deletes what the rolled-back operation itself created; `DeleteStack` takes `RetainResources` for a stack in `DELETE_FAILED` and refuses it otherwise. `Snapshot` deletes, since the emulator takes no snapshots. Contributed by @iot-rocket.+## [1.5.8] — 2026-09-05### Addeddiff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.pyindex c4267639..f1aa793d 100644--- a/ministack/services/cloudformation/changesets.py+++ b/ministack/services/cloudformation/changesets.py@@ -258,12 +258,33 @@ def _describe_change_set(params):changes_xml = ""for ch in cs.get("Changes", []):rc = ch.get("ResourceChange", {})+ scope_xml = "".join(f"<member>{_esc(a)}</member>" for a in rc.get("Scope", []))+ details_xml = ""+ for d in rc.get("Details", []):+ target = d.get("Target", {})+ target_xml = f"<Attribute>{_esc(target.get('Attribute', ''))}</Attribute>"+ if target.get("Name"):+ target_xml += f"<Name>{_esc(target['Name'])}</Name>"+ if target.get("RequiresRecreation"):+ target_xml += (+ f"<RequiresRecreation>{_esc(target['RequiresRecreation'])}"+ "</RequiresRecreation>"+ )+ details_xml += (+ "<member>"+ f"<Target>{target_xml}</Target>"+ f"<Evaluation>{_esc(d.get('Evaluation', 'Static'))}</Evaluation>"+ f"<ChangeSource>{_esc(d.get('ChangeSource', 'DirectModification'))}</ChangeSource>"+ "</member>"+ )changes_xml += ("<member><ResourceChange>"f"<Action>{rc.get('Action', '')}</Action>"f"<LogicalResourceId>{_esc(rc.get('LogicalResourceId', ''))}</LogicalResourceId>"f"<ResourceType>{_esc(rc.get('ResourceType', ''))}</ResourceType>"f"<Replacement>{rc.get('Replacement', '')}</Replacement>"+ f"<Scope>{scope_xml}</Scope>"+ f"<Details>{details_xml}</Details>""</ResourceChange></member>")@@ -350,10 +371,12 @@ def _execute_change_set(params):"_template": copy.deepcopy(stack.get("_template", {})),"_template_body": stack.get("_template_body", ""),"_resolved_params": copy.deepcopy(stack.get("_resolved_params", {})),+ "_conditions": copy.deepcopy(stack.get("_conditions", {})),"Outputs": copy.deepcopy(stack.get("Outputs", [])),}else:previous_stack = None+ retain_except_on_create = _p(params, "RetainExceptOnCreate", "false").lower() == "true"status_prefix = "UPDATE" if is_update else "CREATE"stack["StackStatus"] = f"{status_prefix}_IN_PROGRESS"@@ -379,7 +402,8 @@ def _execute_change_set(params):_deploy_stack_async(real_stack_name, stack_id, template,param_values, False, tags,is_update=is_update,- previous_stack=previous_stack),+ previous_stack=previous_stack,+ retain_except_on_create=retain_except_on_create),),stack,stack_id,diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.pyindex 670f30ce..85681882 100644--- a/ministack/services/cloudformation/handlers.py+++ b/ministack/services/cloudformation/handlers.py@@ -25,7 +25,16 @@ from .engine import (_resolve_refs,validate_template_support,)-from .helpers import _error, _esc, _extract_members, _extract_stack_status_filters, _p, _resolve_template, _xml+from .helpers import (+ _error,+ _esc,+ _extract_members,+ _extract_stack_status_filters,+ _extract_string_members,+ _p,+ _resolve_template,+ _xml,+)from .stacks import (_add_event,_create_stack_task_in_region,@@ -67,6 +76,7 @@ def _create_stack(params):provided_params = _extract_members(params, "Parameters")tags = _extract_members(params, "Tags")disable_rollback = _p(params, "DisableRollback", "false").lower() == "true"+ retain_except_on_create = _p(params, "RetainExceptOnCreate", "false").lower() == "true"# Resolve parameterstry:@@ -120,7 +130,8 @@ def _create_stack(params):_create_stack_task_in_region(_deploy_stack_async(stack_name, stack_id, template,- param_values, disable_rollback, tags),+ param_values, disable_rollback, tags,+ retain_except_on_create=retain_except_on_create),stack,stack_id,)@@ -510,6 +521,20 @@ def _delete_stack(params):stack_id = stack["StackId"]+ # RetainResources: only for a DELETE_FAILED stack, only its own resources.+ retain = _extract_string_members(params, "RetainResources")+ if retain:+ if stack.get("StackStatus") != "DELETE_FAILED":+ return _error("ValidationError",+ f"Stack [{stack_name}] is not in DELETE_FAILED state; "+ "RetainResources can only be specified for a stack in "+ "DELETE_FAILED state")+ unknown = sorted(set(retain) - set(stack.get("_resources", {})))+ if unknown:+ return _error("ValidationError",+ f"Resource(s) [{', '.join(unknown)}] do not exist in "+ f"stack [{stack_name}]")+# Deleting a stack removes its change sets; they must not outlive it and# shadow a later same-named change set on a re-created stack. #1418from ministack.services.cloudformation import _change_sets@@ -518,7 +543,7 @@ def _delete_stack(params):_change_sets.pop(_cid, None)_create_stack_task_in_region(- _delete_stack_async(stack_name, stack_id),+ _delete_stack_async(stack_name, stack_id, frozenset(retain)),stack,stack_id,)@@ -590,6 +615,7 @@ def _update_stack(params):provided_params = _extract_members(params, "Parameters")tags = _extract_members(params, "Tags")disable_rollback = _p(params, "DisableRollback", "false").lower() == "true"+ retain_except_on_create = _p(params, "RetainExceptOnCreate", "false").lower() == "true"try:param_values = _resolve_parameters(@@ -612,6 +638,7 @@ def _update_stack(params):"_template": copy.deepcopy(stack.get("_template", {})),"_template_body": stack.get("_template_body", ""),"_resolved_params": copy.deepcopy(stack.get("_resolved_params", {})),+ "_conditions": copy.deepcopy(stack.get("_conditions", {})),"Parameters": copy.deepcopy(stack.get("Parameters", [])),"Tags": copy.deepcopy(stack.get("Tags", [])),"Outputs": copy.deepcopy(stack.get("Outputs", [])),@@ -646,7 +673,8 @@ def _update_stack(params):_create_stack_task_in_region(_deploy_stack_async(stack_name, stack_id, template,param_values, disable_rollback, tags,- is_update=True, previous_stack=previous_stack),+ is_update=True, previous_stack=previous_stack,+ retain_except_on_create=retain_except_on_create),stack,stack_id,)diff --git a/ministack/services/cloudformation/helpers.py b/ministack/services/cloudformation/helpers.pyindex 6bed9b03..27ac1673 100644--- a/ministack/services/cloudformation/helpers.py+++ b/ministack/services/cloudformation/helpers.py@@ -111,3 +111,20 @@ def _extract_stack_status_filters(params):filters.append(val)i += 1return filters+++def _extract_string_members(params, prefix):+ """Extract a plain string list (``RetainResources.member.N``); the JSON+ protocol sends it as a list under the bare key."""+ direct = params.get(prefix)+ if isinstance(direct, list):+ return [str(v) for v in direct]+ result = []+ i = 1+ while True:+ value = _p(params, f"{prefix}.member.{i}")+ if not value:+ break+ result.append(value)+ i += 1+ return resultdiff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex a9f8bda5..09645a3b 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -5,6 +5,7 @@ CloudFormation provisioners — resource create/delete handlers for each AWS res"""import base64+import contextvarsimport copyimport hashlibimport io@@ -451,18 +452,26 @@ def _custom_named_replacement_error(resource_type, old_props, new_props):return None+# Set by the stack engine around an update whose resource carries+# ``UpdateReplacePolicy: Retain`` (or ``RetainExceptOnCreate``): a handler that+# replaces the resource must then leave the predecessor in place; the engine+# records the DELETE_SKIPPED event.+_RETAIN_REPLACED = contextvars.ContextVar("cfn_retain_replaced", default=False)++def _rename_replacement(physical_id, old_props, new_props, stack_name, logical_id,declared_name, current_name, create_fn, delete_fn):"""Shared prologue for the name-keyed update handlers: when the resourcerecord is gone (current_name is None) or its create-only name propertychanged, the update is a replacement — create the new resource first, then- delete the old one, in CloudFormation's replacement order. Returns the- create result, or None when the update can proceed in place.+ delete the old one, in CloudFormation's replacement order (unless the+ resource's UpdateReplacePolicy retains it). Returns the create result, or+ None when the update can proceed in place."""if current_name is not None and declared_name == current_name:return Nonecreated = create_fn(logical_id or physical_id, new_props, stack_name)- if current_name is not None and created[0] != physical_id:+ if current_name is not None and created[0] != physical_id and not _RETAIN_REPLACED.get():delete_fn(physical_id, old_props)return createddiff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.pyindex a564e143..a2ab5e2a 100644--- a/ministack/services/cloudformation/stacks.py+++ b/ministack/services/cloudformation/stacks.py@@ -18,7 +18,12 @@ from .engine import (_resolve_refs,_topological_sort,)-from .provisioners import _delete_resource, _provision_resource, _update_resource+from .provisioners import (+ _RETAIN_REPLACED,+ _delete_resource,+ _provision_resource,+ _update_resource,+)logger = logging.getLogger("cloudformation")@@ -62,6 +67,31 @@ def _is_custom_resource(resource_type: str) -> bool:# Stack Events helper# ===========================================================================+# The policies that keep a resource. Snapshot is not among them: the emulator+# takes no snapshots, so a Snapshot resource is deleted like a Delete one.+_RETAINING_POLICIES = ("Retain", "RetainExceptOnCreate")+++def _resource_policy(res_def, attribute, resources, params, conditions, mappings,+ stack_name, stack_id):+ """A resource's ``DeletionPolicy`` / ``UpdateReplacePolicy`` as a string,+ ``Delete`` when the template sets none. An intrinsic (``Fn::If``) is+ resolved like a property; one that does not resolve counts as ``Delete``+ and is logged, since that is the destructive reading."""+ value = (res_def or {}).get(attribute)+ if value is None:+ return "Delete"+ if isinstance(value, dict):+ try:+ value = _resolve_refs(copy.deepcopy(value), resources, params, conditions,+ mappings, stack_name, stack_id)+ except Exception as exc:+ logger.warning("%s of %s in %s did not resolve (%s); treating it as Delete",+ attribute, stack_name, value, exc)+ return "Delete"+ return str(value)++def _add_event(stack_id, stack_name, logical_id, resource_type, status,reason="", physical_id=""):"""Record a stack event."""@@ -129,8 +159,13 @@ def _resolve_stack_outputs(outputs_defs, conditions, resources, param_values,async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,param_values: dict, disable_rollback: bool,tags: list, is_update: bool = False,- previous_stack: dict | None = None):- """Background task: provision resources and set final stack status."""+ previous_stack: dict | None = None,+ retain_except_on_create: bool = False):+ """Background task: provision resources and set final stack status.++ ``retain_except_on_create`` is the API parameter of the same name: a+ rollback of this operation then deletes what the operation created even+ when the template says ``DeletionPolicy: Retain``."""from ministack.services.cloudformation import _exports, _stacksstatus_prefix = "UPDATE" if is_update else "CREATE"stack = _stacks[stack_name]@@ -201,16 +236,27 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,old_pid = prev_resource.get("PhysicalResourceId", logical_id)old_props = prev_resource.get("Properties", {})old_attrs = prev_resource.get("Attributes", {})- if _is_custom_resource(resource_type):- physical_id, attrs = await run_reentrant(- _update_resource, resource_type, old_pid, old_props,- resolved_props, stack_name, logical_id, old_attrs- )- else:- physical_id, attrs = _update_resource(- resource_type, old_pid, old_props, resolved_props,- stack_name, logical_id, old_attrs- )+ # A handler that replaces the resource itself (the name-keyed+ # ones) must leave the predecessor alone when the template+ # retains it; the cleanup below then records DELETE_SKIPPED.+ retain_replaced = _resource_policy(+ res_def, "UpdateReplacePolicy", provisioned_resources,+ param_values, conditions, mappings, stack_name, stack_id,+ ) in _RETAINING_POLICIES+ token = _RETAIN_REPLACED.set(retain_replaced)+ try:+ if _is_custom_resource(resource_type):+ physical_id, attrs = await run_reentrant(+ _update_resource, resource_type, old_pid, old_props,+ resolved_props, stack_name, logical_id, old_attrs+ )+ else:+ physical_id, attrs = _update_resource(+ resource_type, old_pid, old_props, resolved_props,+ stack_name, logical_id, old_attrs+ )+ finally:+ _RETAIN_REPLACED.reset(token)if physical_id != old_pid:# A changed physical id is a replacement. Real# CloudFormation deletes the predecessor in the@@ -254,6 +300,16 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,# predecessor, as real CloudFormation does after UPDATE_COMPLETE.if not failed and replaced_resources:for logical_id, rtype, old_pid, old_props in replaced_resources:+ policy = _resource_policy(+ resources_defs.get(logical_id), "UpdateReplacePolicy",+ provisioned_resources, param_values, conditions, mappings,+ stack_name, stack_id)+ if policy in _RETAINING_POLICIES:+ # The predecessor leaves CloudFormation's scope and keeps+ # existing, as on AWS (a DELETE_SKIPPED event, no delete call).+ _add_event(stack_id, stack_name, logical_id, rtype,+ "DELETE_SKIPPED", physical_id=old_pid)+ continuetry:if _is_custom_resource(rtype):await run_reentrant(@@ -271,11 +327,23 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,# Delete removed resources (update case)if not failed and to_remove:old_resources = previous_stack.get("_resources", {})+ old_template = previous_stack.get("_template", {}) or {}+ old_defs = old_template.get("Resources", {}) or {}for logical_id in to_remove:old_res = old_resources.get(logical_id, {})rtype = old_res.get("ResourceType", "")pid = old_res.get("PhysicalResourceId", "")old_props = old_res.get("Properties", {})+ policy = _resource_policy(+ old_defs.get(logical_id), "DeletionPolicy", old_resources,+ previous_stack.get("_resolved_params", {}),+ previous_stack.get("_conditions", conditions),+ old_template.get("Mappings", {}), stack_name, stack_id)+ if policy in _RETAINING_POLICIES:+ _add_event(stack_id, stack_name, logical_id, rtype,+ "DELETE_SKIPPED", physical_id=pid)+ provisioned_resources.pop(logical_id, None)+ continuetry:if _is_custom_resource(rtype):await run_reentrant(@@ -349,6 +417,18 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,# resources and replacements under a new physical id are# undone. An in-place change is not reverted here.continue+ policy = _resource_policy(+ resources_defs.get(logical_id), "DeletionPolicy",+ provisioned_resources, param_values, conditions, mappings,+ stack_name, stack_id)+ if policy == "Retain" and not retain_except_on_create:+ # ``Retain`` survives even the rollback of the operation+ # that created it; ``RetainExceptOnCreate`` and the API+ # parameter of that name are exactly the exception.+ _add_event(stack_id, stack_name, logical_id, rtype,+ "DELETE_SKIPPED", physical_id=pid)+ provisioned_resources.pop(logical_id, None)+ continuetry:if _is_custom_resource(rtype):await run_reentrant(@@ -417,8 +497,14 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,physical_id=stack_id)-async def _delete_stack_async(stack_name: str, stack_id: str):- """Background task: delete all resources and mark stack DELETE_COMPLETE."""+async def _delete_stack_async(stack_name: str, stack_id: str,+ retain_resources=()):+ """Background task: delete all resources and mark stack DELETE_COMPLETE.++ A resource whose ``DeletionPolicy`` is ``Retain`` or+ ``RetainExceptOnCreate``, or whose logical id is in ``retain_resources``+ (the ``RetainResources`` parameter of a DeleteStack on a ``DELETE_FAILED``+ stack), is skipped with a ``DELETE_SKIPPED`` event and keeps existing."""from ministack.services.cloudformation import _exports, _stacksstack = _stacks.get(stack_name)if not stack:@@ -451,6 +537,16 @@ async def _delete_stack_async(stack_name: str, stack_id: str):pid = res.get("PhysicalResourceId", "")res_props = res.get("Properties", {})+ policy = _resource_policy(+ res_defs.get(logical_id), "DeletionPolicy", resources,+ stack.get("_resolved_params", {}), conditions,+ template.get("Mappings", {}) if template else {}, stack_name, stack_id)+ if policy in _RETAINING_POLICIES or logical_id in retain_resources:+ _add_event(stack_id, stack_name, logical_id, rtype,+ "DELETE_SKIPPED", physical_id=pid)+ resources.pop(logical_id, None)+ continue+_add_event(stack_id, stack_name, logical_id, rtype,"DELETE_IN_PROGRESS", physical_id=pid)try:@@ -504,8 +600,29 @@ async def _delete_stack_async(stack_name: str, stack_id: str):# Change Set Helpers# ===========================================================================+# The resource attributes a change set compares next to Properties; each is+# also the ResourceTargetDefinition Attribute value it reports. A change to one+# of them alone is a Modify with Replacement False (measured: an+# UpdateReplacePolicy edit lists `Modify / False / UpdateReplacePolicy`). A Type+# change is handled apart (a replacement). DependsOn and Condition are absent on+# purpose: a DependsOn-only edit did not show up as a change on AWS.+_DIFFED_ATTRIBUTES = (+ "Metadata",+ "CreationPolicy",+ "UpdatePolicy",+ "DeletionPolicy",+ "UpdateReplacePolicy",+)++def _diff_resources(old_template: dict, new_template: dict) -> list:- """Diff two templates and return a list of change dicts."""+ """Diff two templates and return a list of change dicts.++ A resource is a ``Modify`` when its ``Properties`` differ or when one of the+ attributes in ``_DIFFED_ATTRIBUTES`` differs; each changed attribute becomes+ a ``Details`` entry (``Target.Attribute``, plus the property name for+ ``Properties``) and is listed in ``Scope``, as the API reference defines them.+ """old_res = old_template.get("Resources", {})new_res = new_template.get("Resources", {})changes = []@@ -532,15 +649,44 @@ def _diff_resources(old_template: dict, new_template: dict) -> list:}})else:- old_props = old_res[key].get("Properties", {})- new_props = new_res[key].get("Properties", {})+ details = []+ old_props = old_res[key].get("Properties", {}) or {}+ new_props = new_res[key].get("Properties", {}) or {}if old_props != new_props:- changes.append({- "ResourceChange": {- "Action": "Modify",- "LogicalResourceId": key,- "ResourceType": new_res[key].get("Type", ""),- "Replacement": "Conditional",- }- })+ for name in sorted(set(old_props) | set(new_props)):+ if old_props.get(name) != new_props.get(name):+ details.append({+ "Target": {"Attribute": "Properties", "Name": name,+ "RequiresRecreation": "Conditionally"},+ "Evaluation": "Static",+ "ChangeSource": "DirectModification",+ })+ for attr in _DIFFED_ATTRIBUTES:+ if old_res[key].get(attr) != new_res[key].get(attr):+ details.append({+ "Target": {"Attribute": attr},+ "Evaluation": "Static",+ "ChangeSource": "DirectModification",+ })+ type_changed = old_res[key].get("Type") != new_res[key].get("Type")+ if not details and not type_changed:+ continue+ scope = []+ for d in details:+ if d["Target"]["Attribute"] not in scope:+ scope.append(d["Target"]["Attribute"])+ if type_changed or old_props != new_props:+ replacement = "True" if type_changed else "Conditional"+ else:+ replacement = "False"+ changes.append({+ "ResourceChange": {+ "Action": "Modify",+ "LogicalResourceId": key,+ "ResourceType": new_res[key].get("Type", ""),+ "Replacement": replacement,+ "Scope": scope,+ "Details": details,+ }+ })return changesdiff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 4121a271..2772c35e 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -1350,6 +1350,77 @@ def test_cfn_change_set_no_changes_is_failed(cfn, ssm):cfn.delete_stack(StackName=S)+def test_cfn_change_set_sees_policy_and_metadata_changes(cfn, sqs):+ """A change set lists a resource whose DeletionPolicy, UpdateReplacePolicy+ or Metadata changed and nothing else: Modify, Replacement False, the+ attribute in Scope and Details, and the executed set stores the new+ template. A DependsOn-only edit is not a change, as on AWS."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-cs-attrs-{uid}"++ def template(policy=None, depends=False, metadata=None, queue_name=None):+ queue = {"Type": "AWS::SQS::Queue",+ "Properties": {"QueueName": queue_name or f"cfn-cs-attrs-{uid}"}}+ if policy:+ queue["DeletionPolicy"] = policy+ queue["UpdateReplacePolicy"] = policy+ if metadata:+ queue["Metadata"] = metadata+ param = {"Type": "AWS::SSM::Parameter",+ "Properties": {"Name": f"/cfn-cs-attrs/{uid}", "Type": "String",+ "Value": "v"}}+ if depends:+ param["DependsOn"] = "Queue"+ return json.dumps({"Resources": {"Queue": queue, "Param": param}})++ def changes_of(name, body):+ cfn.create_change_set(StackName=stack_name, ChangeSetName=name,+ ChangeSetType="UPDATE", TemplateBody=body)+ return cfn.describe_change_set(ChangeSetName=name, StackName=stack_name)++ cfn.create_stack(StackName=stack_name, TemplateBody=template())+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")++ described = changes_of("depends-only", template(depends=True))+ assert described["Status"] == "FAILED"+ assert "didn't contain changes" in described["StatusReason"]++ described = changes_of("retain", template(policy="Retain", depends=True))+ assert described["Status"] == "CREATE_COMPLETE", described.get("StatusReason")+ assert described["ExecutionStatus"] == "AVAILABLE"+ assert [c["ResourceChange"]["LogicalResourceId"] for c in described["Changes"]] == ["Queue"]+ change = described["Changes"][0]["ResourceChange"]+ assert change["Action"] == "Modify"+ assert change["Replacement"] == "False"+ assert sorted(change["Scope"]) == ["DeletionPolicy", "UpdateReplacePolicy"]+ assert sorted(d["Target"]["Attribute"] for d in change["Details"]) == [+ "DeletionPolicy", "UpdateReplacePolicy"]++ cfn.execute_change_set(ChangeSetName="retain", StackName=stack_name)+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")+ body = cfn.get_template(StackName=stack_name)["TemplateBody"]+ stored = json.loads(body) if isinstance(body, str) else body+ assert stored["Resources"]["Queue"]["DeletionPolicy"] == "Retain"++ described = changes_of("metadata", template(policy="Retain", depends=True,+ metadata={"owner": "fleet"}))+ change = described["Changes"][0]["ResourceChange"]+ assert change["Replacement"] == "False"+ assert change["Scope"] == ["Metadata"]++ described = changes_of("rename", template(policy="Retain", depends=True,+ queue_name=f"cfn-cs-attrs-{uid}-b"))+ change = described["Changes"][0]["ResourceChange"]+ assert change["Scope"] == ["Properties"]+ assert [d["Target"]["Name"] for d in change["Details"]] == ["QueueName"]+ assert change["Details"][0]["Target"]["RequiresRecreation"] == "Conditionally"+ finally:+ _delete_cfn_test_stack(cfn, stack_name)++def test_cfn_execute_change_set_deletes_sibling_change_sets(cfn, ssm):"""Executing a change set deletes the stack's other change sets — they areno longer valid for the updated stack (#1418)."""@@ -14306,6 +14377,278 @@ def test_cfn_update_rollback_deletes_the_replacement_and_restores_the_old_recordassert table["AttributeDefinitions"] == [{"AttributeName": "pk", "AttributeType": "S"}]finally:_delete_cfn_test_stack(cfn, stack_name)+def _queue_exists(sqs, name):+ try:+ sqs.get_queue_url(QueueName=name)+ return True+ except ClientError as exc:+ assert "NonExistentQueue" in exc.response["Error"]["Code"], exc.response["Error"]+ return False+++def _delete_queue_if_present(sqs, name):+ try:+ sqs.delete_queue(QueueUrl=sqs.get_queue_url(QueueName=name)["QueueUrl"])+ except ClientError:+ pass+++def _resource_events(cfn, stack_name, logical_id):+ return [(e["ResourceStatus"], e.get("PhysicalResourceId", ""))+ for e in cfn.describe_stack_events(StackName=stack_name)["StackEvents"]+ if e["LogicalResourceId"] == logical_id]+++def test_cfn_deletion_policy_retain_survives_the_stack_delete(cfn, sqs):+ """DeletionPolicy Retain keeps the resource when the stack is deleted: the+ queue survives with a DELETE_SKIPPED event, its sibling is deleted, the+ stack still reaches DELETE_COMPLETE."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-retain-del-{uid}"+ keep, gone = f"cfn-retain-keep-{uid}", f"cfn-retain-gone-{uid}"+ template = json.dumps({"Resources": {+ "Keep": {"Type": "AWS::SQS::Queue", "DeletionPolicy": "Retain",+ "Properties": {"QueueName": keep}},+ "Gone": {"Type": "AWS::SQS::Queue", "Properties": {"QueueName": gone}},+ }})+ cfn.create_stack(StackName=stack_name, TemplateBody=template)+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ stack_id = stack["StackId"]++ cfn.delete_stack(StackName=stack_name)+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "DELETE_COMPLETE"+ assert _queue_exists(sqs, keep)+ assert not _queue_exists(sqs, gone)+ events = _resource_events(cfn, stack_id, "Keep")+ assert ("DELETE_SKIPPED", sqs.get_queue_url(QueueName=keep)["QueueUrl"]) in events+ assert "DELETE_IN_PROGRESS" not in [status for status, _ in events]+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+ _delete_queue_if_present(sqs, keep)+ _delete_queue_if_present(sqs, gone)+++def test_cfn_update_replace_policy_retain_keeps_the_predecessor(cfn, sqs):+ """A replacement under UpdateReplacePolicy Retain leaves the old physical+ resource in place (DELETE_SKIPPED); without the policy the predecessor is+ deleted in the cleanup phase."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-retain-repl-{uid}"+ names = [f"cfn-retain-repl-{uid}-{i}" for i in ("a", "b", "c")]++ def template(name, policy):+ queue = {"Type": "AWS::SQS::Queue", "Properties": {"QueueName": name}}+ if policy:+ queue["UpdateReplacePolicy"] = policy+ return json.dumps({"Resources": {"Queue": queue}})++ cfn.create_stack(StackName=stack_name, TemplateBody=template(names[0], "Retain"))+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")++ cfn.update_stack(StackName=stack_name, TemplateBody=template(names[1], "Retain"))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")+ assert _queue_exists(sqs, names[0])+ assert _queue_exists(sqs, names[1])+ assert "DELETE_SKIPPED" in [s for s, _ in _resource_events(cfn, stack_name, "Queue")]++ cfn.update_stack(StackName=stack_name, TemplateBody=template(names[2], None))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")+ assert not _queue_exists(sqs, names[1])+ assert _queue_exists(sqs, names[2])+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+ for name in names:+ _delete_queue_if_present(sqs, name)+++def test_cfn_deletion_policy_retain_on_a_removed_resource(cfn, sqs):+ """A resource dropped from the template on update keeps existing when its+ (previous) DeletionPolicy was Retain; it leaves the stack's scope."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-retain-rm-{uid}"+ keep, other = f"cfn-retain-rm-keep-{uid}", f"cfn-retain-rm-other-{uid}"+ with_keep = json.dumps({"Resources": {+ "Keep": {"Type": "AWS::SQS::Queue", "DeletionPolicy": "Retain",+ "Properties": {"QueueName": keep}},+ "Other": {"Type": "AWS::SQS::Queue", "Properties": {"QueueName": other}},+ }})+ without = json.dumps({"Resources": {+ "Other": {"Type": "AWS::SQS::Queue", "Properties": {"QueueName": other}},+ }})+ cfn.create_stack(StackName=stack_name, TemplateBody=with_keep)+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ cfn.update_stack(StackName=stack_name, TemplateBody=without)+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")+ assert _queue_exists(sqs, keep)+ assert [r["LogicalResourceId"] for r in+ cfn.describe_stack_resources(StackName=stack_name)["StackResources"]] == ["Other"]+ assert "DELETE_SKIPPED" in [s for s, _ in _resource_events(cfn, stack_name, "Keep")]+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+ _delete_queue_if_present(sqs, keep)+++def test_cfn_retain_except_on_create_is_deleted_by_the_create_rollback(cfn, sqs):+ """Retain survives the rollback of the operation that created the resource;+ RetainExceptOnCreate does not, and neither does Retain when the request+ carries RetainExceptOnCreate=true."""+ uid = _uuid_mod.uuid4().hex[:8]+ retained, except_on_create, flagged = (+ f"cfn-reoc-retain-{uid}", f"cfn-reoc-except-{uid}", f"cfn-reoc-flag-{uid}")++ def template(name, policy):+ return json.dumps({"Resources": {+ "Queue": {"Type": "AWS::SQS::Queue", "DeletionPolicy": policy,+ "Properties": {"QueueName": name}},+ "Bad": {**_FAILING_RESOURCE, "DependsOn": "Queue"},+ }})++ stacks = [f"cfn-reoc-a-{uid}", f"cfn-reoc-b-{uid}", f"cfn-reoc-c-{uid}"]+ try:+ cfn.create_stack(StackName=stacks[0], TemplateBody=template(retained, "Retain"))+ cfn.create_stack(StackName=stacks[1],+ TemplateBody=template(except_on_create, "RetainExceptOnCreate"))+ cfn.create_stack(StackName=stacks[2], TemplateBody=template(flagged, "Retain"),+ RetainExceptOnCreate=True)+ for name in stacks:+ stack = _wait_stack(cfn, name)+ assert stack["StackStatus"] == "ROLLBACK_COMPLETE", stack.get("StackStatusReason")+ assert _queue_exists(sqs, retained)+ assert "DELETE_SKIPPED" in [s for s, _ in _resource_events(cfn, stacks[0], "Queue")]+ assert not _queue_exists(sqs, except_on_create)+ assert not _queue_exists(sqs, flagged)+ finally:+ for name in stacks:+ _delete_cfn_test_stack(cfn, name)+ for name in (retained, except_on_create, flagged):+ _delete_queue_if_present(sqs, name)+++def test_cfn_retain_except_on_create_on_an_update_rollback(cfn, sqs):+ """A resource that an update adds is "created" by that update: on the+ update's rollback RetainExceptOnCreate deletes it, Retain keeps it."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-reoc-upd-{uid}"+ base_name, kept, dropped = (f"cfn-reoc-upd-{uid}", f"cfn-reoc-upd-keep-{uid}",+ f"cfn-reoc-upd-drop-{uid}")+ base = {"Resources": {"Base": {"Type": "AWS::SQS::Queue",+ "Properties": {"QueueName": base_name}}}}+ updated = json.loads(json.dumps(base))+ updated["Resources"]["Kept"] = {"Type": "AWS::SQS::Queue", "DeletionPolicy": "Retain",+ "Properties": {"QueueName": kept}}+ updated["Resources"]["Dropped"] = {"Type": "AWS::SQS::Queue",+ "DeletionPolicy": "RetainExceptOnCreate",+ "Properties": {"QueueName": dropped}}+ updated["Resources"]["Bad"] = {**_FAILING_RESOURCE, "DependsOn": ["Kept", "Dropped"]}+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(base))+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(updated))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")+ assert _queue_exists(sqs, base_name)+ assert _queue_exists(sqs, kept)+ assert not _queue_exists(sqs, dropped)+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+ for name in (base_name, kept, dropped):+ _delete_queue_if_present(sqs, name)+++def test_cfn_deletion_policy_from_an_intrinsic(cfn, sqs):+ """A DeletionPolicy given as Fn::If resolves against the stack's+ conditions before it is applied."""+ uid = _uuid_mod.uuid4().hex[:8]+ template = json.dumps({+ "Parameters": {"Keep": {"Type": "String", "Default": "no"}},+ "Conditions": {"KeepIt": {"Fn::Equals": [{"Ref": "Keep"}, "yes"]}},+ "Resources": {"Queue": {+ "Type": "AWS::SQS::Queue",+ "DeletionPolicy": {"Fn::If": ["KeepIt", "Retain", "Delete"]},+ "Properties": {"QueueName": {"Ref": "AWS::StackName"}}}},+ })+ stacks = {f"cfn-policy-if-keep-{uid}": "yes", f"cfn-policy-if-drop-{uid}": "no"}+ try:+ for name, keep in stacks.items():+ cfn.create_stack(StackName=name, TemplateBody=template,+ Parameters=[{"ParameterKey": "Keep", "ParameterValue": keep}])+ for name in stacks:+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"+ cfn.delete_stack(StackName=name)+ assert _wait_stack(cfn, name)["StackStatus"] == "DELETE_COMPLETE"+ assert _queue_exists(sqs, f"cfn-policy-if-keep-{uid}")+ assert not _queue_exists(sqs, f"cfn-policy-if-drop-{uid}")+ finally:+ for name in stacks:+ _delete_cfn_test_stack(cfn, name)+ _delete_queue_if_present(sqs, name)+++def test_cfn_delete_stack_retain_resources_only_for_delete_failed(cfn, sqs, lam):+ """RetainResources is refused on a healthy stack; on a DELETE_FAILED stack+ it skips the named resource and the stack reaches DELETE_COMPLETE."""+ suffix = _uuid_mod.uuid4().hex[:8]+ fn = f"cr-retain-res-{suffix}"+ stack_name = f"cfn-retain-resources-{suffix}"+ queue = f"cfn-retain-resources-{suffix}"+ lam.create_function(+ FunctionName=fn,+ Runtime="python3.12",+ Role=_CR_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _cr_make_zip(_CR_HANDLER_DELETE_FAILS)},+ )+ template = json.dumps({"Resources": {+ "Queue": {"Type": "AWS::SQS::Queue", "Properties": {"QueueName": queue}},+ "CR": {"Type": "Custom::Tester", "Properties": {+ "ServiceToken": f"arn:aws:lambda:us-east-1:000000000000:function:{fn}"}},+ }})+ try:+ cfn.create_stack(StackName=stack_name, TemplateBody=template)+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")++ with pytest.raises(ClientError) as exc:+ cfn.delete_stack(StackName=stack_name, RetainResources=["CR"])+ assert exc.value.response["Error"]["Code"] == "ValidationError"+ assert "DELETE_FAILED" in exc.value.response["Error"]["Message"]++ cfn.delete_stack(StackName=stack_name)+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "DELETE_FAILED", stack.get("StackStatusReason")+ assert not _queue_exists(sqs, queue)++ with pytest.raises(ClientError) as exc:+ cfn.delete_stack(StackName=stack_name, RetainResources=["Nope"])+ assert "Nope" in exc.value.response["Error"]["Message"]++ cfn.delete_stack(StackName=stack_name, RetainResources=["CR"])+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "DELETE_COMPLETE", stack.get("StackStatusReason")+ finally:+ try:+ lam.update_function_code(FunctionName=fn, ZipFile=_cr_make_zip(_CR_HANDLER_SUCCESS))+ except ClientError:+ pass+ _delete_cfn_test_stack(cfn, stack_name)+ _delete_queue_if_present(sqs, queue)+ try:+ lam.delete_function(FunctionName=fn)+ except ClientError:+ pass++def test_cfn_delete_change_set_existing_succeeds(cfn):"""DeleteChangeSet of an existing change set succeeds -- by stack name andby stack ID -- and the response parses (boto3 needs the