Skip to content

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

fix(cloudformation): refuse an UpdateStack that changes nothing (#1639)

iot-rocket96d52d02dd55
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7f0c5d95..1e52c9a8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **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
- **CloudFront — the policy, OAC and function types provision from CloudFormation** — `AWS::CloudFront::CachePolicy`, `OriginRequestPolicy`, `ResponseHeadersPolicy`, `OriginAccessControl` and `Function` had complete APIs and no CloudFormation provisioner, so a CDK app declaring any of them rolled the stack back with `Unsupported resource type` while the same objects were creatable over the API. Each type now provisions by converting its CFN properties to the element the service's own config parser accepts, so validation, defaults and the stored record are identical to the API path, and `Ref`/`Fn::GetAtt` return the documented values (policy `Id`, OAC `Id`, function `FunctionARN`). Deletes are wired; an update replaces rather than mutating in place. Contributed by @mm-salesqueze.
diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.py
index ff8d7440..8c9acdf6 100644
--- a/ministack/services/cloudformation/handlers.py
+++ b/ministack/services/cloudformation/handlers.py
@@ -492,6 +492,24 @@ def _delete_stack(params):
# --- UpdateStack ---
+def _stack_has_no_updates(stack, template, param_values, tags):
+ """True when an UpdateStack would change nothing: the template equals the
+ one the stack runs, every parameter resolves to its current value, and the
+ request either carries no tags or the tags the stack already has. Real
+ CloudFormation refuses such a request with ``No updates are to be
+ performed.`` instead of running an empty update (a template with a
+ dynamic reference is the documented exception, and the emulator refuses
+ dynamic references up front)."""
+ if template != stack.get("_template", {}):
+ return False
+ current = {k: v.get("Value") for k, v in stack.get("_resolved_params", {}).items()}
+ if {k: v.get("Value") for k, v in param_values.items()} != current:
+ return False
+ if tags and tags != stack.get("Tags", []):
+ return False
+ return True
+
+
def _update_stack(params):
from ministack.services.cloudformation import _stacks
stack_name = _p(params, "StackName")
@@ -549,6 +567,9 @@ def _update_stack(params):
except ValueError as exc:
return _error("ValidationError", str(exc))
+ if _stack_has_no_updates(stack, template, param_values, tags):
+ return _error("ValidationError", "No updates are to be performed.")
+
# Save previous state for rollback
previous_stack = {
"_resources": copy.deepcopy(stack.get("_resources", {})),
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index a16f6548..923a4e2c 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -1169,7 +1169,7 @@ def test_cfn_unnamed_dynamodb_table_survives_unrelated_update(cfn, ddb, ssm):
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):
+ def template(param_value_source, description="unrelated change forces this resource to be reprocessed"):
return json.dumps({
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
@@ -1187,7 +1187,7 @@ def test_cfn_unnamed_dynamodb_table_survives_unrelated_update(cfn, ddb, ssm):
"Name": "/cfn-t02f/table-name",
"Type": "String",
"Value": param_value_source,
- "Description": "unrelated change forces this resource to be reprocessed",
+ "Description": description,
},
},
},
@@ -1200,8 +1200,10 @@ def test_cfn_unnamed_dynamodb_table_survives_unrelated_update(cfn, ddb, ssm):
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"}))
+ # Param, not Table, to actually be reprocessed this update). An identical
+ # template would be refused with "No updates are to be performed."
+ cfn.update_stack(StackName="cfn-t02f", TemplateBody=template(
+ {"Ref": "Table"}, description="the unrelated change, second edition"))
stack = _wait_stack(cfn, "cfn-t02f")
assert stack["StackStatus"] == "UPDATE_COMPLETE"
@@ -14362,3 +14364,60 @@ def test_cfn_delete_change_set_missing_is_idempotent(cfn):
with pytest.raises(ClientError) as exc:
cfn.delete_change_set(StackName=name, ChangeSetName="cdk-deploy-change-set")
assert exc.value.response["Error"]["Code"] == "ValidationError"
+
+
+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
+ identical TemplateBody and for UsePreviousTemplate alike; a changed
+ parameter value or a changed tag set is an update."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-no-updates-{uid}"
+ template = json.dumps({
+ "Parameters": {"Visibility": {"Type": "Number", "Default": 30}},
+ "Resources": {"Queue": {"Type": "AWS::SQS::Queue", "Properties": {
+ "QueueName": f"cfn-no-updates-{uid}",
+ "VisibilityTimeout": {"Ref": "Visibility"}}}},
+ })
+ cfn.create_stack(StackName=stack_name, TemplateBody=template,
+ Tags=[{"Key": "stage", "Value": "one"}])
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+
+ for kwargs in (
+ {"TemplateBody": template},
+ {"UsePreviousTemplate": True},
+ {"TemplateBody": template, "Parameters": [
+ {"ParameterKey": "Visibility", "ParameterValue": "30"}]},
+ {"UsePreviousTemplate": True, "Tags": [{"Key": "stage", "Value": "one"}]},
+ ):
+ with pytest.raises(ClientError) as exc:
+ cfn.update_stack(StackName=stack_name, **kwargs)
+ assert exc.value.response["Error"]["Code"] == "ValidationError"
+ assert exc.value.response["Error"]["Message"] == "No updates are to be performed."
+ events = cfn.describe_stack_events(StackName=stack_name)["StackEvents"]
+ assert not [e for e in events if e["ResourceStatus"].startswith("UPDATE")]
+
+ cfn.update_stack(StackName=stack_name, UsePreviousTemplate=True,
+ Parameters=[{"ParameterKey": "Visibility", "ParameterValue": "45"}])
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ queue_url = sqs.get_queue_url(QueueName=f"cfn-no-updates-{uid}")["QueueUrl"]
+ assert sqs.get_queue_attributes(
+ QueueUrl=queue_url, AttributeNames=["VisibilityTimeout"]
+ )["Attributes"]["VisibilityTimeout"] == "45"
+
+ # A parameter left out of an update reverts to its template default,
+ # so a tags-only update keeps the value with UsePreviousValue.
+ cfn.update_stack(StackName=stack_name, UsePreviousTemplate=True,
+ Parameters=[{"ParameterKey": "Visibility", "UsePreviousValue": True}],
+ Tags=[{"Key": "stage", "Value": "two"}])
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert stack["Tags"] == [{"Key": "stage", "Value": "two"}]
+ assert stack["Parameters"] == [
+ {"ParameterKey": "Visibility", "ParameterValue": "45"}]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+