Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(cloudformation): list the resources a change set change reaches (#1944)
iot-rocketd898494f058b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a09c44db..dc3e0dda 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Fixed+- **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.- **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.pyindex 7fb22f8d..0f329a43 100644--- a/ministack/services/cloudformation/changesets.py+++ b/ministack/services/cloudformation/changesets.py@@ -509,7 +509,10 @@ def _create_change_set(params):with _stack_region_context(stack, stack_id):old_resolved = _resolve_props_for_diff(old_template, old_params, stack_name, stack_id)new_resolved = _resolve_props_for_diff(template, param_values, stack_name, stack_id)- changes = _diff_resources(old_resolved, new_resolved, stack.get("_resources"))+ changed_params = {k for k, v in param_values.items()+ if old_params.get(k, {}).get("Value") != v.get("Value")}+ changes = _diff_resources(old_resolved, new_resolved, stack.get("_resources"),+ template, changed_params)import_failure = Noneif cs_type == "IMPORT":# An import describes the resources being adopted, not the template@@ -616,11 +619,16 @@ def _describe_change_set(params):f"<RequiresRecreation>{_esc(target['RequiresRecreation'])}""</RequiresRecreation>")+ causing_xml = (+ f"<CausingEntity>{_esc(d['CausingEntity'])}</CausingEntity>"+ if d.get("CausingEntity") 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"{causing_xml}""</member>")# botocore reads an empty element as "", so a member the change doesdiff --git a/ministack/services/cloudformation/engine.py b/ministack/services/cloudformation/engine.pyindex b77f2267..34855d8d 100644--- a/ministack/services/cloudformation/engine.py+++ b/ministack/services/cloudformation/engine.py@@ -1322,58 +1322,42 @@ def _resolve_refs(value, resources, params, conditions, mappings,# Dependency Extractor + Topological Sort# ===========================================================================+def _intrinsic_references(value):+ """Yield (name, attribute or None) for each Ref, Fn::GetAtt and Fn::Sub variable."""+ if isinstance(value, list):+ for item in value:+ yield from _intrinsic_references(item)+ return+ if not isinstance(value, dict):+ return+ for key, arg in value.items():+ if key == "Ref" and isinstance(arg, str):+ yield arg, None+ elif key == "Fn::GetAtt":+ parts = arg.split(".", 1) if isinstance(arg, str) else arg+ if isinstance(parts, list) and parts and isinstance(parts[0], str):+ attr = parts[1] if len(parts) > 1 and isinstance(parts[1], str) else None+ yield parts[0], attr+ elif key == "Fn::Sub":+ text, bindings = (list(arg) + [{}])[:2] if isinstance(arg, list) else (arg, {})+ bindings = bindings if isinstance(bindings, dict) else {}+ for var in re.findall(r"\$\{([^}]+)\}", str(text)):+ if not var.startswith("!") and var not in bindings:+ name, _, attr = var.partition(".")+ yield name, attr or None+ yield from _intrinsic_references(list(bindings.values()))+ else:+ yield from _intrinsic_references(arg)++def _extract_deps(resource_def: dict, all_resource_names: set) -> set:"""Walk a resource definition and extract dependency logical IDs."""- deps = set()-- def _walk(obj):- if isinstance(obj, dict):- if "Ref" in obj:- ref = obj["Ref"]- if ref in all_resource_names:- deps.add(ref)- if "Fn::GetAtt" in obj:- args = obj["Fn::GetAtt"]- if isinstance(args, list) and args:- if args[0] in all_resource_names:- deps.add(args[0])- elif isinstance(args, str):- logical = args.split(".")[0]- if logical in all_resource_names:- deps.add(logical)- if "Fn::Sub" in obj:- sub_val = obj["Fn::Sub"]- template_str = sub_val[0] if isinstance(sub_val, list) else sub_val- for match in re.finditer(r"\$\{([^}]+)\}", str(template_str)):- var = match.group(1)- if var.startswith("!"):- continue- base = var.split(".")[0]- if base in all_resource_names:- deps.add(base)- # Walk ALL branches of Fn::If- if "Fn::If" in obj:- args = obj["Fn::If"]- for branch in args[1:]:- _walk(branch)- for k, v in obj.items():- if k not in ("Ref", "Fn::GetAtt", "Fn::Sub", "Fn::If"):- _walk(v)- elif isinstance(obj, list):- for item in obj:- _walk(item)-- # DependsOn+ deps = {name for name, _ in _intrinsic_references(resource_def.get("Properties", {}))+ if name in all_resource_names}depends_on = resource_def.get("DependsOn", [])if isinstance(depends_on, str):depends_on = [depends_on]- for d in depends_on:- if d in all_resource_names:- deps.add(d)-- # Walk Properties- _walk(resource_def.get("Properties", {}))-+ deps.update(d for d in depends_on if d in all_resource_names)return depsdiff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.pyindex 401513e7..580592b9 100644--- a/ministack/services/cloudformation/stacks.py+++ b/ministack/services/cloudformation/stacks.py@@ -17,6 +17,7 @@ from .engine import (_NO_VALUE,_evaluate_conditions,_extract_deps,+ _intrinsic_references,_resolve_dynamic_references,_resolve_refs,_topological_sort,@@ -1090,22 +1091,104 @@ def _policy_action(res_def: dict, attribute: str, prefix: str = "") -> dict:return {"PolicyAction": prefix + action} if action else {}-def _diff_resources(old_template: dict, new_template: dict, resources: dict | None = None) -> list:+def _replacement(details: list, type_changed: bool) -> str:+ """The Replacement of a Modify that carries these details."""+ recreation = {(d["Target"]["RequiresRecreation"], d["Evaluation"]) for d in details}+ if type_changed or ("Always", "Static") in recreation:+ return "True"+ if any(r != "Never" for r, _ in recreation):+ return "Conditional"+ return "False"+++def _reference_details(res_def: dict, replacements: dict, changed_params) -> dict:+ """Details per property for its references to changed parameters and resources."""+ rtype = res_def.get("Type", "")+ found: dict = {}+ for name, value in (res_def.get("Properties") or {}).items():+ for ref, attr in _intrinsic_references(value):+ if ref in changed_params and attr is None:+ source, entity, evaluation = "ParameterReference", ref, "Static"+ elif ref in replacements and (attr or replacements[ref] != "False"):+ source = "ResourceAttribute" if attr else "ResourceReference"+ entity = f"{ref}.{attr}" if attr else ref+ evaluation = "Static" if replacements[ref] == "True" else "Dynamic"+ else:+ continue+ detail = {+ "Target": {"Attribute": "Properties", "Name": name,+ "RequiresRecreation": _property_recreation(rtype, name)},+ "Evaluation": evaluation,+ "ChangeSource": source,+ "CausingEntity": entity,+ }+ if detail not in found.setdefault(name, []):+ found[name].append(detail)+ return found+++def _diff_resources(old_template: dict, new_template: dict, resources: dict | None = None,+ template: dict | None = None, changed_params=()) -> list:"""Diff two templates and return a list of change dicts.A resource is a ``Modify`` when its ``Properties`` differ or when one of theattributes in ``_DIFFED_ATTRIBUTES`` differs; each changed attribute becomesa ``Details`` entry (``Target.Attribute``, plus the property name for``Properties``) and is listed in ``Scope``, as the API reference defines them.+ A property that references a changed parameter, a replaced resource or an+ attribute of a modified resource in ``template`` (the unresolved new+ 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."""old_res = old_template.get("Resources", {})new_res = new_template.get("Resources", {})+ raw_res = (template or new_template).get("Resources", {})changes = []- all_keys = old_res.keys() | new_res.keys()- for key in sorted(all_keys):+ common = old_res.keys() & new_res.keys()+ changed_props, attr_details, type_changed = {}, {}, {}+ for key in common:+ old_props = old_res[key].get("Properties", {}) or {}+ new_props = new_res[key].get("Properties", {}) or {}+ changed_props[key] = {name for name in set(old_props) | set(new_props)+ if old_props.get(name) != new_props.get(name)}+ attr_details[key] = [+ {"Target": {"Attribute": attr, "RequiresRecreation": "Never"},+ "Evaluation": "Static", "ChangeSource": "DirectModification"}+ for attr in _DIFFED_ATTRIBUTES+ if old_res[key].get(attr) != new_res[key].get(attr)+ ]+ type_changed[key] = old_res[key].get("Type") != new_res[key].get("Type")++ def _modify_details(key, refs):+ details = []+ rtype = new_res[key].get("Type", "")+ for name in sorted(changed_props[key] | set(refs)):+ if name in changed_props[key]:+ details.append({+ "Target": {"Attribute": "Properties", "Name": name,+ "RequiresRecreation": _property_recreation(rtype, name)},+ "Evaluation": "Dynamic" if refs.get(name) else "Static",+ "ChangeSource": "DirectModification",+ })+ details.extend(refs.get(name, []))+ return details + attr_details[key]++ # A replaced or modified resource changes what references it, which can in+ # turn replace or modify the referencing resource.+ refs: dict = {}+ while True:+ details = {key: _modify_details(key, refs.get(key, {})) for key in common}+ replacements = {key: _replacement(d, type_changed[key])+ for key, d in details.items() if d or type_changed[key]}+ found = {key: _reference_details(raw_res.get(key, {}), replacements, changed_params)+ for key in common}+ if found == refs:+ break+ refs = found++ for key in sorted(old_res.keys() | new_res.keys()):pid = (resources or {}).get(key, {}).get("PhysicalResourceId")physical = {"PhysicalResourceId": pid} if pid else {}if key not in old_res:@@ -1126,42 +1209,12 @@ def _diff_resources(old_template: dict, new_template: dict, resources: dict | No**_policy_action(old_res[key], "DeletionPolicy"),}})- else:- details = []- old_props = old_res[key].get("Properties", {}) or {}- new_props = new_res[key].get("Properties", {}) or {}- rtype = new_res[key].get("Type", "")- if old_props != new_props:- for name in sorted(set(old_props) | set(new_props)):- if old_props.get(name) != new_props.get(name):- details.append({- "Target": {"Attribute": "Properties", "Name": name,- "RequiresRecreation":- _property_recreation(rtype, name)},- "Evaluation": "Static",- "ChangeSource": "DirectModification",- })- for attr in _DIFFED_ATTRIBUTES:- if old_res[key].get(attr) != new_res[key].get(attr):- details.append({- "Target": {"Attribute": attr, "RequiresRecreation": "Never"},- "Evaluation": "Static",- "ChangeSource": "DirectModification",- })- type_changed = old_res[key].get("Type") != new_res[key].get("Type")- if not details and not type_changed:- continue+ elif key in replacements:scope = []- for d in details:+ for d in details[key]:if d["Target"]["Attribute"] not in scope:scope.append(d["Target"]["Attribute"])- recreation = {d["Target"].get("RequiresRecreation") for d in details}- if type_changed or "Always" in recreation:- replacement = "True"- elif "Conditionally" in recreation:- replacement = "Conditional"- else:- replacement = "False"+ replacement = replacements[key]changes.append({"ResourceChange": {"Action": "Modify",@@ -1172,7 +1225,7 @@ def _diff_resources(old_template: dict, new_template: dict, resources: dict | No**(_policy_action(new_res[key], "UpdateReplacePolicy", "ReplaceAnd")if replacement == "True" else {}),"Scope": scope,- "Details": details,+ "Details": details[key],}})return changesdiff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex c4eccc62..124c0caf 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -26196,6 +26196,63 @@ def test_change_set_replacement_reports_the_update_replace_policy(policy, expectassert (change["Replacement"], change.get("PolicyAction")) == ("True", expected)+_DIRECT_STATIC = ("DirectModification", "Static", None)++[email protected]("edit,params,expected", [+ (lambda r: r["Queue"]["Properties"].update(QueueName=r["Queue"]["Properties"]["QueueName"] + "-new"), [], {+ "Queue": ("True", {_DIRECT_STATIC}),+ "ByRef": ("False", {("ResourceReference", "Static", "Queue")}),+ "ByArn": ("False", {("ResourceAttribute", "Static", "Queue.Arn")}),+ "Chained": ("False", {("ResourceAttribute", "Dynamic", "ByRef.Value")}),+ "Named": ("True", {("ResourceAttribute", "Static", "Queue.QueueName")}),+ "ByNamed": ("False", {("ResourceReference", "Static", "Named")}),+ }),+ (lambda r: r["Queue"]["Properties"].update(VisibilityTimeout=60), [], {+ "Queue": ("False", {_DIRECT_STATIC}),+ "ByArn": ("False", {("ResourceAttribute", "Dynamic", "Queue.Arn")}),+ "Named": ("Conditional", {("ResourceAttribute", "Dynamic", "Queue.QueueName")}),+ "ByNamed": ("False", {("ResourceReference", "Dynamic", "Named")}),+ }),+ (lambda r: None, [{"ParameterKey": "Val", "ParameterValue": "two"}], {+ "ByParam": ("False", {("ParameterReference", "Static", "Val"),+ ("DirectModification", "Dynamic", None)}),+ }),+], ids=["replace", "modify-in-place", "parameter"])+def test_change_set_lists_what_a_change_reaches(cfn, stack, edit, params, expected):+ """Resources that reference a changed resource or parameter are listed with the cause."""+ name = f"repl-{_uuid_mod.uuid4().hex[:10]}"++ def param(value):+ return {"Type": "AWS::SSM::Parameter", "Properties": {"Type": "String", "Value": value}}++ def template():+ return {"Parameters": {"Val": {"Type": "String", "Default": "one"}}, "Resources": {+ "Queue": {"Type": "AWS::SQS::Queue", "Properties": {"QueueName": name}},+ "ByRef": param({"Ref": "Queue"}),+ "ByArn": param({"Fn::GetAtt": ["Queue", "Arn"]}),+ "Chained": param({"Fn::GetAtt": ["ByRef", "Value"]}),+ "Named": {"Type": "AWS::SSM::Parameter", "Properties": {+ "Name": {"Fn::Sub": "/" + name + "/${Queue.QueueName}"}, "Type": "String", "Value": "v"}},+ "ByNamed": param({"Ref": "Named"}),+ "ByParam": param({"Ref": "Val"}),+ "Static": param("static"),+ }}++ stack_name = stack(template())+ new = template()+ edit(new["Resources"])+ cfn.create_change_set(StackName=stack_name, ChangeSetName="cs", TemplateBody=json.dumps(new),+ Parameters=params)+ cfn.get_waiter("change_set_create_complete").wait(+ StackName=stack_name, ChangeSetName="cs", WaiterConfig={"Delay": 1, "MaxAttempts": 30})+ changes = cfn.describe_change_set(StackName=stack_name, ChangeSetName="cs")["Changes"]+ assert {c["ResourceChange"]["LogicalResourceId"]: (+ c["ResourceChange"]["Replacement"],+ {(d["ChangeSource"], d["Evaluation"], d.get("CausingEntity")) for d in c["ResourceChange"]["Details"]},+ ) for c in changes} == expected++def test_cfn_appconfig_application_updates_in_place(cfn, appconfig_client):"""An application update keeps its id."""suffix = _uuid_mod.uuid4().hex[:8]