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): rollback restores template, parameters and tags (#1641)
iot-rocket31c44d33f237
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c6b332d8..a53dcb81 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **CloudFormation — a rolled-back update leaves the stack reporting what it ran before** — after `UPDATE_ROLLBACK_COMPLETE`, `GetTemplate` returned the template that failed and `DescribeStacks` the failed update's parameters and tags, so a `cdk diff` after a failed deploy compared against the wrong base. The rollback now restores the previous template body, parameters and tags together with the resources and outputs. Contributed by @iot-rocket.- **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.diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.pyindex 0d71e489..670f30ce 100644--- a/ministack/services/cloudformation/handlers.py+++ b/ministack/services/cloudformation/handlers.py@@ -612,6 +612,8 @@ def _update_stack(params):"_template": copy.deepcopy(stack.get("_template", {})),"_template_body": stack.get("_template_body", ""),"_resolved_params": copy.deepcopy(stack.get("_resolved_params", {})),+ "Parameters": copy.deepcopy(stack.get("Parameters", [])),+ "Tags": copy.deepcopy(stack.get("Tags", [])),"Outputs": copy.deepcopy(stack.get("Outputs", [])),}diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.pyindex a97f96cd..a564e143 100644--- a/ministack/services/cloudformation/stacks.py+++ b/ministack/services/cloudformation/stacks.py@@ -372,6 +372,15 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,stack["_resources"] = previous_stack.get("_resources", {})stack["_template"] = previous_stack.get("_template", {})stack["_resolved_params"] = previous_stack.get("_resolved_params", {})+ # What the API reports has to follow: GetTemplate serves+ # _template_body and DescribeStacks the Parameters and Tags,+ # and a rolled-back stack reports what it ran before the+ # update, not what failed.+ stack["_template_body"] = previous_stack.get(+ "_template_body", stack.get("_template_body", ""))+ stack["Parameters"] = previous_stack.get(+ "Parameters", stack.get("Parameters", []))+ stack["Tags"] = previous_stack.get("Tags", stack.get("Tags", []))stack["Outputs"] = previous_stack.get("Outputs", [])stack["StackStatus"] = "UPDATE_ROLLBACK_COMPLETE"else:diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex a1def6f7..17d63cb9 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -14366,6 +14366,42 @@ def test_cfn_delete_change_set_missing_is_idempotent(cfn):assert exc.value.response["Error"]["Code"] == "ValidationError"+def test_cfn_update_rollback_reports_the_previous_template_parameters_and_tags(cfn, sqs):+ """After UPDATE_ROLLBACK_COMPLETE the stack describes what it ran before+ the failed update: GetTemplate returns the previous template body,+ DescribeStacks the previous parameter values and tags. The update fails on+ the custom-named table whose key type change requires replacement."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-rb-report-{uid}"+ queue_name = f"cfn-rb-report-{uid}"+ table_name = f"cfn-rb-report-{uid}"++ def template(key_type, description):+ return json.dumps({+ "Description": description,+ "Parameters": {"Visibility": {"Type": "Number", "Default": 30}},+ "Resources": {+ "Queue": {"Type": "AWS::SQS::Queue", "Properties": {+ "QueueName": queue_name,+ "VisibilityTimeout": {"Ref": "Visibility"}}},+ "Table": {"Type": "AWS::DynamoDB::Table", "DependsOn": "Queue", "Properties": {+ "TableName": table_name,+ "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": key_type}],+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],+ "BillingMode": "PAY_PER_REQUEST",+ }},+ },+ })++ def normalized(body):+ return json.loads(body) if isinstance(body, str) else body++ original = template("S", "before")+ cfn.create_stack(+ StackName=stack_name, TemplateBody=original,+ Parameters=[{"ParameterKey": "Visibility", "ParameterValue": "30"}],+ Tags=[{"Key": "stage", "Value": "before"}],+ )def test_cfn_export_in_use_is_an_import_not_a_mention(cfn, ssm):"""Deleting an exporting stack is refused only while another stack importsthe export through Fn::ImportValue, its argument resolved with that stack's@@ -14431,6 +14467,19 @@ def test_cfn_update_stack_without_changes_is_refused(cfn, sqs):stack = _wait_stack(cfn, stack_name)assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ cfn.update_stack(+ StackName=stack_name, TemplateBody=template("N", "after"),+ Parameters=[{"ParameterKey": "Visibility", "ParameterValue": "45"}],+ Tags=[{"Key": "stage", "Value": "after"}],+ )+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")++ assert normalized(cfn.get_template(StackName=stack_name)["TemplateBody"]) == json.loads(original)+ assert stack["Parameters"] == [+ {"ParameterKey": "Visibility", "ParameterValue": "30"}]+ assert stack["Tags"] == [{"Key": "stage", "Value": "before"}]+ assert stack.get("Description") in (None, "before")for kwargs in ({"TemplateBody": template},{"UsePreviousTemplate": True},