Skip to content

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

fix(cloudformation): a stack delete blocks on real imports only (#1640)

iot-rocketaf5e58277b44
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1e52c9a8..c6b332d8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **CloudFormation — an export counts as in use only when a stack imports it** — `DeleteStack` searched the serialized templates of every other stack for the export name, so a stack that merely carried the name in a string value blocked the delete, while an import through a resolved `Fn::ImportValue` argument (`Fn::Sub` with a parameter) did not. The check now walks the other stacks' `Fn::ImportValue` uses and resolves their arguments against those stacks' own parameters, as CloudFormation does. Contributed by @iot-rocket.
- **CloudFormation — `UpdateStack` without changes is refused** — an identical `TemplateBody`, or `UsePreviousTemplate` with unchanged parameters, ran an empty update (`UPDATE_IN_PROGRESS` / `UPDATE_COMPLETE` events) where CloudFormation answers `ValidationError: No updates are to be performed.`, so a "deploy until nothing changes" loop never ended. The request is refused when the template, every resolved parameter and the tags (when sent) equal what the stack runs; a changed parameter value or tag set is still an update. Contributed by @iot-rocket.
- **CloudFormation — unrecognized resource types are rejected up front, `Fn::GetAtt` to a missing attribute fails the stack** — a template with a resource type the emulator does not know provisioned every resource ahead of it, failed on that one and rolled the stack back; `CreateStack`, `UpdateStack`, `CreateChangeSet` and `ValidateTemplate` now refuse it synchronously with CloudFormation's own `Template format error: Unrecognized resource types: [...]` and leave no stack (or `REVIEW_IN_PROGRESS` placeholder) behind. Dynamic references (`{{resolve:ssm:...}}`, `{{resolve:secretsmanager:...}}`), which the emulator does not resolve, are refused the same way instead of reaching the service as literal strings. `Fn::GetAtt` to an attribute a resource does not expose answered with the physical id, a silently wrong value; it now fails the operation with `Requested attribute X does not exist in schema for T` and the stack rolls back, matching what a real account does. Outputs are resolved before the success path commits, so a failing output rolls back too and registers no export. Contributed by @iot-rocket.
### Added
diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.py
index 8c9acdf6..0d71e489 100644
--- a/ministack/services/cloudformation/handlers.py
+++ b/ministack/services/cloudformation/handlers.py
@@ -22,6 +22,7 @@ from .engine import (
_evaluate_conditions,
_parse_template,
_resolve_parameters,
+ _resolve_refs,
validate_template_support,
)
from .helpers import _error, _esc, _extract_members, _extract_stack_status_filters, _p, _resolve_template, _xml
@@ -435,6 +436,42 @@ def _get_template(params):
# --- DeleteStack ---
+def _imported_export_names(stack, stack_name):
+ """The export names a stack imports: every ``Fn::ImportValue`` in its
+ Resources, Outputs and Conditions, with the argument resolved against
+ the stack's own parameters, mappings and resources (``Fn::Sub`` and
+ ``Ref`` inside the argument are common). Only such an import blocks the
+ deletion of the exporting stack on AWS; a template that merely mentions
+ the export name in a string, or in ``Metadata``, does not."""
+ template = stack.get("_template", {})
+ names = set()
+
+ def walk(node):
+ if isinstance(node, dict):
+ if len(node) == 1 and "Fn::ImportValue" in node:
+ arg = node["Fn::ImportValue"]
+ try:
+ resolved = _resolve_refs(
+ arg, stack.get("_resources", {}),
+ stack.get("_resolved_params", {}),
+ stack.get("_conditions", {}),
+ template.get("Mappings", {}),
+ stack_name, stack.get("StackId", ""))
+ except Exception:
+ resolved = arg
+ names.add(str(resolved))
+ return
+ for value in node.values():
+ walk(value)
+ elif isinstance(node, list):
+ for value in node:
+ walk(value)
+
+ for section in ("Resources", "Outputs", "Conditions"):
+ walk(template.get(section, {}))
+ return names
+
+
def _delete_stack(params):
from ministack.services.cloudformation import _stacks
stack_name = _p(params, "StackName")
@@ -467,8 +504,7 @@ def _delete_stack(params):
continue
other_status = other_stack.get("StackStatus", "")
if other_status.endswith("_COMPLETE") and "DELETE" not in other_status:
- other_template = other_stack.get("_template", {})
- if export_name in json.dumps(other_template):
+ if export_name in _imported_export_names(other_stack, other_name):
return _error("ValidationError",
f"Export {export_name} is imported by stack {other_name}")
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 923a4e2c..a1def6f7 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -14366,6 +14366,52 @@ def test_cfn_delete_change_set_missing_is_idempotent(cfn):
assert exc.value.response["Error"]["Code"] == "ValidationError"
+def test_cfn_export_in_use_is_an_import_not_a_mention(cfn, ssm):
+ """Deleting an exporting stack is refused only while another stack imports
+ the export through Fn::ImportValue, its argument resolved with that stack's
+ parameters. A stack whose template merely carries the export name in a
+ string value, or an Fn::ImportValue under Metadata, does not block the
+ delete."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ export_name = f"cfn-export-use-{uid}"
+ producer = f"cfn-export-producer-{uid}"
+ mention = f"cfn-export-mention-{uid}"
+ importer = f"cfn-export-importer-{uid}"
+ cfn.create_stack(StackName=producer, TemplateBody=json.dumps({
+ "Resources": {},
+ "Outputs": {"Shared": {"Value": "shared", "Export": {"Name": export_name}}},
+ }))
+ try:
+ assert _wait_stack(cfn, producer)["StackStatus"] == "CREATE_COMPLETE"
+ cfn.create_stack(StackName=mention, TemplateBody=json.dumps({
+ "Metadata": {"Note": {"Fn::ImportValue": export_name}},
+ "Resources": {"P": {"Type": "AWS::SSM::Parameter", "Properties": {
+ "Name": f"/cfn/export-use/{uid}/mention", "Type": "String",
+ "Value": f"the export is called {export_name}"}}},
+ }))
+ assert _wait_stack(cfn, mention)["StackStatus"] == "CREATE_COMPLETE"
+ cfn.create_stack(StackName=importer, TemplateBody=json.dumps({
+ "Parameters": {"Prefix": {"Type": "String"}},
+ "Resources": {"P": {"Type": "AWS::SSM::Parameter", "Properties": {
+ "Name": f"/cfn/export-use/{uid}/import", "Type": "String",
+ "Value": {"Fn::ImportValue": {"Fn::Sub": "${Prefix}-" + uid}}}}},
+ }), Parameters=[{"ParameterKey": "Prefix", "ParameterValue": "cfn-export-use"}])
+ stack = _wait_stack(cfn, importer)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ assert ssm.get_parameter(Name=f"/cfn/export-use/{uid}/import")["Parameter"]["Value"] == "shared"
+
+ with pytest.raises(ClientError) as exc:
+ cfn.delete_stack(StackName=producer)
+ assert exc.value.response["Error"]["Code"] == "ValidationError"
+ assert f"Export {export_name} is imported by stack {importer}" in exc.value.response["Error"]["Message"]
+
+ cfn.delete_stack(StackName=importer)
+ _wait_stack(cfn, importer)
+ cfn.delete_stack(StackName=producer)
+ assert _wait_stack(cfn, producer)["StackStatus"] == "DELETE_COMPLETE"
+ finally:
+ for name in (importer, mention, producer):
+ _delete_cfn_test_stack(cfn, name)
def test_cfn_update_stack_without_changes_is_refused(cfn, sqs):
"""UpdateStack with the template and parameters the stack already runs is
refused with CloudFormation's ``No updates are to be performed.``, for an