Skip to content

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

fix(cloudformation): resources unchanged by a stack update are left alone (#1340)

ryan-bennette160574e6a0c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 27dad2b3..01e945bc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **CloudFormation — resources unchanged by a stack update are left alone** — every previously-provisioned resource was reprocessed on every stack update regardless of whether its properties changed, and any resource type with no dedicated update handler fell back to calling create again — a fallback whose own name-generation regenerated a fresh random suffix on every call, and whose caller passed the wrong id into it, on top of that. An auto-named resource's "idempotent" create (the type framework's own documented expectation) silently produced a brand new, empty resource under a new identity on every single update, orphaning the real one — and anything referencing it via `Ref`/`Fn::GetAtt` picked up that new, wrong identity the moment it was reprocessed later in the same update, since real CloudFormation does propagate a changed reference. Found via a DynamoDB table silently duplicating on an unrelated update to a real multi-stack deploy. A genuinely unchanged resource is no longer touched at all, matching real CloudFormation; auto-generated names are now a deterministic hash of (stack name, logical id) rather than random, so the remaining case — a resource's properties *did* change but its type still has no update handler — reproduces the same name it started with. Also fixes the same symptom for `AWS::Events::EventBus` (previously failed a stack update outright with "already exists" once created) and any other resource type with no update handler and no name-collision guard of its own. Contributed by @ryan-bennett.
- **CloudFormation — `AWS::SSM::Parameter::Value<...>` template parameters now resolve against SSM Parameter Store** — a template parameter typed `AWS::SSM::Parameter::Value<String>` (or `<List<String>>` / `<AWS::EC2::Image::Id>`) takes an SSM parameter *name* as its Default/provided value; real CloudFormation resolves that name against Parameter Store before `Ref` ever sees it — the mechanism behind, e.g., CDK's `StringParameter.valueForStringParameter`. MiniStack treated these like any other AWS-specific parameter type and passed the literal name straight through, so `Ref` returned the parameter's name instead of its stored value, and any resource property built from it (or a nested stack composing two independently-deployed stacks through a shared parameter) silently received the wrong string. Resolution now looks the name up in the SSM store at parameter-resolution time; a name that doesn't exist fails `CreateStack`/`UpdateStack` synchronously with a `ValidationError`, matching AWS. Contributed by @ryan-bennett.
## [1.4.15] — 2026-08-10
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 9a310b8e..836224bc 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -70,8 +70,23 @@ def _physical_name(stack_name: str, logical_id: str, *,
Matches the pattern AWS CloudFormation uses for auto-named resources so that
local testing with CDK (which omits explicit names) produces names that are
immediately traceable back to the stack and logical resource.
+
+ The suffix is a deterministic hash of (stack_name, logical_id), not a fresh
+ random value per call — matching real CloudFormation, where an auto-named
+ resource's physical name is stable across updates for the same logical
+ resource, only changing on a genuine replacement. Most resource types have
+ no explicit update handler here and fall back to calling create again on
+ every stack update (see _update_resource's own doc comment, "provisioners
+ are expected to implement idempotently") — a random suffix defeated that
+ for any type whose create doesn't separately guard against re-creating an
+ existing name (unlike e.g. SQS, which happens to just overwrite): every
+ update silently produced a brand new, empty resource under a new name,
+ orphaning the real one — and anything referencing it via Ref/Fn::GetAtt
+ picked up that new (wrong) identity the moment it was reprocessed later in
+ the same update. Resource *replacement* (a property change real AWS can't
+ apply in place) isn't specially detected here — same as before this fix.
"""
- suffix = "".join(random.choices(string.ascii_uppercase + string.digits, k=13))
+ suffix = hashlib.sha256(f"{stack_name}:{logical_id}".encode()).hexdigest()[:13].upper()
base = f"{stack_name}-{logical_id}-{suffix}"
if lowercase:
base = base.lower()
@@ -120,12 +135,27 @@ def _delete_resource(resource_type: str, physical_id: str, props: dict,
def _update_resource(resource_type: str, physical_id: str, old_props: dict,
new_props: dict, stack_name: str,
- logical_id: str | None = None) -> tuple:
+ logical_id: str | None = None,
+ old_attrs: dict | None = None) -> tuple:
"""Update a provisioned resource in place when the type provides an ``update``
handler. Falls back to ``create`` (which provisioners are expected to
implement idempotently) when no explicit update handler is registered.
Returns (physical_id, attributes).
"""
+ if old_props == new_props:
+ # Nothing about this resource actually changed — real CloudFormation
+ # doesn't touch a resource at all in this case. Matters most for
+ # types with no update handler (see the create-fallback below):
+ # without this, every such resource was re-provisioned on *every*
+ # stack update regardless of whether anything about it changed, and
+ # a create that isn't perfectly idempotent (most aren't, once a
+ # property actually needs a fresh value like DynamoDB's TableId, or
+ # simply forgets to guard against re-creating its own prior name,
+ # like EventBus once did) silently produced a new, empty resource
+ # under a new identity — orphaning the real one, which anything
+ # still referencing it via Ref/Fn::GetAtt would then pick up the
+ # instant it was reprocessed later in the same update.
+ return physical_id, old_attrs or {}
handler = _RESOURCE_HANDLERS.get(resource_type)
if handler and "update" in handler:
if handler.get("update_with_logical_id"):
@@ -140,9 +170,13 @@ def _update_resource(resource_type: str, physical_id: str, old_props: dict,
logical_id=logical_id,
resource_type=resource_type,
)
- # No update handler — fall through to create. Most resource types make
- # their create idempotent; CFN never sees a fresh physical id this way.
- return _provision_resource(resource_type, physical_id, new_props, stack_name)
+ # No update handler — fall through to create, passing the *logical* id
+ # (not physical_id, unused here) so a name-less resource's create call
+ # derives the same _physical_name() it did originally: same
+ # (stack_name, logical_id) in, same deterministic name out. Most
+ # resource types make their create idempotent on that stable name;
+ # real CloudFormation never presents a fresh physical id this way.
+ return _provision_resource(resource_type, logical_id or physical_id, new_props, stack_name)
# ===========================================================================
diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.py
index 202cc156..63ee6c6a 100644
--- a/ministack/services/cloudformation/stacks.py
+++ b/ministack/services/cloudformation/stacks.py
@@ -160,15 +160,16 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
if prev_resource:
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 asyncio.to_thread(
_update_resource, resource_type, old_pid, old_props,
- resolved_props, stack_name, logical_id
+ 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
+ stack_name, logical_id, old_attrs
)
else:
if _is_custom_resource(resource_type):
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 7b9e6e87..67fedc4a 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -471,6 +471,57 @@ def test_cfn_stack_with_parameters(cfn, sqs):
assert any("cfn-t02-custom" in u for u in urls)
+def test_cfn_unnamed_dynamodb_table_survives_unrelated_update(cfn, ddb, ssm):
+ """A stack update must not touch an auto-named resource whose own
+ properties didn't change — DynamoDB::Table has no update handler, so it
+ falls back to calling create again on every update. That create wasn't
+ idempotent: with no explicit TableName, it derived a fresh name every
+ call, so any update of a stack containing an unnamed table silently
+ created a second, empty table under a new name — and an unrelated
+ resource referencing the table via Ref (real CloudFormation propagates
+ that Ref's resolved value on every update) picked up that new, wrong
+ identity the moment it was reprocessed."""
+ def template(param_value_source):
+ return json.dumps({
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Table": {
+ "Type": "AWS::DynamoDB::Table",
+ "Properties": {
+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
+ "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
+ "BillingMode": "PAY_PER_REQUEST",
+ },
+ },
+ "Param": {
+ "Type": "AWS::SSM::Parameter",
+ "Properties": {
+ "Name": "/cfn-t02f/table-name",
+ "Type": "String",
+ "Value": param_value_source,
+ "Description": "unrelated change forces this resource to be reprocessed",
+ },
+ },
+ },
+ })
+
+ cfn.create_stack(StackName="cfn-t02f", TemplateBody=template({"Ref": "Table"}))
+ _wait_stack(cfn, "cfn-t02f")
+ tables_before = set(ddb.list_tables()["TableNames"])
+ table_name_before = ssm.get_parameter(Name="/cfn-t02f/table-name")["Parameter"]["Value"]
+ assert table_name_before in tables_before
+
+ # Table itself is untouched; only Param's Description changes (forcing
+ # Param, not Table, to actually be reprocessed this update).
+ cfn.update_stack(StackName="cfn-t02f", TemplateBody=template({"Ref": "Table"}))
+ stack = _wait_stack(cfn, "cfn-t02f")
+ assert stack["StackStatus"] == "UPDATE_COMPLETE"
+
+ tables_after = set(ddb.list_tables()["TableNames"])
+ table_name_after = ssm.get_parameter(Name="/cfn-t02f/table-name")["Parameter"]["Value"]
+ assert tables_after == tables_before
+ assert table_name_after == table_name_before
+
def test_cfn_ssm_parameter_value_type_resolves_stored_value(cfn, ssm, sqs):
"""A `AWS::SSM::Parameter::Value<String>` template parameter's Default/
provided value is an SSM parameter *name*, not the value itself — real
@@ -3891,6 +3942,50 @@ def test_cfn_eventbus_getatt_arn(cfn, eb):
_wait_stack(cfn, "cfn-eb-t03")
+def test_cfn_eventbus_survives_unrelated_update(cfn, eb, sqs):
+ """A stack update must not fail an unchanged AWS::Events::EventBus.
+
+ EventBus has no update handler, so an update falls back to calling
+ create again — a name that already exists (its own, from the previous
+ deploy — e.g. a name computed client-side and baked into the template,
+ like CDK's EventBus construct default-names its bus) previously made
+ every update of a stack containing one fail with "already exists", even
+ when nothing about the bus itself changed. Fixed generically (see
+ _update_resource's no-op short-circuit), not with EventBus-specific
+ logic — this exercises that general fix against a real resource type
+ known to hit it."""
+ def template(queue_name):
+ return json.dumps({
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Bus": {
+ "Type": "AWS::Events::EventBus",
+ "Properties": {"Name": "cfn-eb-t10"},
+ },
+ "Queue": {
+ "Type": "AWS::SQS::Queue",
+ "Properties": {"QueueName": queue_name},
+ },
+ },
+ })
+
+ cfn.create_stack(StackName="cfn-eb-t10", TemplateBody=template("cfn-eb-t10-q1"))
+ stack = _wait_stack(cfn, "cfn-eb-t10")
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+ bus_before = eb.describe_event_bus(Name="cfn-eb-t10")
+
+ # Only the queue changes — the bus is untouched, exactly like a real
+ # redeploy that doesn't touch AuditTrail at all.
+ cfn.update_stack(StackName="cfn-eb-t10", TemplateBody=template("cfn-eb-t10-q2"))
+ stack = _wait_stack(cfn, "cfn-eb-t10")
+ assert stack["StackStatus"] == "UPDATE_COMPLETE"
+
+ bus_after = eb.describe_event_bus(Name="cfn-eb-t10")
+ assert bus_after["Arn"] == bus_before["Arn"]
+ urls = sqs.list_queues(QueueNamePrefix="cfn-eb-t10-q2").get("QueueUrls", [])
+ assert any("cfn-eb-t10-q2" in u for u in urls)
+
+
def test_cfn_eventbus_tags(cfn, eb):
"""Test EventBus tags are propagated."""
template = {