Skip to content

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

fix(cloudformation): UpdateReplacePolicy Retain holds for every handler-side replacement (#1701)

iot-rocketdd5cc3d84cbd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 74bfc0b3..d6b68161 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **Transcribe — `StartTranscriptionJob` returns a job already `IN_PROGRESS`** — the start response reported `QUEUED` with no `StartTime`, and the job reached `IN_PROGRESS` only from the background worker, after the response had been sent. A caller that reads the status off the start response and then waits for the terminal `Transcribe Job State Change` event, rather than polling, therefore never saw an in-progress state at all: the job went straight from queued to complete. Jobs now start `IN_PROGRESS` with `StartTime` set, matching the response the AWS CLI walkthrough documents, and `TRANSCRIBE_JOB_RUN_SECONDS` covers the whole run rather than half of it. `QUEUED`, which AWS reaches only for a request that opted into job queueing through `JobExecutionSettings.AllowDeferredExecution` while the account is at its concurrent job limit, stays reachable through the new `TRANSCRIBE_JOB_QUEUE_SECONDS` (default `0`); both knobs are settable at runtime through `/_ministack/config`. Contributed by @ppettitau.
+- **CloudFormation — `UpdateReplacePolicy: Retain` holds for every handler-side replacement** — 24 update handlers that replace a resource themselves (a renamed SSM parameter, CloudWatch dashboard, IoT policy or provisioning template, a Cognito user pool group or client moved to another pool, an S3 bucket policy moved to another bucket, the API Gateway REST resources, a Lambda permission, URL, event source mapping or event invoke config, a Firehose delivery stream, an OpenSearch domain) deleted the predecessor inline, so a template that retains it lost the resource, and where the physical id changed the stack still recorded `DELETE_SKIPPED` for it; only the handlers routed through the shared rename helper honoured the policy. Every inline delete now goes through one helper that reads the policy the engine publishes, the three handlers that deleted before creating create first, and the predecessor stays, with its `DELETE_SKIPPED` event where the replacement changes the physical id, as on AWS. Contributed by @iot-rocket.
+
+- **CloudFormation — a resource inside a nested stack reads its own `UpdateReplacePolicy`** — the nested-stack deploy loop never set the contextvar the engine publishes the policy in, so every handler running for a child resource saw whatever the parent's own loop had left there: a retained parent kept every child's predecessor and an unretained parent deleted a retained child's. The loop now resolves each child resource's policy the way the engine does, intrinsics included, and publishes it around that resource's update only. Contributed by @iot-rocket.
- **Cognito — `SetIdentityPoolRoles` keeps the role mappings it is given** — the call stored `Roles` only and `GetIdentityPoolRoles` answered a hard-coded `RoleMappings: {}`, so a mapping set through the API, or declared on a CloudFormation `AWS::Cognito::IdentityPoolRoleAttachment`, was accepted and silently dropped. Both members are stored on the identity pool and served back now; the call sets the whole configuration and the API has no call that removes a mapping on its own, so an omitted `RoleMappings` clears what was there (reasoned from the API surface, not measured against a live account). The map is stored as sent rather than validated, and takes no part in credential vending, which still picks the role by `authenticated` or `unauthenticated`. Contributed by @iot-rocket.
- **CloudFormation — `AWS::Cognito::IdentityPoolRoleAttachment` updates in place** — the type had no update handler, so a stack update fell through to the create handler and nothing in the code said which property may change in place and which one replaces. `Roles` and `RoleMappings` are "Update requires: No interruption" on the resource reference and are re-applied to the pool the attachment already sits on, a property the template drops reverts to its create default (`SetIdentityPoolRoles` takes the whole configuration), and `IdentityPoolId` requires replacement, so the new pool is configured before the old one is cleared. Contributed by @iot-rocket.
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 4328c6d6..cd3b1c5f 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -644,6 +644,11 @@ def _custom_named_replacement_error(resource_type, old_props, new_props):
# 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)
+# The DeletionPolicy / UpdateReplacePolicy values that keep a resource; the
+# engine reads the same tuple for the cleanup phase and the stack delete.
+# 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 _rename_replacement(physical_id, old_props, new_props, stack_name, logical_id,
@@ -672,6 +677,25 @@ def _rename_replacement(physical_id, old_props, new_props, stack_name, logical_i
return created
+def _delete_predecessor(delete_fn, *args, **kwargs):
+ """Delete the resource a handler-side replacement has just superseded,
+ unless the template retains it (an UpdateReplacePolicy in the engine's
+ retaining set): the engine then records the DELETE_SKIPPED event and the
+ predecessor stays, as on AWS. Every update handler that creates the
+ replacement itself removes the old resource through this, so the policy
+ cannot be forgotten at one site, with three exceptions. Two have a
+ deterministic generated name (the DynamoDB table and the Location
+ tracker): the replacement takes the name back, so there is nothing left
+ to retain. The third is the Lambda permission's degenerate ``Id`` branch,
+ which removes and re-puts one statement under a Sid that cannot change:
+ the physical id is kept, nothing is replaced, and the policy does not
+ apply.
+ """
+ if _RETAIN_REPLACED.get():
+ return
+ delete_fn(*args, **kwargs)
+
+
def _update_resource(resource_type: str, physical_id: str, old_props: dict,
new_props: dict, stack_name: str,
logical_id: str | None = None,
@@ -965,7 +989,7 @@ def _opensearch_domain_update(physical_id, old_props, new_props, stack_name,
replacement_logical_id, new_props, stack_name
)
try:
- _opensearch.delete_domain_record(physical_id, missing_ok=True)
+ _delete_predecessor(_opensearch.delete_domain_record, physical_id, missing_ok=True)
except Exception:
_opensearch.delete_domain_record(new_id, missing_ok=True)
raise
@@ -1163,7 +1187,7 @@ def _s3_bucket_policy_update(physical_id, old_props, new_props, stack_name):
# Bucket is create-only on AWS — the policy is replaced onto the new
# bucket and removed from the old one.
result = _s3_bucket_policy_create(physical_id, new_props, stack_name)
- _s3_bucket_policy_delete(physical_id, old_props)
+ _delete_predecessor(_s3_bucket_policy_delete, physical_id, old_props)
return result
return _s3_bucket_policy_create(physical_id, new_props, stack_name)
@@ -1611,6 +1635,12 @@ def _ddb_update(physical_id, old_props, new_props, stack_name, logical_id=None):
f"resource requires replacing. Rename {name} and update the "
"stack again."
)
+ # Not routed through _delete_predecessor: the emulator's generated
+ # name is deterministic, so the table comes back under the same name
+ # and the old one is lost even under UpdateReplacePolicy Retain (AWS
+ # would mint a new name and keep the old table). AWS::Location::Tracker
+ # is the other type with that shape and is left alone for the same
+ # reason.
_ddb_delete(physical_id, old_props)
return _ddb_create(logical_id or physical_id, new_props, stack_name)
@@ -1962,7 +1992,7 @@ def _lambda_url_update(physical_id, old_props, new_props, stack_name):
for key in ("TargetFunctionArn", "Qualifier")
):
new_id, attrs = _lambda_url_create(physical_id, new_props, stack_name)
- _lambda_url_delete(physical_id, old_props)
+ _delete_predecessor(_lambda_url_delete, physical_id, old_props)
return new_id, attrs
_func, func_name, qualifier = _lambda_url_target(new_props)
@@ -2381,7 +2411,7 @@ def _ssm_update(physical_id, old_props, new_props, stack_name):
raise ValueError(f"AWS::SSM::Parameter replace failed: {body!r}")
# Drop the old parameter through the SSM path so its history and tags go
# with it (a bare store pop orphaned both).
- _ssm._delete_parameter({"Name": physical_id})
+ _delete_predecessor(_ssm._delete_parameter, {"Name": physical_id})
return new_name, _ssm_attrs(new_name, data)
# Every other property is No interruption: overwrite in place through
# PutParameter, so Version increments and history grows (a bare store write
@@ -3234,22 +3264,30 @@ def _lambda_permission_remove_statement(props, sids):
def _lambda_permission_update(physical_id, old_props, new_props, stack_name, logical_id=None):
"""Every AWS::Lambda::Permission property requires replacement
(https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-permission.html),
- so any change is RemovePermission followed by AddPermission under a fresh
- physical id — and, as on AWS, a fresh generated Sid, so the engine's
- predecessor cleanup (which deletes by the OLD resource's Sid) and the
- rollback of a failed later resource (which deletes by the NEW one) each
- touch only their own statement.
-
- The one degenerate case is an explicit legacy ``Id`` that both templates
- share: the Sid then cannot change, so the physical id is kept to suppress
- the predecessor cleanup that would otherwise strip the statement this
- update just installed.
+ so any change is AddPermission under a fresh physical id followed by
+ RemovePermission of the old statement, the order CloudFormation replaces
+ in, unless the template retains the old one. The fresh generated Sid is
+ what keeps the engine's predecessor cleanup (which deletes by the OLD
+ resource's Sid) and the rollback of a failed later resource (which
+ deletes by the NEW one) on their own statements.
+
+ The one degenerate case is an explicit legacy ``Id`` that names the Sid
+ the old resource wrote: the Sid then cannot change, AddPermission would
+ refuse the duplicate, so the statement is removed and re-put under it and
+ the physical id is kept (not a replacement). That is the FIRST candidate
+ only, the Sid the old resource actually used; the second is the
+ persisted-by-an-earlier-release fallback, and a new ``Id`` naming it is a
+ real Sid change and so a real replacement.
"""
- _lambda_permission_remove_statement(
- old_props, _lambda_permission_sids(old_props, logical_id, physical_id))
- new_pid, attrs = _lambda_permission_create(logical_id or physical_id, new_props, stack_name)
- if old_props.get("Id") and old_props.get("Id") == new_props.get("Id"):
+ old_sids = _lambda_permission_sids(old_props, logical_id, physical_id)
+ if new_props.get("Id") and old_sids and new_props["Id"] == old_sids[0]:
+ # The Sid cannot change, so the statement is re-put under it and the
+ # physical id is kept: not a replacement.
+ _lambda_permission_remove_statement(old_props, old_sids)
+ _new_pid, attrs = _lambda_permission_create(logical_id or physical_id, new_props, stack_name)
return physical_id, attrs
+ new_pid, attrs = _lambda_permission_create(logical_id or physical_id, new_props, stack_name)
+ _delete_predecessor(_lambda_permission_remove_statement, old_props, old_sids)
return new_pid, attrs
@@ -3461,7 +3499,7 @@ def _cfn_nested_stack_deploy(logical_id, props, parent_stack_name, *,
_topological_sort,
)
from ministack.services.cloudformation.helpers import _resolve_template
- from ministack.services.cloudformation.stacks import _add_event
+ from ministack.services.cloudformation.stacks import _add_event, _resource_policy
template_url = props.get("TemplateURL")
if not template_url:
@@ -3592,10 +3630,20 @@ def _cfn_nested_stack_deploy(logical_id, props, parent_stack_name, *,
resource_type, prev.get("Properties", {}),
(previous_stack_snapshot or {}).get("Tags") or [],
child_name, child_stack_id, child_logical_id)
- physical_id, attrs = _update_resource(
- resource_type, prev.get("PhysicalResourceId", child_logical_id),
- old_tagged, new_tagged, child_name, child_logical_id,
- )
+ # The child's own UpdateReplacePolicy decides whether a
+ # handler-side replacement keeps the predecessor; without
+ # this the parent's policy leaked into the child's handlers.
+ token = _RETAIN_REPLACED.set(_resource_policy(
+ res_def, "UpdateReplacePolicy", provisioned, param_values,
+ conditions, mappings, child_name, child_stack_id,
+ ) in _RETAINING_POLICIES)
+ try:
+ physical_id, attrs = _update_resource(
+ resource_type, prev.get("PhysicalResourceId", child_logical_id),
+ old_tagged, new_tagged, child_name, child_logical_id,
+ )
+ finally:
+ _RETAIN_REPLACED.reset(token)
else:
physical_id, attrs = _provision_resource(
resource_type, child_logical_id, new_tagged, child_name,
@@ -3829,7 +3877,7 @@ def _apigw_rest_api_update(physical_id, old_props, new_props, stack_name, logica
to the dependent resources as the same update reprocesses them)."""
if new_props.get("Body") != old_props.get("Body"):
created = _apigw_rest_api_create(logical_id or physical_id, new_props, stack_name)
- _apigw_rest_api_delete(physical_id, old_props)
+ _delete_predecessor(_apigw_rest_api_delete, physical_id, old_props)
return created
patch_ops = []
@@ -3896,7 +3944,7 @@ def _apigw_resource_update(physical_id, old_props, new_props, stack_name):
# All three properties (RestApiId, ParentId, PathPart) are create-only on
# AWS — any change is a replacement.
created = _apigw_resource_create(physical_id, new_props, stack_name)
- _apigw_resource_delete(physical_id, old_props)
+ _delete_predecessor(_apigw_resource_delete, physical_id, old_props)
return created
@@ -3980,7 +4028,7 @@ def _apigw_method_update(physical_id, old_props, new_props, stack_name):
for key in ("RestApiId", "ResourceId", "HttpMethod")
):
created = _apigw_method_create(physical_id, new_props, stack_name)
- _apigw_method_delete(physical_id, old_props)
+ _delete_predecessor(_apigw_method_delete, physical_id, old_props)
return created
if old_props.get("Integration") and not new_props.get("Integration"):
_apigw_v1._delete_integration(
@@ -4037,8 +4085,13 @@ def _apigw_model_update(physical_id, old_props, new_props, stack_name):
# changes. The stack engine delegates that replacement lifecycle here.
if (old_api_id != new_api_id or physical_id != new_name
or old_content_type != new_content_type):
- _apigw_v1._delete_model(old_api_id, physical_id)
- return _apigw_model_create(physical_id, new_props, stack_name)
+ # The replacement is created first; the emulator's CreateModel path
+ # overwrites a model of the same name on the same API, so the
+ # predecessor is deleted only when its (api, name) key differs.
+ created = _apigw_model_create(physical_id, new_props, stack_name)
+ if (old_api_id, physical_id) != (new_api_id, created[0]):
+ _delete_predecessor(_apigw_v1._delete_model, old_api_id, physical_id)
+ return created
patch_operations = []
old_description = old_props.get("Description", "")
@@ -4244,7 +4297,7 @@ def _apigw_stage_update(physical_id, old_props, new_props, stack_name):
for key in ("RestApiId", "StageName")
):
created = _apigw_stage_create(physical_id, new_props, stack_name)
- _apigw_stage_delete(physical_id, old_props)
+ _delete_predecessor(_apigw_stage_delete, physical_id, old_props)
return created
api_id = new_props.get("RestApiId", "")
stage_name = new_props.get("StageName", "")
@@ -4344,8 +4397,9 @@ def _apigw_api_key_update(physical_id, old_props, new_props, stack_name):
# replaces the key. Everything else updates the existing record in place.
if (old_props.get("Value") != new_props.get("Value")
or old_props.get("Name") != new_props.get("Name")):
- _apigw_v1._delete_api_key(physical_id)
- return _apigw_api_key_create(physical_id, new_props, stack_name)
+ created = _apigw_api_key_create(physical_id, new_props, stack_name)
+ _delete_predecessor(_apigw_v1._delete_api_key, physical_id)
+ return created
key = _apigw_v1._api_keys.get(physical_id)
if key is None:
return _apigw_api_key_create(physical_id, new_props, stack_name)
@@ -4463,7 +4517,7 @@ def _apigw_base_path_mapping_update(physical_id, old_props, new_props, stack_nam
# same atomic create-before-delete behavior here.
new_id, attrs = _apigw_base_path_mapping_create(physical_id, new_props, stack_name)
if (new_domain, new_base_path) != (old_domain, old_base_path):
- _apigw_v1._delete_base_path_mapping(old_domain, old_base_path)
+ _delete_predecessor(_apigw_v1._delete_base_path_mapping, old_domain, old_base_path)
return new_id, attrs
@@ -4554,7 +4608,7 @@ def _apigw_domain_name_update(physical_id, old_props, new_props, stack_name):
new_domain_name = new_props.get("DomainName", "")
new_id, attrs = _apigw_domain_name_create(physical_id, new_props, stack_name)
if new_domain_name != physical_id:
- _apigw_domain_name_delete(physical_id, old_props)
+ _delete_predecessor(_apigw_domain_name_delete, physical_id, old_props)
elif existing_mappings is not None:
# The native create helper initializes this collection. Preserve
# dependent mappings while mutable domain properties update in place.
@@ -4596,7 +4650,7 @@ def _apigw_gateway_response_update(physical_id, old_props, new_props, stack_name
# customization so a failed create cannot destroy the working resource.
if any(new_props.get(key) != old_props.get(key) for key in ("RestApiId", "ResponseType")):
new_id, attrs = _apigw_gateway_response_create(physical_id, new_props, stack_name)
- _apigw_gateway_response_delete(physical_id, old_props)
+ _delete_predecessor(_apigw_gateway_response_delete, physical_id, old_props)
return new_id, attrs
_new_id, attrs = _apigw_gateway_response_create(physical_id, new_props, stack_name)
@@ -4649,7 +4703,7 @@ def _apigw_documentation_part_update(physical_id, old_props, new_props, stack_na
# specification; Properties is mutable in place.
if any(new_props.get(key) != old_props.get(key) for key in ("RestApiId", "Location")):
new_id, attrs = _apigw_documentation_part_create(physical_id, new_props, stack_name)
- _apigw_documentation_part_delete(physical_id, old_props)
+ _delete_predecessor(_apigw_documentation_part_delete, physical_id, old_props)
return new_id, attrs
if new_props.get("Properties") != old_props.get("Properties"):
@@ -4785,8 +4839,7 @@ def _lambda_esm_update(physical_id, old_props, new_props, stack_name):
for immutable in ("EventSourceArn", "StartingPosition", "StartingPositionTimestamp"):
if new_props.get(immutable) != old_props.get(immutable):
new_id, attrs = _lambda_esm_create(physical_id, new_props, stack_name)
- _lambda_svc._esms.pop(physical_id, None)
- _lambda_svc._release_esm_poll_state(physical_id)
+ _delete_predecessor(_lambda_esm_delete, physical_id, old_props)
return new_id, attrs
for key in (
"BatchSize",
@@ -4855,7 +4908,10 @@ def _lambda_event_invoke_config_update(physical_id, old_props, new_props, stack_
physical_id, new_props, stack_name
)
if replacement:
- _lambda_event_invoke_config_delete(physical_id, old_props)
+ # FunctionName written in another form (name vs ARN) resolves to the
+ # same config; deleting the predecessor would delete the new one.
+ if new_id != physical_id:
+ _delete_predecessor(_lambda_event_invoke_config_delete, physical_id, old_props)
return new_id, attrs
return physical_id, attrs
@@ -5639,7 +5695,7 @@ def _cognito_user_pool_client_update(physical_id, old_props, new_props, stack_na
if (new_props.get("UserPoolId") != old_props.get("UserPoolId")
or bool(new_props.get("GenerateSecret")) != bool(old_props.get("GenerateSecret"))):
created = _cognito_user_pool_client_create(logical_id or physical_id, new_props, stack_name)
- _cognito_user_pool_client_delete(physical_id, old_props)
+ _delete_predecessor(_cognito_user_pool_client_delete, physical_id, old_props)
return created
payload = _declared_or_default(
old_props, new_props, _COGNITO_USER_POOL_CLIENT_UPDATABLE
@@ -5796,7 +5852,7 @@ def _cognito_user_pool_group_update(physical_id, old_props, new_props, stack_nam
logical_id or physical_id, new_props, stack_name
)
if group is not None:
- _cognito_user_pool_group_delete(physical_id, old_props)
+ _delete_predecessor(_cognito_user_pool_group_delete, physical_id, old_props)
return created
group["Description"] = new_props.get("Description", "")
@@ -7637,7 +7693,7 @@ def _cw_dashboard_update(physical_id, old_props, new_props, stack_name):
raise ValueError("DashboardName must be between 1 and 255 characters")
_cw.cloudformation_put_dashboard(name, _cw_dashboard_body(new_props))
if name != physical_id:
- _cw.cloudformation_delete_dashboard(physical_id)
+ _delete_predecessor(_cw.cloudformation_delete_dashboard, physical_id)
return name, {}
@@ -8725,7 +8781,7 @@ def _firehose_delivery_stream_update(physical_id, old_props, new_props, stack_na
new_id, attrs = _firehose_delivery_stream_create(
physical_id, new_props, stack_name
)
- _firehose_delivery_stream_delete(physical_id, old_props)
+ _delete_predecessor(_firehose_delivery_stream_delete, physical_id, old_props)
return new_id, attrs
stream = _firehose._streams.get(physical_id)
if stream is None:
@@ -8886,7 +8942,7 @@ def _iot_policy_update(physical_id, old_props, new_props, stack_name, logical_id
)
if name != physical_id:
created = _iot_policy_create(logical_id or physical_id, new_props, stack_name)
- _iot_policy_delete(physical_id, old_props)
+ _delete_predecessor(_iot_policy_delete, physical_id, old_props)
return created
_iot_policy_prune_versions(name)
resp = _iot._create_policy_version(
@@ -8974,7 +9030,7 @@ def _iot_provisioning_template_update(physical_id, old_props, new_props, stack_n
created = _iot_provisioning_template_create(
logical_id or physical_id, new_props, stack_name
)
- _iot_provisioning_template_delete(physical_id, old_props)
+ _delete_predecessor(_iot_provisioning_template_delete, physical_id, old_props)
return created
payload = _iot_provisioning_template_payload(name, new_props)
payload.pop("templateName", None)
@@ -9201,7 +9257,7 @@ def _cognito_identity_pool_principal_tag_update(physical_id, old_props, new_prop
# either is a replacement, and the mapping left on the old pair would
# otherwise keep tagging principals after the template stopped declaring it.
if (old_props.get("IdentityPoolId"), old_props.get("IdentityProviderName")) != (iid, provider):
- _cognito_identity_pool_principal_tag_delete(physical_id, old_props)
+ _delete_predecessor(_cognito_identity_pool_principal_tag_delete, physical_id, old_props)
return f"{iid}|{provider}", {}
@@ -9406,6 +9462,9 @@ def _location_tracker_update(physical_id, old_props, new_props, stack_name,
if replaced is not None:
return replaced
if old_props.get("KmsKeyId") != new_props.get("KmsKeyId"):
+ # Not routed through _delete_predecessor, like the DynamoDB key-schema
+ # branch: the auto-generated name is deterministic, so the replacement
+ # takes it back and retaining the predecessor is not possible here.
_location_tracker_delete(physical_id, old_props)
return _location_tracker_create(logical_id or physical_id, new_props, stack_name)
changes = {}
diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.py
index ecd33d0b..86c9e879 100644
--- a/ministack/services/cloudformation/stacks.py
+++ b/ministack/services/cloudformation/stacks.py
@@ -21,6 +21,7 @@ from .engine import (
)
from .provisioners import (
_RETAIN_REPLACED,
+ _RETAINING_POLICIES,
_delete_resource,
_provision_resource,
_update_resource,
@@ -76,10 +77,6 @@ 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):
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 97cd993c..bc66b694 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -18906,6 +18906,50 @@ def test_cfn_lambda_permission_id_change_replaces_the_statement(cfn, lam):
lam.delete_function(FunctionName=fn_name)
+def test_cfn_lambda_permission_id_adopting_the_generated_sid_keeps_the_statement(cfn, lam):
+ """A template that adds an explicit Id naming the Sid the resource
+ already wrote cannot change that Sid, so the statement is re-put under it
+ and the physical id is kept: not a replacement. A template that names the
+ legacy logical-id fallback instead does change the Sid, so that is a real
+ replacement and the old statement goes."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-perm-adopt-{uid}"
+ fn_name = f"cfn-perm-adopt-{uid}"
+ _cfn_permission_test_function(lam, fn_name)
+
+ def template(sid):
+ props = {"FunctionName": fn_name, "Action": "lambda:InvokeFunction",
+ "Principal": "s3.amazonaws.com"}
+ if sid:
+ props["Id"] = sid
+ return json.dumps({"Resources": {"Perm": {
+ "Type": "AWS::Lambda::Permission", "Properties": props}}})
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(None))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ generated = {s["Sid"] for s in _lambda_policy_statements(lam, fn_name)}
+ assert len(generated) == 1
+ sid = generated.pop()
+ assert sid != "Perm", "the generated Sid is the physical id, not the logical id"
+
+ # Naming the Sid the resource already wrote: kept, one statement.
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(sid))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert {s["Sid"] for s in _lambda_policy_statements(lam, fn_name)} == {sid}
+
+ # Naming something else is a Sid change, so a real replacement.
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("Perm"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert {s["Sid"] for s in _lambda_policy_statements(lam, fn_name)} == {"Perm"}
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ lam.delete_function(FunctionName=fn_name)
+
+
def test_cfn_lambda_permission_rollback_of_a_replacement_removes_the_new_statement(cfn, lam, ddb):
"""When an update that replaced the permission fails later in the run,
the rollback removes the statement the replacement added, since the
@@ -19808,27 +19852,509 @@ def test_cfn_update_replace_policy_retain_keeps_the_predecessor(cfn, sqs):
queue["UpdateReplacePolicy"] = policy
return json.dumps({"Resources": {"Queue": queue}})
+ try:
+ _assert_retain_keeps_handler_side_predecessor(
+ cfn, stack_name, template, "Queue", names, lambda name: _queue_exists(sqs, name))
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ for name in names:
+ _delete_queue_if_present(sqs, name)
+
+
+def _assert_retain_keeps_handler_side_predecessor(cfn, stack_name, template, logical_id,
+ names, exists):
+ """Rename ``logical_id`` from names[0] to names[1] under UpdateReplacePolicy
+ Retain and assert that both resources exist afterwards with a DELETE_SKIPPED
+ event; then rename to names[2] without the policy and assert the predecessor
+ is gone. ``template(name, policy)`` builds the body, ``exists(name)`` asks
+ the service."""
cfn.create_stack(StackName=stack_name, TemplateBody=template(names[0], "Retain"))
+ 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 exists(names[0]), "the retained predecessor was deleted"
+ assert exists(names[1])
+ assert "DELETE_SKIPPED" in [s for s, _ in _resource_events(cfn, stack_name, logical_id)]
+
+ 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 exists(names[1])
+ assert exists(names[2])
+
+
+def test_cfn_update_replace_policy_retain_ssm_parameter(cfn, ssm):
+ """A handler that replaces the resource itself (an SSM parameter renamed:
+ Name is Replacement) must leave the predecessor alone under Retain."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-retain-ssm-{uid}"
+ names = [f"/cfn-retain-{uid}/{i}" for i in ("a", "b", "c")]
+
+ def template(name, policy):
+ res = {"Type": "AWS::SSM::Parameter",
+ "Properties": {"Name": name, "Type": "String", "Value": "v"}}
+ if policy:
+ res["UpdateReplacePolicy"] = policy
+ return json.dumps({"Resources": {"Param": res}})
+
+ def exists(name):
+ try:
+ ssm.get_parameter(Name=name)
+ return True
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "ParameterNotFound", exc.response["Error"]
+ return False
+
+ try:
+ _assert_retain_keeps_handler_side_predecessor(
+ cfn, stack_name, template, "Param", names, exists)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ for name in names:
+ try:
+ ssm.delete_parameter(Name=name)
+ except ClientError:
+ pass
+
+
+def test_cfn_update_replace_policy_retain_cloudwatch_dashboard(cfn, cw):
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-retain-dash-{uid}"
+ names = [f"cfn-retain-dash-{uid}-{i}" for i in ("a", "b", "c")]
+ body = json.dumps({"widgets": [{"type": "text", "properties": {"markdown": "x"}}]})
+
+ def template(name, policy):
+ res = {"Type": "AWS::CloudWatch::Dashboard",
+ "Properties": {"DashboardName": name, "DashboardBody": body}}
+ if policy:
+ res["UpdateReplacePolicy"] = policy
+ return json.dumps({"Resources": {"Dash": res}})
+
+ def exists(name):
+ try:
+ cw.get_dashboard(DashboardName=name)
+ return True
+ except ClientError as exc:
+ assert "NotFound" in exc.response["Error"]["Code"], exc.response["Error"]
+ return False
+
+ try:
+ _assert_retain_keeps_handler_side_predecessor(
+ cfn, stack_name, template, "Dash", names, exists)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ try:
+ cw.delete_dashboards(DashboardNames=names)
+ except ClientError:
+ pass
+
+
+def test_cfn_update_replace_policy_retain_iot_policy(cfn, iot_client):
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-retain-iotpol-{uid}"
+ names = [f"cfn-retain-pol-{uid}-{i}" for i in ("a", "b", "c")]
+ document = {"Version": "2012-10-17",
+ "Statement": [{"Effect": "Allow", "Action": ["iot:Connect"], "Resource": "*"}]}
+
+ def template(name, policy):
+ res = {"Type": "AWS::IoT::Policy",
+ "Properties": {"PolicyName": name, "PolicyDocument": document}}
+ if policy:
+ res["UpdateReplacePolicy"] = policy
+ return json.dumps({"Resources": {"Pol": res}})
+
+ def exists(name):
+ try:
+ iot_client.get_policy(policyName=name)
+ return True
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "ResourceNotFoundException", exc.response["Error"]
+ return False
+
+ try:
+ _assert_retain_keeps_handler_side_predecessor(
+ cfn, stack_name, template, "Pol", names, exists)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ for name in names:
+ try:
+ iot_client.delete_policy(policyName=name)
+ except ClientError:
+ pass
+
+
+def test_cfn_update_replace_policy_retain_cognito_user_pool_group(cfn, cognito_idp):
+ """The group handler replaces inside the pool by (pool, name) and does not
+ go through the shared rename helper; Retain has to hold there as well."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-retain-group-{uid}"
+ pool_id = None
+ names = [f"retain-{uid}-{i}" for i in ("a", "b", "c")]
+
+ def template(name, policy):
+ res = {"Type": "AWS::Cognito::UserPoolGroup",
+ "Properties": {"UserPoolId": pool_id, "GroupName": name}}
+ if policy:
+ res["UpdateReplacePolicy"] = policy
+ return json.dumps({"Resources": {"Group": res}})
+
+ def exists(name):
+ groups = cognito_idp.list_groups(UserPoolId=pool_id)["Groups"]
+ return name in [g["GroupName"] for g in groups]
+
+ try:
+ pool_id = cognito_idp.create_user_pool(PoolName=f"cfn-retain-group-{uid}")["UserPool"]["Id"]
+ _assert_retain_keeps_handler_side_predecessor(
+ cfn, stack_name, template, "Group", names, exists)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ if pool_id:
+ try:
+ cognito_idp.delete_user_pool(UserPoolId=pool_id)
+ except ClientError:
+ pass
+
+
+def test_cfn_update_replace_policy_retain_s3_bucket_policy(cfn, s3):
+ """A bucket policy moved to another bucket (Bucket is Replacement) keeps
+ the old bucket's policy under Retain."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-retain-bp-{uid}"
+ names = [f"cfn-retain-bp-{uid}-{i}" for i in ("a", "b", "c")]
+
+ def template(bucket, policy):
+ res = {"Type": "AWS::S3::BucketPolicy", "Properties": {
+ "Bucket": bucket,
+ "PolicyDocument": {"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject",
+ "Resource": f"arn:aws:s3:::{bucket}/*"}]}}}
+ if policy:
+ res["UpdateReplacePolicy"] = policy
+ return json.dumps({"Resources": {"Policy": res}})
+
+ def exists(bucket):
+ try:
+ s3.get_bucket_policy(Bucket=bucket)
+ return True
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "NoSuchBucketPolicy", exc.response["Error"]
+ return False
+
+ try:
+ for name in names:
+ s3.create_bucket(Bucket=name)
+ _assert_retain_keeps_handler_side_predecessor(
+ cfn, stack_name, template, "Policy", names, exists)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ for name in names:
+ try:
+ s3.delete_bucket(Bucket=name)
+ except ClientError:
+ pass
+
+
+def test_cfn_update_replace_policy_retain_lambda_event_source_mapping(cfn, lam):
+ """EventSourceArn is Replacement and the mapping id is generated: the
+ replaced mapping stays under Retain."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-retain-esm-{uid}"
+ fn = f"cfn-retain-esm-{uid}"
+ names = [f"arn:aws:sqs:us-east-1:000000000000:cfn-retain-esm-{uid}-{i}" for i in ("a", "b", "c")]
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", "def handler(e,c): return {}")
+
+ def template(source_arn, policy):
+ res = {"Type": "AWS::Lambda::EventSourceMapping", "Properties": {
+ "FunctionName": fn, "EventSourceArn": source_arn, "BatchSize": 1}}
+ if policy:
+ res["UpdateReplacePolicy"] = policy
+ return json.dumps({"Resources": {"Esm": res}})
+
+ def exists(source_arn):
+ mappings = lam.list_event_source_mappings(FunctionName=fn)["EventSourceMappings"]
+ return source_arn in [m["EventSourceArn"] for m in mappings]
+
+ try:
+ lam.create_function(
+ FunctionName=fn, Runtime="python3.11", Role="arn:aws:iam::000000000000:role/r",
+ Handler="index.handler", Code={"ZipFile": buf.getvalue()})
+ _assert_retain_keeps_handler_side_predecessor(
+ cfn, stack_name, template, "Esm", names, exists)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ try:
+ for m in lam.list_event_source_mappings(FunctionName=fn)["EventSourceMappings"]:
+ lam.delete_event_source_mapping(UUID=m["UUID"])
+ lam.delete_function(FunctionName=fn)
+ except ClientError:
+ pass
+
+
+def test_cfn_update_replace_policy_retain_iot_provisioning_template(cfn, iot_client):
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-retain-provtpl-{uid}"
+ names = [f"cfn-retain-pt-{uid}-{i}" for i in ("a", "b", "c")]
+
+ def template(name, policy):
+ res = {"Type": "AWS::IoT::ProvisioningTemplate", "Properties": {
+ "TemplateName": name, "Enabled": True,
+ "ProvisioningRoleArn": "arn:aws:iam::000000000000:role/provisioning",
+ "TemplateBody": _cfn_provisioning_template_body()}}
+ if policy:
+ res["UpdateReplacePolicy"] = policy
+ return json.dumps({"Resources": {"PT": res}})
+
+ def exists(name):
+ try:
+ iot_client.describe_provisioning_template(templateName=name)
+ return True
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "ResourceNotFoundException", \
+ exc.response["Error"]
+ return False
+
+ try:
+ _assert_retain_keeps_handler_side_predecessor(
+ cfn, stack_name, template, "PT", names, exists)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ for name in names:
+ try:
+ iot_client.delete_provisioning_template(templateName=name)
+ except ClientError:
+ pass
+
+
+def test_cfn_update_replace_policy_retain_lambda_url(cfn, lam):
+ """A Lambda URL is keyed by its function, so a TargetFunctionArn change
+ replaces it inside the handler and the predecessor URL must survive
+ Retain."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-retain-url-{uid}"
+ names = [f"cfn-retain-url-{uid}-{i}" for i in ("a", "b", "c")]
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", "def handler(e,c): return {}")
+ for name in names:
+ lam.create_function(
+ FunctionName=name, Runtime="python3.12", Role="arn:aws:iam::000000000000:role/l",
+ Handler="index.handler", Code={"ZipFile": buf.getvalue()})
+
+ def template(name, policy):
+ res = {"Type": "AWS::Lambda::Url", "Properties": {
+ "TargetFunctionArn": name, "AuthType": "NONE"}}
+ if policy:
+ res["UpdateReplacePolicy"] = policy
+ return json.dumps({"Resources": {"Url": res}})
+
+ def exists(name):
+ try:
+ lam.get_function_url_config(FunctionName=name)
+ return True
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "ResourceNotFoundException", \
+ exc.response["Error"]
+ return False
+
+ try:
+ _assert_retain_keeps_handler_side_predecessor(
+ cfn, stack_name, template, "Url", names, exists)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ for name in names:
+ try:
+ lam.delete_function(FunctionName=name)
+ except ClientError:
+ pass
+
+
+def test_cfn_update_replace_policy_retain_except_on_create_also_holds(cfn, ssm):
+ """RetainExceptOnCreate is the other half of the retaining set the engine
+ and the handlers now read from one tuple: it keeps a handler-side
+ predecessor exactly as Retain does, since the resource is not newly
+ created by the operation that rolls back."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-retain-exc-{uid}"
+ names = [f"/cfn-retain-exc-{uid}/{i}" for i in ("a", "b", "c")]
+
+ def template(name, policy):
+ res = {"Type": "AWS::SSM::Parameter",
+ "Properties": {"Name": name, "Type": "String", "Value": "v"}}
+ if policy:
+ res["UpdateReplacePolicy"] = policy
+ return json.dumps({"Resources": {"Param": res}})
+
+ def exists(name):
+ try:
+ ssm.get_parameter(Name=name)
+ return True
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "ParameterNotFound", exc.response["Error"]
+ return False
+
try:
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=template(names[0], "RetainExceptOnCreate"))
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=template(names[1], "RetainExceptOnCreate"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert exists(names[0]), "the retained predecessor was deleted"
+ assert exists(names[1])
+ assert "DELETE_SKIPPED" in [s for s, _ in _resource_events(cfn, stack_name, "Param")]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ for name in names:
+ try:
+ ssm.delete_parameter(Name=name)
+ except ClientError:
+ pass
+
+
+def test_cfn_nested_stack_child_reads_its_own_update_replace_policy(monkeypatch):
+ """A resource inside a nested stack keeps its predecessor under its own
+ UpdateReplacePolicy Retain and loses it without, whatever the policy on
+ the parent's AWS::CloudFormation::Stack resource: the nested-stack loop
+ ran the child's handlers under the parent's policy before."""
+ from ministack.services import ssm as _ssm
+ from ministack.services.cloudformation import _stack_events, _stacks
+ from ministack.services.cloudformation import helpers as _helpers
+ from ministack.services.cloudformation.provisioners import (
+ _RETAIN_REPLACED,
+ _cfn_nested_stack_deploy,
+ )
+
+ uid = _uuid_mod.uuid4().hex[:8]
+ parent = f"cfn-nested-retain-{uid}"
+ names = [f"/cfn-nested-retain-{uid}/{i}" for i in ("a", "b", "c")]
+ templates = {}
+
+ def child(name, policy):
+ res = {"Type": "AWS::SSM::Parameter",
+ "Properties": {"Name": name, "Type": "String", "Value": "v"}}
+ if policy:
+ res["UpdateReplacePolicy"] = policy
+ return {"Resources": {"Param": res}}
+
+ monkeypatch.setattr(
+ _helpers, "_resolve_template",
+ lambda params: (json.dumps(templates[params["TemplateURL"][0]]), None))
+ _stacks[parent] = {
+ "StackName": parent,
+ "StackId": f"arn:aws:cloudformation:us-east-1:000000000000:stack/{parent}/parent",
+ "StackStatus": "UPDATE_IN_PROGRESS", "_resources": {},
+ }
+
+ def deploy(url, parent_retains, previous=None):
+ props = {"TemplateURL": url}
+ token = _RETAIN_REPLACED.set(parent_retains)
+ try:
+ if previous is None:
+ child_id, _attrs = _cfn_nested_stack_deploy("Child", props, parent)
+ else:
+ child_id, _attrs = _cfn_nested_stack_deploy(
+ "Child", props, parent, previous_physical_id=previous, previous_props=props)
+ finally:
+ _RETAIN_REPLACED.reset(token)
+ return child_id.split("/")[1]
+
+ def exists(name):
+ return name in _ssm._parameters
+
+ try:
+ # The child retains, the parent resource does not: the predecessor stays.
+ templates["s3://tpl/a"] = child(names[0], "Retain")
+ templates["s3://tpl/b"] = child(names[1], "Retain")
+ stack = deploy("s3://tpl/a", parent_retains=False)
+ deploy("s3://tpl/b", parent_retains=False, previous=stack)
+ assert exists(names[0]) and exists(names[1])
+ # The child does not retain, the parent resource does: it is deleted.
+ templates["s3://tpl/c"] = child(names[2], None)
+ deploy("s3://tpl/c", parent_retains=True, previous=stack)
+ assert not exists(names[1])
+ assert exists(names[2])
+ finally:
+ for name in [n for n in list(_stacks) if n.startswith(parent)]:
+ gone = _stacks.pop(name, None) or {}
+ _stack_events.pop(gone.get("StackId"), None)
+ for name in names:
+ _ssm._parameters.pop(name, None)
+
+
+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
+ the old id is gone."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-apikey-ren-{uid}"
- cfn.update_stack(StackName=stack_name, TemplateBody=template(names[1], "Retain"))
+ def template(name):
+ return json.dumps({
+ "Resources": {"Key": {"Type": "AWS::ApiGateway::ApiKey",
+ "Properties": {"Name": name, "Enabled": True}}},
+ "Outputs": {"KeyId": {"Value": {"Ref": "Key"}}},
+ })
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(f"{stack_name}-a"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ old_id = _output(stack, "KeyId")
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(f"{stack_name}-b"))
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")]
+ new_id = _output(stack, "KeyId")
+ assert new_id != old_id
+ assert apigw_v1.get_api_key(apiKey=new_id)["name"] == f"{stack_name}-b"
+ with pytest.raises(ClientError):
+ apigw_v1.get_api_key(apiKey=old_id)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
- cfn.update_stack(StackName=stack_name, TemplateBody=template(names[2], None))
+
+def test_cfn_apigw_model_content_type_change_keeps_the_name(cfn, apigw_v1):
+ """ContentType is Replacement on AWS::ApiGateway::Model, but the model is
+ keyed by name on its API: the replacement lands under the same name and
+ the old record is not deleted from under it."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-model-ct-{uid}"
+ api_id = None
+ model_name = f"Model{uid}"
+
+ def template(content_type):
+ return json.dumps({
+ "Resources": {"Model": {"Type": "AWS::ApiGateway::Model", "Properties": {
+ "RestApiId": api_id, "Name": model_name, "ContentType": content_type,
+ "Description": content_type, "Schema": {"type": "object"}}}},
+ "Outputs": {"Name": {"Value": {"Ref": "Model"}}},
+ })
+
+ try:
+ api_id = apigw_v1.create_rest_api(name=f"cfn-model-ct-{uid}")["id"]
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("application/json"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("application/xml"))
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])
+ assert _output(stack, "Name") == model_name
+ model = apigw_v1.get_model(restApiId=api_id, modelName=model_name)
+ assert model["contentType"] == "application/xml"
+ assert model["description"] == "application/xml"
finally:
_delete_cfn_test_stack(cfn, stack_name)
- for name in names:
- _delete_queue_if_present(sqs, name)
+ if api_id:
+ try:
+ apigw_v1.delete_rest_api(restApiId=api_id)
+ except ClientError:
+ pass
def test_cfn_deletion_policy_retain_on_a_removed_resource(cfn, sqs):