Skip to content

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

fix(cloudformation): list stack-tag changes in a change set (#1945)

iot-rocketc02f67e522a8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dc3e0dda..4a245283 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Fixed
+- **CloudFormation — a change set with only new stack tags lists them** — it ended `FAILED` with "didn't contain changes"; it now lists each resource the stack holds, other than a custom resource or wait condition, as a `Modify` with `Scope: Tags`, and stack tags given in another order are no change for a change set or `UpdateStack`. Contributed by @iot-rocket.
+- **CloudFormation — change sets list what a change reaches** — a resource that references a replaced resource, an attribute of a modified resource or a changed parameter is now listed as a `Modify` whose detail names the cause (`ChangeSource` `ResourceReference`, `ResourceAttribute` or `ParameterReference`, with `CausingEntity`). Contributed by @iot-rocket.
- **CloudFormation — change sets list what a change reaches** — a resource that references a replaced resource, an attribute of a modified resource or a changed parameter is now listed as a `Modify` whose detail names the cause (`ChangeSource` `ResourceReference`, `ResourceAttribute` or `ParameterReference`, with `CausingEntity`). Contributed by @iot-rocket.
- **ECS — `DescribeClusters` statistics** — `include=["STATISTICS"]` returns the sixteen running/pending task and active/draining service counters per launch type instead of an empty list.
- **ECS — `DescribeClusters` honours `include`** — `settings` and `tags` come back empty and `attachments` and `configuration` are left out unless requested, `CreateCluster` keeps `configuration`, and a CloudFormation cluster reports its tags and the default `containerInsights` setting.
diff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.py
index 0f329a43..e061940b 100644
--- a/ministack/services/cloudformation/changesets.py
+++ b/ministack/services/cloudformation/changesets.py
@@ -45,6 +45,7 @@ from .stacks import (
_diff_resources,
_stack_region,
_stack_region_context,
+ _stack_tags_changed,
)
logger = logging.getLogger("cloudformation")
@@ -511,8 +512,10 @@ def _create_change_set(params):
new_resolved = _resolve_props_for_diff(template, param_values, stack_name, stack_id)
changed_params = {k for k, v in param_values.items()
if old_params.get(k, {}).get("Value") != v.get("Value")}
+ retag = (stack.get("_resources", {}) if cs_type == "UPDATE"
+ and _stack_tags_changed(stack, tags, tags_given) else ())
changes = _diff_resources(old_resolved, new_resolved, stack.get("_resources"),
- template, changed_params)
+ template, changed_params, retag)
import_failure = None
if cs_type == "IMPORT":
# An import describes the resources being adopted, not the template
@@ -623,11 +626,15 @@ def _describe_change_set(params):
f"<CausingEntity>{_esc(d['CausingEntity'])}</CausingEntity>"
if d.get("CausingEntity") else ""
)
+ source_xml = (
+ f"<ChangeSource>{_esc(d['ChangeSource'])}</ChangeSource>"
+ if d.get("ChangeSource") else ""
+ )
details_xml += (
"<member>"
f"<Target>{target_xml}</Target>"
f"<Evaluation>{_esc(d.get('Evaluation', 'Static'))}</Evaluation>"
- f"<ChangeSource>{_esc(d.get('ChangeSource', 'DirectModification'))}</ChangeSource>"
+ f"{source_xml}"
f"{causing_xml}"
"</member>"
)
diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.py
index 68f0d2ba..fecc7b34 100644
--- a/ministack/services/cloudformation/handlers.py
+++ b/ministack/services/cloudformation/handlers.py
@@ -58,6 +58,7 @@ from .stacks import (
_deploy_stack_async,
_roll_back_operation,
_stack_region_context,
+ _stack_tags_changed,
)
logger = logging.getLogger("cloudformation")
@@ -934,9 +935,9 @@ def _stack_has_no_updates(stack, template, param_values, tags,
use_previous_template=False, tags_given=False):
"""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 body that
+ request either carries no tags or the tags the stack already has, in any
+ order. Real CloudFormation refuses such a request with ``No updates are to
+ be performed.`` instead of running an empty update. A template body that
carries a dynamic reference is the exception: the update is accepted
(with ``UsePreviousTemplate`` it is still refused) — measured on AWS."""
if template != stack.get("_template", {}):
@@ -946,9 +947,7 @@ def _stack_has_no_updates(stack, template, param_values, tags,
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 or tags_given) and tags != stack.get("Tags", []):
- return False
- return True
+ return not _stack_tags_changed(stack, tags, tags_given)
def _update_stack(params):
diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.py
index 580592b9..a0992def 100644
--- a/ministack/services/cloudformation/stacks.py
+++ b/ministack/services/cloudformation/stacks.py
@@ -31,6 +31,7 @@ from .provisioners import (
_property_recreation,
_provision_resource,
_snapshot_resource,
+ _tag_map,
_update_resource,
_with_stack_tags,
)
@@ -1079,6 +1080,19 @@ _DIFFED_ATTRIBUTES = (
"UpdateReplacePolicy",
)
+# The types a stack-tag change leaves out of a change set; every other
+# resource the stack holds, taggable or not, is a Modify with Scope Tags.
+_UNTAGGED_TYPES = (
+ "AWS::CloudFormation::CustomResource",
+ "AWS::CloudFormation::WaitCondition",
+ "AWS::CloudFormation::WaitConditionHandle",
+)
+
+
+def _stack_tags_changed(stack: dict, tags: list, tags_given: bool) -> bool:
+ """True when a request's stack tags differ from the stack's, order aside."""
+ return bool(tags or tags_given) and _tag_map(tags) != _tag_map(stack.get("Tags"))
+
_POLICY_ACTIONS = {"Delete": "Delete", "Retain": "Retain", "RetainExceptOnCreate": "Retain",
"Snapshot": "Snapshot"}
@@ -1128,7 +1142,7 @@ def _reference_details(res_def: dict, replacements: dict, changed_params) -> dic
def _diff_resources(old_template: dict, new_template: dict, resources: dict | None = None,
- template: dict | None = None, changed_params=()) -> list:
+ template: dict | None = None, changed_params=(), retag=()) -> list:
"""Diff two templates and return a list of change dicts.
A resource is a ``Modify`` when its ``Properties`` differ or when one of the
@@ -1140,6 +1154,8 @@ def _diff_resources(old_template: dict, new_template: dict, resources: dict | No
template, ``new_template`` by default) gets a detail naming that cause.
``resources`` are the stack's provisioned resources, whose physical ids a
``Remove`` or ``Modify`` reports.
+ Each resource in ``retag`` (the stack's resources when its tags change)
+ outside ``_UNTAGGED_TYPES`` also gets a ``Tags`` entry.
"""
old_res = old_template.get("Resources", {})
new_res = new_template.get("Resources", {})
@@ -1209,12 +1225,25 @@ def _diff_resources(old_template: dict, new_template: dict, resources: dict | No
**_policy_action(old_res[key], "DeletionPolicy"),
}
})
- elif key in replacements:
+ else:
+ rtype = new_res[key].get("Type", "")
+ retagged = key in retag and not (
+ rtype.startswith("Custom::") or rtype in _UNTAGGED_TYPES)
+ if key not in replacements and not retagged:
+ continue
scope = []
for d in details[key]:
if d["Target"]["Attribute"] not in scope:
scope.append(d["Target"]["Attribute"])
- replacement = replacements[key]
+ replacement = replacements.get(key, "False")
+ if retagged:
+ # Tags comes before the template's own changes in Details, last in
+ # Scope, and has no ChangeSource.
+ details[key].insert(0, {
+ "Target": {"Attribute": "Tags", "RequiresRecreation": "Never"},
+ "Evaluation": "Static",
+ })
+ scope.append("Tags")
changes.append({
"ResourceChange": {
"Action": "Modify",
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 124c0caf..8f063bf4 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -9881,6 +9881,66 @@ def test_cfn_change_set_tags_replace_the_previous_stack_tags(cfn, sqs):
_delete_cfn_test_stack(cfn, name)
+def test_cfn_change_set_with_only_new_stack_tags(cfn, sqs):
+ """New stack tags alone make a change set: each resource the stack holds
+ but a wait condition handle is a Modify with Scope Tags, and the execution
+ retags the queue. The same tags in another order, or no Tags, are no
+ change, for a change set and for UpdateStack; an empty list clears them."""
+ name = f"cfn-cs-tags-only-{_uuid_mod.uuid4().hex[:8]}"
+ template = json.dumps({
+ "Conditions": {"Never": {"Fn::Equals": ["a", "b"]}},
+ "Resources": {
+ "Queue": {"Type": "AWS::SQS::Queue"},
+ "Off": {"Type": "AWS::SQS::Queue", "Condition": "Never"},
+ "Policy": {"Type": "AWS::SQS::QueuePolicy", "Properties": {
+ "Queues": [{"Ref": "Queue"}],
+ "PolicyDocument": {"Version": "2012-10-17", "Statement": [{
+ "Effect": "Deny", "Principal": "*", "Action": "sqs:SendMessage",
+ "Resource": "*"}]}}},
+ "Handle": {"Type": "AWS::CloudFormation::WaitConditionHandle"},
+ },
+ "Outputs": {"QueueUrl": {"Value": {"Ref": "Queue"}}},
+ })
+ tags = [{"Key": "team", "Value": "a"}, {"Key": "env", "Value": "dev"}]
+ retagged = [{"Key": "team", "Value": "b"}, {"Key": "env", "Value": "dev"}]
+
+ def change_set(cs_name, **kwargs):
+ cfn.create_change_set(StackName=name, ChangeSetName=cs_name,
+ UsePreviousTemplate=True, **kwargs)
+ return cfn.describe_change_set(ChangeSetName=cs_name, StackName=name)
+
+ cfn.create_stack(StackName=name, TemplateBody=template, Tags=tags)
+ try:
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ with pytest.raises(ClientError, match="No updates are to be performed"):
+ cfn.update_stack(StackName=name, UsePreviousTemplate=True, Tags=tags[::-1])
+ for cs_name, kwargs in (("omitted", {}), ("reordered", {"Tags": tags[::-1]})):
+ described = change_set(cs_name, **kwargs)
+ assert described["Status"] == "FAILED", cs_name
+ assert "didn't contain changes" in described["StatusReason"]
+
+ tag_detail = {"Target": {"Attribute": "Tags", "RequiresRecreation": "Never"},
+ "Evaluation": "Static"}
+ for cs_name, new_tags in (("cleared", []), ("retag", retagged)):
+ described = change_set(cs_name, Tags=new_tags)
+ assert (described["Status"], described["ExecutionStatus"]) == (
+ "CREATE_COMPLETE", "AVAILABLE"), described.get("StatusReason")
+ assert [(c["ResourceChange"]["LogicalResourceId"], c["ResourceChange"]["Action"],
+ c["ResourceChange"]["Replacement"], c["ResourceChange"]["Scope"],
+ c["ResourceChange"]["Details"]) for c in described["Changes"]] == [
+ (lid, "Modify", "False", ["Tags"], [tag_detail]) for lid in ("Policy", "Queue")]
+
+ cfn.execute_change_set(ChangeSetName="retag", StackName=name)
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert stack["Tags"] == retagged
+ tags_now = sqs.list_queue_tags(QueueUrl=_output(stack, "QueueUrl"))["Tags"]
+ assert (tags_now["team"], tags_now["env"]) == ("b", "dev")
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
def test_cfn_stack_update_keeps_foreign_tags_on_table_and_project(cfn, ddb, codebuild, apigw_v1):
"""Tags set outside the stack on a table (TagResource) and on a CodeBuild
project (UpdateProject) survive a stack-tag change, which also reaches a
@@ -26055,6 +26115,32 @@ def test_policy_only_edit_does_not_replace():
assert change["Scope"] == ["UpdateReplacePolicy"]
+# Measured: a stack-tag change lists every resource the stack holds but
+# custom resources and wait conditions, whether or not the type takes tags.
[email protected]("rtype,listed", [
+ ("AWS::SQS::QueuePolicy", True),
+ ("AWS::CDK::Metadata", True),
+ ("AWS::CloudFormation::Stack", True),
+ ("Custom::Echo", False),
+ ("AWS::CloudFormation::CustomResource", False),
+ ("AWS::CloudFormation::WaitCondition", False),
+ ("AWS::CloudFormation::WaitConditionHandle", False),
+])
+def test_stack_tag_change_lists_each_kept_resource(rtype, listed):
+ template = _template(rtype, {})
+ changes = _diff_resources(template, template, retag={"R"})
+ assert [c["ResourceChange"]["Scope"] for c in changes] == ([["Tags"]] if listed else [])
+
+
+def test_stack_tag_change_joins_a_property_change():
+ change = _diff_resources(_template("AWS::SQS::Queue", {"DelaySeconds": 0}),
+ _template("AWS::SQS::Queue", {"DelaySeconds": 5}),
+ retag={"R"})[0]["ResourceChange"]
+ assert change["Scope"] == ["Properties", "Tags"]
+ assert [d["Target"]["Attribute"] for d in change["Details"]] == ["Tags", "Properties"]
+ assert change["Replacement"] == "False"
+
+
def test_reporting_tables_are_consistent():
assert _REPLACING_PROPERTIES.keys() <= _RESOURCE_HANDLERS.keys()
# A conditional row for an unlisted type would never be read.