Skip to content

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

feat(cloudformation): RollbackStack and stack drift detection (#1879)

Fábio André Ramos Rodrigues22055f64c8d4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5d480032..085de01e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,6 +27,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **CloudFormation — a nested stack's update deletes the resources its template drops** — a resource removed from the child template, or created by a failed child update that was rolled back, stayed in its service and in the nested stack's resource list. Contributed by @iot-rocket.
### Added
+- **CloudFormation — `RollbackStack`** — a stack left `CREATE_FAILED` or `UPDATE_FAILED` by `DisableRollback` is rolled back to its last stable state, as `cdk rollback` expects. A failed create deletes what it made and ends `ROLLBACK_COMPLETE`; a failed update reverts in-place changes, deletes what it added and ends `UPDATE_ROLLBACK_COMPLETE` with the previous template, parameters, tags and outputs. `RetainExceptOnCreate` also deletes new resources marked `Retain`. Any other status answers `ValidationError`.
+- **CloudFormation — stack drift detection** — `DetectStackDrift` (with `LogicalResourceIds`), `DescribeStackDriftDetectionStatus`, `DetectStackResourceDrift` and `DescribeStackResourceDrifts` (status filters, `MaxResults`, `NextToken`) compare the properties a template sets, plus stack-level tags, with the owning service's current record. A deleted record is `DELETED`; a changed one is `MODIFIED` with `PropertyDifferences` (`ADD`, `REMOVE`, `NOT_EQUAL`) and expected and actual properties. Property-level drift covers SQS queues, SSM parameters, SNS topics, Lambda functions, IAM roles, DynamoDB tables, S3 buckets (name and versioning), log groups and Secrets Manager secrets; Kinesis streams, ECR repositories, state machines, EventBridge rules and SNS subscriptions get an existence check; other types stay `NOT_CHECKED`. `DescribeStacks`, `ListStacks`, `DescribeStackResource(s)` and `ListStackResources` report `DriftInformation`, and results persist with the stack. Detection runs on `CREATE_COMPLETE`, `UPDATE_COMPLETE`, `UPDATE_ROLLBACK_COMPLETE` and `UPDATE_ROLLBACK_FAILED` stacks only.
- **CloudWatch Logs — resource policy** — `PutResourcePolicy`, `DescribeResourcePolicies` and `DeleteResourcePolicy`, the account/log-group-level policy Crossplane's `provider-aws-cloudwatchlogs` manages for cross-service log delivery — distinct from the per-destination `PutDestinationPolicy` and the delivery-scoped `PutDeliveryDestinationPolicy`. `PutResourcePolicy` supports `expectedRevisionId` for optimistic concurrency (`OperationAbortedException` on mismatch). Contributed by @fabio-andre-rodrigues.
- **Bedrock AgentCore — resource-based policies** — `PutResourcePolicy`, `GetResourcePolicy` and `DeleteResourcePolicy` persist policies for runtimes and endpoints. With `AUTH=true`, runtime invocation evaluates caller principals, explicit denies and the runtime-plus-endpoint policy requirement for cross-account calls. This emulates the documented AgentCore policy contract locally; it does not validate behavior against AWS.
- **KMS — grants** — `CreateGrant`, `RevokeGrant` and `RetireGrant`, and `ListGrants` returns the grants they create instead of always an empty list. `CreateGrant` returns a `GrantId` and a `GrantToken`, follows the key state (`DisabledException` for a disabled key, `KMSInvalidStateException` pending deletion, replica deletion or import), rejects operations the key cannot perform (`Sign` / `Verify` / `GenerateMac` / `VerifyMac` on a symmetric encryption key, data key operations on an asymmetric key, anything but `GenerateMac` / `VerifyMac` / `DescribeKey` / `CreateGrant` / `RetireGrant` on an HMAC key) with `ValidationException`, and with a `Name` a retry with identical parameters returns the original `GrantId` with a new token. `ListGrants` filters by `GrantId` and `GranteePrincipal` and pages with `Limit` (1 to 100, default 50) and `Marker`. `RetireGrant` takes a `GrantToken`, or a `KeyId` and `GrantId`. All three honour `DryRun`, and grants persist with the key. Grants are recorded but not evaluated when authorizing other calls, as with key policies. Contributed by @DaviReisVieira.
diff --git a/README.md b/README.md
index 832acef1..38a02694 100644
--- a/README.md
+++ b/README.md
@@ -459,7 +459,7 @@ subnet = ec2.create_subnet(
| Feature | Details |
|---------|---------|
-| **Stack Operations** | CreateStack, UpdateStack, DeleteStack, DescribeStacks, ListStacks, DescribeStackEvents, DescribeStackResource, DescribeStackResources, GetTemplate, ValidateTemplate, GetTemplateSummary |
+| **Stack Operations** | CreateStack, UpdateStack, DeleteStack, DescribeStacks, ListStacks, DescribeStackEvents, DescribeStackResource, DescribeStackResources, GetTemplate, ValidateTemplate, GetTemplateSummary, RollbackStack |
| **Change Sets** | CreateChangeSet, DescribeChangeSet, ExecuteChangeSet, DeleteChangeSet, ListChangeSets |
| **Exports** | ListExports — cross-stack references via `Fn::ImportValue` |
| **Template Formats** | JSON and YAML (including `!Ref`, `!Sub`, `!GetAtt` shorthand tags) |
@@ -470,10 +470,8 @@ subnet = ec2.create_subnet(
| **Conditions** | Fn::Equals, Fn::And, Fn::Or, Fn::Not — conditional resource creation |
| **Rules** | The `Rules` section runs after the parameters resolve and before any resource is touched (CreateStack, UpdateStack, CreateChangeSet): `RuleCondition`, `Assertions` with `AssertDescription`, Fn::And/Or/Not/Equals/If/Contains/EachMemberEquals/EachMemberIn and Ref; Fn::RefAll, Fn::ValueOf and Fn::ValueOfAll read the EC2 store for VPC, subnet and security-group ids |
| **Transforms** | `AWS::Serverless-2016-10-31` (SAM, in the `full` image), `AWS::LanguageExtensions` (`Fn::ForEach` over a literal list, a `CommaDelimitedList` parameter, `Fn::FindInMap` or `Fn::Split`, nested and inside `Properties`; `${Id}` / `&{Id}` in the fragment keys, `${Id}` in `Fn::Sub` and a `Ref` to the identifier; `Fn::Length`, `Fn::ToJsonString`) and the embedded `AWS::Include` transform (`Fn::Transform` with an `s3://` `Location`, JSON or YAML snippets) |
-| **Rollback** | Configurable via `DisableRollback`, CreateStack `OnFailure` (`ROLLBACK`, `DO_NOTHING`, `DELETE`) and CreateChangeSet `OnStackFailure` (`DELETE` for CREATE change sets only); ExecuteChangeSet honours `DisableRollback`. On failure, previously created resources are cleaned up in reverse dependency order; `DELETE` then deletes the stack |
-| **Stack Deletion** | `RetainResources` and `DeletionMode=FORCE_DELETE_STACK` on a `DELETE_FAILED` stack: the resources that failed to delete, and what they depend on, are retained (`DELETE_SKIPPED`) and the stack reaches `DELETE_COMPLETE` |
-| **Templates** | GetTemplate `TemplateStage` (`Original`, the default here, or `Processed`, the template after SAM, `AWS::LanguageExtensions` and `AWS::Include`), `StagesAvailable`, and a change set's template through `ChangeSetName` |
-| **Client Request Tokens** | The `ClientRequestToken` of CreateStack, UpdateStack, DeleteStack, ExecuteChangeSet, ContinueUpdateRollback and CancelUpdateStack is reported on every stack event the operation records |
+| **Rollback** | Configurable via `DisableRollback` — on failure, previously created resources are cleaned up in reverse dependency order; a stack left `CREATE_FAILED` or `UPDATE_FAILED` by `DisableRollback` is rolled back later with RollbackStack (`ROLLBACK_COMPLETE` or `UPDATE_ROLLBACK_COMPLETE`, `RetainExceptOnCreate` honoured) |
+| **Drift Detection** | DetectStackDrift, DescribeStackDriftDetectionStatus, DetectStackResourceDrift, DescribeStackResourceDrifts (status filters, `MaxResults`/`NextToken`), and `DriftInformation` on DescribeStacks, ListStacks and the stack resource calls. Detection completes synchronously and compares the properties the template sets with the service's current record. Property-level drift (`PropertyDifferences`, expected and actual properties) for AWS::SQS::Queue, AWS::SSM::Parameter, AWS::SNS::Topic, AWS::Lambda::Function, AWS::IAM::Role, AWS::DynamoDB::Table, AWS::S3::Bucket (name, versioning), AWS::Logs::LogGroup and AWS::SecretsManager::Secret; stack-level tags count toward `Tags`. Existence only (`IN_SYNC` or `DELETED`) for AWS::Kinesis::Stream, AWS::ECR::Repository, AWS::StepFunctions::StateMachine, AWS::Events::Rule and AWS::SNS::Subscription. Every other type is `NOT_CHECKED` |
| **Async Status** | Stacks deploy asynchronously (`CREATE_IN_PROGRESS` → `CREATE_COMPLETE`) — poll with DescribeStacks |
| **Quotas** | The template and stack quotas of the CloudFormation quotas page are enforced before a stack exists: 51,200 bytes of `TemplateBody`, 1,000,000 bytes behind `TemplateURL`, 500 resources, 200 parameters / outputs / mappings, 200 attributes per mapping, 255-character names, a 1,024-byte description, 4,096-byte parameter values, and a stack name of up to 128 alphanumeric characters and hyphens starting with a letter |
diff --git a/ministack/core/router.py b/ministack/core/router.py
index 0cd3c67b..46652ee7 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -1135,6 +1135,11 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
"SetStackPolicy": "cloudformation",
"GetStackPolicy": "cloudformation",
"SignalResource": "cloudformation",
+ "RollbackStack": "cloudformation",
+ "DetectStackDrift": "cloudformation",
+ "DescribeStackDriftDetectionStatus": "cloudformation",
+ "DetectStackResourceDrift": "cloudformation",
+ "DescribeStackResourceDrifts": "cloudformation",
# EBS Snapshots
# Note: CreateSnapshot, DeleteSnapshot, DescribeSnapshots are intentionally
# omitted here because they conflict with ElastiCache actions of the same
diff --git a/ministack/services/cloudformation/__init__.py b/ministack/services/cloudformation/__init__.py
index 2a1c9a05..e535e9e4 100644
--- a/ministack/services/cloudformation/__init__.py
+++ b/ministack/services/cloudformation/__init__.py
@@ -7,7 +7,9 @@ Supports: CreateStack, UpdateStack, DeleteStack, DescribeStacks, ListStacks,
ListStackResources, GetTemplate, ValidateTemplate, ListExports,
CreateChangeSet, DescribeChangeSet, ExecuteChangeSet,
DeleteChangeSet, ListChangeSets,
- GetTemplateSummary.
+ GetTemplateSummary, RollbackStack, DetectStackDrift,
+ DescribeStackDriftDetectionStatus, DetectStackResourceDrift,
+ DescribeStackResourceDrifts.
Uses Query API (Action=...) with form-encoded body.
"""
diff --git a/ministack/services/cloudformation/drift.py b/ministack/services/cloudformation/drift.py
new file mode 100644
index 00000000..e40bfcb0
--- /dev/null
+++ b/ministack/services/cloudformation/drift.py
@@ -0,0 +1,449 @@
+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT
+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).
+"""
+CloudFormation drift detection: compare a stack resource's expected properties
+(the resolved template properties the stack record keeps) with what the
+owning service's store holds now.
+
+Each supported type has a reader in ``_DRIFT_READERS``: a function that looks
+the resource up by its physical id and returns its current properties in the
+template's shape (``None`` when the record is gone, which is ``DELETED``), plus
+the set of properties it can read. Only properties the template sets
+explicitly and the reader covers are compared, as the drift user guide says
+("CloudFormation only determines drift for property values that are
+explicitly set"). A reader with an empty set is an existence check. A type
+without a reader is ``NOT_CHECKED``.
+"""
+
+import copy
+import json
+import logging
+
+import ministack.services.cloudwatch_logs as _cw_logs
+import ministack.services.dynamodb as _dynamodb
+import ministack.services.ecr as _ecr
+import ministack.services.eventbridge as _eb
+import ministack.services.iam as _iam
+import ministack.services.kinesis as _kinesis
+import ministack.services.lambda_svc as _lambda_svc
+import ministack.services.s3 as _s3
+import ministack.services.secretsmanager as _sm
+import ministack.services.sns as _sns
+import ministack.services.sqs as _sqs
+import ministack.services.ssm as _ssm
+import ministack.services.stepfunctions as _sfn
+
+from .provisioners import _STACK_TAG_PROPERTY, _tag_map
+
+logger = logging.getLogger("cloudformation")
+
+# The stack statuses the drift user guide lists for drift detection.
+DRIFT_DETECTABLE_STATUSES = frozenset({
+ "CREATE_COMPLETE", "UPDATE_COMPLETE", "UPDATE_ROLLBACK_COMPLETE",
+ "UPDATE_ROLLBACK_FAILED",
+})
+
+RESOURCE_DRIFT_STATUSES = ("IN_SYNC", "MODIFIED", "DELETED", "NOT_CHECKED",
+ "UNKNOWN", "UNSUPPORTED")
+
+
+def _json_or(value):
+ """A policy-like attribute a service keeps as a JSON string, parsed; the
+ template writes it as an object."""
+ if isinstance(value, str):
+ try:
+ return json.loads(value)
+ except ValueError:
+ return value
+ return value
+
+
+# ---------------------------------------------------------------------------
+# Readers: physical id + expected properties -> current properties or None
+# ---------------------------------------------------------------------------
+
+def _read_sqs_queue(physical_id, props):
+ queue = _sqs._queues.get(physical_id)
+ if queue is None:
+ return None
+ attrs = queue.get("attributes", {})
+ out = {"QueueName": queue.get("name"), "Tags": queue.get("tags", {}),
+ "FifoQueue": bool(queue.get("is_fifo"))}
+ for key in ("VisibilityTimeout", "MaximumMessageSize", "MessageRetentionPeriod",
+ "DelaySeconds", "ReceiveMessageWaitTimeSeconds",
+ "ContentBasedDeduplication"):
+ if key in attrs:
+ out[key] = attrs[key]
+ for key in ("RedrivePolicy", "RedriveAllowPolicy"):
+ if attrs.get(key):
+ out[key] = _json_or(attrs[key])
+ return out
+
+
+def _read_ssm_parameter(physical_id, props):
+ record = _ssm._parameters.get(physical_id)
+ if record is None:
+ return None
+ out = {
+ "Name": record.get("Name"),
+ "Type": record.get("Type"),
+ "Value": record.get("OriginalValue", record.get("Value")),
+ "Description": record.get("Description", ""),
+ "AllowedPattern": record.get("AllowedPattern", ""),
+ "Tier": record.get("Tier"),
+ "DataType": record.get("DataType"),
+ "Tags": _ssm._tags.get(record.get("ARN") or _ssm._param_arn(physical_id), {}),
+ }
+ return {k: v for k, v in out.items() if v is not None}
+
+
+def _read_sns_topic(physical_id, props):
+ topic = _sns._topics.get(physical_id)
+ if topic is None:
+ return None
+ out = {"TopicName": topic.get("name"), "Tags": topic.get("tags", {})}
+ if "DisplayName" in topic.get("attributes", {}):
+ out["DisplayName"] = topic["attributes"]["DisplayName"]
+ return out
+
+
+def _read_lambda_function(physical_id, props):
+ func = _lambda_svc._functions.get(physical_id)
+ if func is None:
+ return None
+ config = func.get("config", {})
+ out = {"FunctionName": config.get("FunctionName"), "Tags": func.get("tags", {})}
+ for key in ("Runtime", "Handler", "Role", "Timeout", "MemorySize", "Description",
+ "Architectures", "PackageType"):
+ if key in config:
+ out[key] = config[key]
+ variables = (config.get("Environment") or {}).get("Variables")
+ if variables is not None:
+ out["Environment"] = {"Variables": variables}
+ if config.get("EphemeralStorage"):
+ out["EphemeralStorage"] = {"Size": config["EphemeralStorage"].get("Size")}
+ if config.get("TracingConfig"):
+ out["TracingConfig"] = {"Mode": config["TracingConfig"].get("Mode")}
+ return out
+
+
+def _read_iam_role(physical_id, props):
+ role = _iam._roles.get(physical_id)
+ if role is None:
+ return None
+ return {
+ "RoleName": role.get("RoleName"),
+ "Path": role.get("Path", "/"),
+ "Description": role.get("Description", ""),
+ "MaxSessionDuration": role.get("MaxSessionDuration"),
+ "AssumeRolePolicyDocument": _json_or(role.get("AssumeRolePolicyDocument")),
+ "Tags": _tag_map(role.get("Tags")),
+ }
+
+
+def _read_dynamodb_table(physical_id, props):
+ table = _dynamodb._tables.get(physical_id)
+ if table is None:
+ return None
+ billing = (table.get("BillingModeSummary") or {}).get("BillingMode", "PROVISIONED")
+ out = {
+ "TableName": table.get("TableName"),
+ "BillingMode": billing,
+ "KeySchema": table.get("KeySchema", []),
+ "AttributeDefinitions": table.get("AttributeDefinitions", []),
+ "DeletionProtectionEnabled": table.get("DeletionProtectionEnabled", False),
+ "Tags": _tag_map(_dynamodb._tags.get(table.get("TableArn"), [])),
+ }
+ throughput = table.get("ProvisionedThroughput") or {}
+ if billing == "PROVISIONED" and throughput:
+ out["ProvisionedThroughput"] = {
+ k: throughput[k] for k in ("ReadCapacityUnits", "WriteCapacityUnits")
+ if k in throughput
+ }
+ stream = table.get("StreamSpecification") or {}
+ if stream.get("StreamViewType"):
+ out["StreamSpecification"] = {"StreamViewType": stream["StreamViewType"]}
+ return out
+
+
+def _read_s3_bucket(physical_id, props):
+ if physical_id not in _s3._buckets:
+ return None
+ out = {"BucketName": physical_id}
+ status = _s3._bucket_versioning.get(physical_id)
+ if status:
+ out["VersioningConfiguration"] = {"Status": status}
+ return out
+
+
+def _read_log_group(physical_id, props):
+ group = _cw_logs._log_groups.get(physical_id)
+ if group is None:
+ return None
+ out = {"LogGroupName": physical_id, "Tags": group.get("tags", {})}
+ if group.get("retentionInDays") is not None:
+ out["RetentionInDays"] = group["retentionInDays"]
+ if group.get("logGroupClass"):
+ out["LogGroupClass"] = group["logGroupClass"]
+ return out
+
+
+def _read_secret(physical_id, props):
+ secret = _sm._secrets.get(physical_id)
+ if secret is None:
+ return None
+ return {
+ "Name": secret.get("Name"),
+ "Description": secret.get("Description", ""),
+ "Tags": _tag_map(secret.get("Tags")),
+ }
+
+
+def _exists_in(store_getter):
+ """An existence check: the record is looked up by the physical id."""
+ def read(physical_id, props):
+ return {} if physical_id in store_getter() else None
+ return read
+
+
+def _read_events_rule(physical_id, props):
+ key = _eb._rule_key(physical_id, props.get("EventBusName", "default"))
+ return {} if key in _eb._rules else None
+
+
+def _read_sns_subscription(physical_id, props):
+ return {} if physical_id in _sns._sub_arn_to_topic else None
+
+
+# type -> (reader, the properties it reads). An empty set is an existence check.
+_DRIFT_READERS = {
+ "AWS::SQS::Queue": (_read_sqs_queue, frozenset({
+ "QueueName", "VisibilityTimeout", "MaximumMessageSize", "MessageRetentionPeriod",
+ "DelaySeconds", "ReceiveMessageWaitTimeSeconds", "ContentBasedDeduplication",
+ "FifoQueue", "RedrivePolicy", "RedriveAllowPolicy", "Tags"})),
+ "AWS::SSM::Parameter": (_read_ssm_parameter, frozenset({
+ "Name", "Type", "Value", "Description", "AllowedPattern", "Tier", "DataType",
+ "Tags"})),
+ "AWS::SNS::Topic": (_read_sns_topic, frozenset({"TopicName", "DisplayName", "Tags"})),
+ "AWS::Lambda::Function": (_read_lambda_function, frozenset({
+ "FunctionName", "Runtime", "Handler", "Role", "Timeout", "MemorySize",
+ "Description", "Architectures", "PackageType", "Environment",
+ "EphemeralStorage", "TracingConfig", "Tags"})),
+ "AWS::IAM::Role": (_read_iam_role, frozenset({
+ "RoleName", "Path", "Description", "MaxSessionDuration",
+ "AssumeRolePolicyDocument", "Tags"})),
+ "AWS::DynamoDB::Table": (_read_dynamodb_table, frozenset({
+ "TableName", "BillingMode", "KeySchema", "AttributeDefinitions",
+ "ProvisionedThroughput", "StreamSpecification", "DeletionProtectionEnabled",
+ "Tags"})),
+ "AWS::S3::Bucket": (_read_s3_bucket, frozenset({"BucketName", "VersioningConfiguration"})),
+ "AWS::Logs::LogGroup": (_read_log_group, frozenset({
+ "LogGroupName", "RetentionInDays", "LogGroupClass", "Tags"})),
+ "AWS::SecretsManager::Secret": (_read_secret, frozenset({"Name", "Description", "Tags"})),
+ "AWS::Kinesis::Stream": (_exists_in(lambda: _kinesis._streams), frozenset()),
+ "AWS::ECR::Repository": (_exists_in(lambda: _ecr._repositories), frozenset()),
+ "AWS::StepFunctions::StateMachine": (_exists_in(lambda: _sfn._state_machines), frozenset()),
+ "AWS::Events::Rule": (_read_events_rule, frozenset()),
+ "AWS::SNS::Subscription": (_read_sns_subscription, frozenset()),
+}
+
+
+def supports_drift(resource_type: str) -> bool:
+ return resource_type in _DRIFT_READERS
+
+
+# ---------------------------------------------------------------------------
+# Comparison
+# ---------------------------------------------------------------------------
+
+def _coerce_like(expected, actual):
+ """``actual`` in the JSON types of ``expected``: services keep numbers and
+ booleans as strings (SQS attributes), templates write them either way."""
+ if isinstance(expected, dict) and isinstance(actual, dict):
+ return {k: _coerce_like(expected.get(k), v) for k, v in actual.items()}
+ if isinstance(expected, list) and isinstance(actual, list):
+ sample = expected[0] if expected else None
+ return [_coerce_like(sample, v) for v in actual]
+ if isinstance(expected, bool) and isinstance(actual, str):
+ if actual.lower() in ("true", "false"):
+ return actual.lower() == "true"
+ elif isinstance(expected, int) and not isinstance(expected, bool) and isinstance(actual, str):
+ try:
+ return int(actual)
+ except ValueError:
+ return actual
+ elif isinstance(expected, str) and isinstance(actual, (int, float)) \
+ and not isinstance(actual, bool):
+ return str(actual)
+ elif isinstance(expected, str) and isinstance(actual, bool):
+ return str(actual).lower()
+ return actual
+
+
+def _scalar_text(value) -> str:
+ if value is None:
+ return "null"
+ if isinstance(value, bool):
+ return str(value).lower()
+ if isinstance(value, (dict, list)):
+ return json.dumps(value, sort_keys=True, default=str)
+ return str(value)
+
+
+def _same(expected, actual) -> bool:
+ if isinstance(expected, dict) and isinstance(actual, dict):
+ return (expected.keys() == actual.keys()
+ and all(_same(expected[k], actual[k]) for k in expected))
+ if isinstance(expected, list) and isinstance(actual, list):
+ return len(expected) == len(actual) and not _list_differences(expected, actual, "")
+ if isinstance(expected, (dict, list)) or isinstance(actual, (dict, list)):
+ return False
+ return _scalar_text(expected) == _scalar_text(actual)
+
+
+def _list_differences(expected: list, actual: list, path: str) -> list:
+ """Arrays compare as sets of elements: an element found on both sides
+ matches wherever it sits. Of the rest, elements with the same ``Key`` (tags)
+ or at the same position are compared in depth; what is left on the actual
+ side was added, what is left on the expected side was removed."""
+ diffs = []
+ unmatched_actual = list(range(len(actual)))
+ leftover_expected = []
+ for i, exp in enumerate(expected):
+ hit = next((j for j in unmatched_actual if _same(exp, actual[j])), None)
+ if hit is None:
+ leftover_expected.append(i)
+ else:
+ unmatched_actual.remove(hit)
+ for i in leftover_expected:
+ exp = expected[i]
+ partner = None
+ if isinstance(exp, dict) and "Key" in exp:
+ partner = next((j for j in unmatched_actual
+ if isinstance(actual[j], dict)
+ and actual[j].get("Key") == exp["Key"]), None)
+ elif i in unmatched_actual:
+ partner = i
+ if partner is None:
+ diffs.append(_difference(f"{path}/{i}", exp, None, "REMOVE"))
+ continue
+ unmatched_actual.remove(partner)
+ diffs.extend(_differences(exp, actual[partner], f"{path}/{i}"))
+ for j in unmatched_actual:
+ diffs.append(_difference(f"{path}/{j}", None, actual[j], "ADD"))
+ return diffs
+
+
+def _difference(path, expected, actual, kind) -> dict:
+ return {
+ "PropertyPath": path,
+ "ExpectedValue": _scalar_text(expected),
+ "ActualValue": _scalar_text(actual),
+ "DifferenceType": kind,
+ }
+
+
+def _differences(expected, actual, path: str) -> list:
+ """``PropertyDifference`` entries, with the JSON-pointer paths the API
+ reference's example uses (``/RedrivePolicy/maxReceiveCount``)."""
+ if isinstance(expected, dict) and isinstance(actual, dict):
+ diffs = []
+ for key, exp in expected.items():
+ sub = f"{path}/{key}"
+ if key not in actual:
+ diffs.append(_difference(sub, exp, None, "REMOVE"))
+ else:
+ diffs.extend(_differences(exp, actual[key], sub))
+ for key in actual.keys() - expected.keys():
+ diffs.append(_difference(f"{path}/{key}", None, actual[key], "ADD"))
+ return diffs
+ if isinstance(expected, list) and isinstance(actual, list):
+ return _list_differences(expected, actual, path)
+ if _same(expected, actual):
+ return []
+ return [_difference(path, expected, actual, "NOT_EQUAL")]
+
+
+def _tags_in_shape(tags: dict, like):
+ """A ``{key: value}`` tag map in the shape the template uses: a map, or a
+ ``[{Key, Value}]`` list in the order of ``like``, extra keys last."""
+ if isinstance(like, dict):
+ return dict(tags)
+ order = [t.get("Key") for t in (like or []) if isinstance(t, dict)]
+ keys = [k for k in order if k in tags] + sorted(k for k in tags if k not in order)
+ return [{"Key": k, "Value": tags[k]} for k in keys]
+
+
+def _expected_properties(resource_type: str, props: dict, supported, stack_tags) -> dict:
+ """The properties drift detection checks: the explicitly set ones the
+ reader covers. The tag property also carries the stack-level tags
+ ("CloudFormation also detects drift on stack-level tags"); the
+ ``aws:``-prefixed ones are the service's, not the template's."""
+ expected = {k: copy.deepcopy(v) for k, v in (props or {}).items() if k in supported}
+ spec = _STACK_TAG_PROPERTY.get(resource_type)
+ if spec and spec[0] in supported:
+ prop = spec[0]
+ own = props.get(prop)
+ merged = {**_tag_map(stack_tags), **_tag_map(own)}
+ merged = {k: v for k, v in merged.items() if not k.startswith("aws:")}
+ if merged:
+ like = own if own is not None else ({} if spec[1] == "map" else [])
+ expected[prop] = _tags_in_shape(merged, like)
+ else:
+ expected.pop(prop, None)
+ return expected
+
+
+def detect_resource_drift(stack: dict, logical_id: str, record: dict, timestamp: str) -> dict:
+ """The ``StackResourceDrift`` of one resource that has a reader."""
+ rtype = record.get("ResourceType", "")
+ physical_id = record.get("PhysicalResourceId", "")
+ reader, supported = _DRIFT_READERS[rtype]
+ drift = {
+ "StackId": stack.get("StackId", ""),
+ "LogicalResourceId": logical_id,
+ "PhysicalResourceId": physical_id,
+ "ResourceType": rtype,
+ "Timestamp": timestamp,
+ }
+ props = record.get("Properties") or {}
+ try:
+ current = reader(physical_id, props)
+ except Exception as exc: # the resource could not be read: UNKNOWN, as documented
+ logger.warning("Drift detection of %s (%s) failed: %s", logical_id, rtype, exc)
+ drift["StackResourceDriftStatus"] = "UNKNOWN"
+ drift["DriftStatusReason"] = f"Drift detection failed: {exc}"
+ return drift
+ if current is None:
+ drift["StackResourceDriftStatus"] = "DELETED"
+ return drift
+ expected = _expected_properties(rtype, props, supported, stack.get("Tags") or [])
+ actual = {}
+ for key, exp in expected.items():
+ if key not in current:
+ continue
+ value = current[key]
+ spec = _STACK_TAG_PROPERTY.get(rtype)
+ if spec and key == spec[0]:
+ tags = {k: v for k, v in _tag_map(value).items() if not k.startswith("aws:")}
+ value = _tags_in_shape(tags, exp)
+ actual[key] = _coerce_like(exp, copy.deepcopy(value))
+ differences = _differences(expected, actual, "")
+ drift["ExpectedProperties"] = json.dumps(expected, sort_keys=True, default=str)
+ drift["ActualProperties"] = json.dumps(actual, sort_keys=True, default=str)
+ if differences:
+ drift["StackResourceDriftStatus"] = "MODIFIED"
+ drift["PropertyDifferences"] = differences
+ else:
+ drift["StackResourceDriftStatus"] = "IN_SYNC"
+ return drift
+
+
+def record_resource_drift(record: dict, drift: dict) -> None:
+ """Keep the result on the resource record: ``DescribeStackResourceDrifts``
+ lists it and the resource's ``DriftInformation`` reports it."""
+ record["_drift"] = drift
+ record["DriftInformation"] = {
+ "StackResourceDriftStatus": drift["StackResourceDriftStatus"],
+ "LastCheckTimestamp": drift["Timestamp"],
+ }
diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.py
index 70c28053..bf3a9f8e 100644
--- a/ministack/services/cloudformation/handlers.py
+++ b/ministack/services/cloudformation/handlers.py
@@ -9,6 +9,7 @@ import json
import logging
from ministack.core.responses import get_account_id, get_region, new_uuid, now_iso
+from ministack.services.cloudformation import drift as _drift
from ministack.services.cloudformation import wait_conditions as _wc
from .changesets import (
@@ -55,6 +56,7 @@ from .stacks import (
_create_then_delete_on_failure,
_delete_stack_async,
_deploy_stack_async,
+ _roll_back_operation,
_stack_region_context,
)
@@ -494,6 +496,7 @@ def _describe_stacks(params):
f"<Parameters>{params_xml}</Parameters>"
f"<Outputs>{outputs_xml}</Outputs>"
f"<Tags>{tags_xml}</Tags>"
+ f"{_stack_drift_information_xml(s)}"
"</member>"
)
@@ -531,6 +534,7 @@ def _list_stacks(params):
entry += f"<StackStatusReason>{_esc(s['StackStatusReason'])}</StackStatusReason>"
if s.get("DeletionTime"):
entry += f"<DeletionTime>{s['DeletionTime']}</DeletionTime>"
+ entry += _stack_drift_information_xml(s)
entry += "</member>"
summaries += entry
@@ -651,6 +655,7 @@ def _describe_stack_resource(params):
f"<StackName>{_esc(stack_name)}</StackName>"
f"<StackId>{_esc(stack['StackId'])}</StackId>"
f"{_resource_metadata_xml(stack, logical_id)}"
+ f"{_resource_drift_information_xml(res)}"
)
return _xml(200, "DescribeStackResourceResponse",
@@ -693,6 +698,7 @@ def _describe_stack_resources(params):
f"<Timestamp>{res.get('Timestamp', '')}</Timestamp>"
f"<StackName>{_esc(stack_name)}</StackName>"
f"<StackId>{_esc(stack['StackId'])}</StackId>"
+ f"{_resource_drift_information_xml(res)}"
"</member>"
)
@@ -727,6 +733,7 @@ def _list_stack_resources(params):
f"<ResourceType>{_esc(res.get('ResourceType', ''))}</ResourceType>"
f"<ResourceStatus>{res.get('ResourceStatus', '')}</ResourceStatus>"
f"<LastUpdatedTimestamp>{res.get('Timestamp', '')}</LastUpdatedTimestamp>"
+ f"{_resource_drift_information_xml(res)}"
"</member>"
)
@@ -1375,6 +1382,286 @@ def _continue_update_rollback(params):
"<ContinueUpdateRollbackResult></ContinueUpdateRollbackResult>")
+# --- RollbackStack ---
+
+def _rollback_stack(params):
+ """RollbackStack: roll a stack that failed with ``DisableRollback`` back
+ to its last known stable state. ``CREATE_FAILED`` has none, so what the
+ create made is deleted and the stack ends ``ROLLBACK_COMPLETE``;
+ ``UPDATE_FAILED`` goes back to the stack as it was before the update and
+ ends ``UPDATE_ROLLBACK_COMPLETE`` (API_RollbackStack). ``RoleARN`` and
+ ``ClientRequestToken`` are accepted and not used: the emulator assumes no
+ role, and a repeated token is not refused."""
+ stack_name = _p(params, "StackName")
+ if not stack_name:
+ return _error("ValidationError", "StackName is required")
+ stack = _resolve_stack(stack_name)
+ if not stack or stack.get("StackStatus") == "DELETE_COMPLETE":
+ return _error("ValidationError", f"Stack [{stack_name}] does not exist")
+ stack_name = stack.get("StackName", stack_name)
+ status = stack.get("StackStatus", "")
+ if status not in ("CREATE_FAILED", "UPDATE_FAILED"):
+ return _error("ValidationError",
+ "RollbackStack cannot be called from current stack status")
+ operation = stack.get("_failed_operation") or {
+ # A record without the failed operation (saved before RollbackStack
+ # existed): nothing is known to undo, so the stack keeps what it has
+ # and only the status settles.
+ "is_update": status == "UPDATE_FAILED",
+ "previous_stack": {
+ key: copy.deepcopy(stack.get(key)) for key in (
+ "_resources", "_template", "_template_body", "_resolved_params",
+ "Parameters", "Tags", "Outputs") if key in stack
+ } if status == "UPDATE_FAILED" else None,
+ "template": stack.get("_template") or {},
+ "param_values": stack.get("_resolved_params") or {},
+ }
+ if "RetainExceptOnCreate" in params:
+ operation = {**operation, "retain_except_on_create":
+ _p(params, "RetainExceptOnCreate", "false").lower() == "true"}
+ stack_id = stack["StackId"]
+ stack["StackStatus"] = ("UPDATE_ROLLBACK_IN_PROGRESS" if operation.get("is_update")
+ else "ROLLBACK_IN_PROGRESS")
+ _create_stack_task_in_region(
+ _roll_back_operation(stack_name, stack_id, stack, operation,
+ reason_override="User Initiated"),
+ stack,
+ stack_id,
+ )
+ return _xml(200, "RollbackStackResponse",
+ f"<RollbackStackResult><StackId>{_esc(stack_id)}</StackId></RollbackStackResult>")
+
+
+# --- Drift detection ---
+
+# Detection records kept per stack; the API says the number of retained
+# results "may vary".
+_DRIFT_DETECTIONS_KEPT = 10
+
+
+def _stack_drift_information_xml(stack):
+ """``DriftInformation`` of a stack: ``NOT_CHECKED`` until a detection ran."""
+ info = stack.get("DriftInformation") or {}
+ status = info.get("StackDriftStatus", "NOT_CHECKED")
+ checked = info.get("LastCheckTimestamp")
+ ts = f"<LastCheckTimestamp>{checked}</LastCheckTimestamp>" if checked else ""
+ return (f"<DriftInformation><StackDriftStatus>{status}</StackDriftStatus>{ts}"
+ "</DriftInformation>")
+
+
+def _resource_drift_information_xml(res):
+ """``DriftInformation`` of a stack resource: ``NOT_CHECKED`` until its
+ type was checked (and for good for a type without drift support)."""
+ info = res.get("DriftInformation") or {}
+ status = info.get("StackResourceDriftStatus", "NOT_CHECKED")
+ checked = info.get("LastCheckTimestamp")
+ ts = f"<LastCheckTimestamp>{checked}</LastCheckTimestamp>" if checked else ""
+ return (f"<DriftInformation><StackResourceDriftStatus>{status}"
+ f"</StackResourceDriftStatus>{ts}</DriftInformation>")
+
+
+def _stack_resource_drift_xml(drift):
+ diffs = "".join(
+ "<member>"
+ f"<PropertyPath>{_esc(d['PropertyPath'])}</PropertyPath>"
+ f"<ExpectedValue>{_esc(d['ExpectedValue'])}</ExpectedValue>"
+ f"<ActualValue>{_esc(d['ActualValue'])}</ActualValue>"
+ f"<DifferenceType>{d['DifferenceType']}</DifferenceType>"
+ "</member>"
+ for d in drift.get("PropertyDifferences", []))
+ out = (
+ f"<StackId>{_esc(drift['StackId'])}</StackId>"
+ f"<LogicalResourceId>{_esc(drift['LogicalResourceId'])}</LogicalResourceId>"
+ f"<PhysicalResourceId>{_esc(drift.get('PhysicalResourceId', ''))}</PhysicalResourceId>"
+ f"<ResourceType>{_esc(drift['ResourceType'])}</ResourceType>"
+ f"<StackResourceDriftStatus>{drift['StackResourceDriftStatus']}</StackResourceDriftStatus>"
+ f"<Timestamp>{drift['Timestamp']}</Timestamp>"
+ )
+ for key in ("ExpectedProperties", "ActualProperties", "DriftStatusReason"):
+ if key in drift:
+ out += f"<{key}>{_esc(drift[key])}</{key}>"
+ if diffs:
+ out += f"<PropertyDifferences>{diffs}</PropertyDifferences>"
+ return out
+
+
+def _drift_target(stack_name):
+ """The stack a drift call names, or the error: it has to exist and be in
+ one of the statuses the drift user guide lists."""
+ if not stack_name:
+ return None, _error("ValidationError", "StackName is required")
+ stack = _resolve_stack(stack_name)
+ if not stack or stack.get("StackStatus") == "DELETE_COMPLETE":
+ return None, _error("ValidationError", f"Stack [{stack_name}] does not exist")
+ status = stack.get("StackStatus", "")
+ if status not in _drift.DRIFT_DETECTABLE_STATUSES:
+ return None, _error(
+ "ValidationError",
+ f"Stack [{stack.get('StackName', stack_name)}] is in {status} state; drift "
+ "detection is available in CREATE_COMPLETE, UPDATE_COMPLETE, "
+ "UPDATE_ROLLBACK_COMPLETE and UPDATE_ROLLBACK_FAILED")
+ return stack, None
+
+
+def _detect_stack_drift(params):
+ """DetectStackDrift: check every resource (or the ``LogicalResourceIds``)
+ whose type has a reader against its service store, synchronously; the
+ detection is ``DETECTION_COMPLETE`` by the time the call returns."""
+ stack, err = _drift_target(_p(params, "StackName"))
+ if err:
+ return err
+ resources = stack.get("_resources", {})
+ wanted = _extract_string_members(params, "LogicalResourceIds")
+ unknown = sorted(set(wanted) - set(resources))
+ if unknown:
+ return _error("ValidationError",
+ f"Resource(s) [{', '.join(unknown)}] do not exist in stack "
+ f"[{stack['StackName']}]")
+ timestamp = now_iso()
+ detection_id = new_uuid()
+ drifted = 0
+ failed = []
+ for logical_id, record in resources.items():
+ if wanted and logical_id not in wanted:
+ continue
+ if not _drift.supports_drift(record.get("ResourceType", "")):
+ continue
+ drift = _drift.detect_resource_drift(stack, logical_id, record, timestamp)
+ _drift.record_resource_drift(record, drift)
+ if drift["StackResourceDriftStatus"] in ("MODIFIED", "DELETED"):
+ drifted += 1
+ elif drift["StackResourceDriftStatus"] == "UNKNOWN":
+ failed.append(logical_id)
+ if drifted:
+ stack_status = "DRIFTED"
+ elif failed:
+ stack_status = "UNKNOWN"
+ else:
+ stack_status = "IN_SYNC"
+ detection = {
+ "StackId": stack["StackId"],
+ "StackDriftDetectionId": detection_id,
+ "StackDriftStatus": stack_status,
+ "DetectionStatus": "DETECTION_FAILED" if failed else "DETECTION_COMPLETE",
+ "Timestamp": timestamp,
+ }
+ if failed:
+ detection["DetectionStatusReason"] = (
+ f"Failed to detect drift on resources [{', '.join(sorted(failed))}]")
+ else:
+ detection["DriftedStackResourceCount"] = drifted
+ stack["DriftInformation"] = {"StackDriftStatus": stack_status,
+ "LastCheckTimestamp": timestamp}
+ detections = stack.setdefault("_drift_detections", {})
+ detections[detection_id] = detection
+ while len(detections) > _DRIFT_DETECTIONS_KEPT:
+ detections.pop(next(iter(detections)))
+ return _xml(200, "DetectStackDriftResponse",
+ "<DetectStackDriftResult>"
+ f"<StackDriftDetectionId>{detection_id}</StackDriftDetectionId>"
+ "</DetectStackDriftResult>")
+
+
+def _describe_stack_drift_detection_status(params):
+ from ministack.services.cloudformation import _stacks
+ detection_id = _p(params, "StackDriftDetectionId")
+ if not detection_id:
+ return _error("ValidationError", "StackDriftDetectionId is required")
+ detection = None
+ for stack in _stacks.values():
+ detection = (stack.get("_drift_detections") or {}).get(detection_id)
+ if detection:
+ break
+ if not detection:
+ return _error("ValidationError",
+ f"Drift detection with id [{detection_id}] does not exist")
+ body = (
+ f"<StackId>{_esc(detection['StackId'])}</StackId>"
+ f"<StackDriftDetectionId>{detection_id}</StackDriftDetectionId>"
+ f"<StackDriftStatus>{detection['StackDriftStatus']}</StackDriftStatus>"
+ f"<DetectionStatus>{detection['DetectionStatus']}</DetectionStatus>"
+ f"<Timestamp>{detection['Timestamp']}</Timestamp>"
+ )
+ if detection.get("DetectionStatusReason"):
+ body += (f"<DetectionStatusReason>{_esc(detection['DetectionStatusReason'])}"
+ "</DetectionStatusReason>")
+ if "DriftedStackResourceCount" in detection:
+ body += (f"<DriftedStackResourceCount>{detection['DriftedStackResourceCount']}"
+ "</DriftedStackResourceCount>")
+ return _xml(200, "DescribeStackDriftDetectionStatusResponse",
+ f"<DescribeStackDriftDetectionStatusResult>{body}"
+ "</DescribeStackDriftDetectionStatusResult>")
+
+
+def _detect_stack_resource_drift(params):
+ stack, err = _drift_target(_p(params, "StackName"))
+ if err:
+ return err
+ logical_id = _p(params, "LogicalResourceId")
+ if not logical_id:
+ return _error("ValidationError", "LogicalResourceId is required")
+ record = stack.get("_resources", {}).get(logical_id)
+ if not record:
+ return _error("ValidationError",
+ f"Resource [{logical_id}] does not exist in stack [{stack['StackName']}]")
+ rtype = record.get("ResourceType", "")
+ if not _drift.supports_drift(rtype):
+ # "Resources that don't currently support drift detection can't be checked."
+ return _error("ValidationError",
+ f"Drift detection is not supported for resource type [{rtype}]")
+ timestamp = now_iso()
+ drift = _drift.detect_resource_drift(stack, logical_id, record, timestamp)
+ _drift.record_resource_drift(record, drift)
+ # The stack's LastCheckTimestamp covers a check of any of its resources.
+ info = stack.setdefault("DriftInformation", {"StackDriftStatus": "NOT_CHECKED"})
+ info["LastCheckTimestamp"] = timestamp
+ return _xml(200, "DetectStackResourceDriftResponse",
+ "<DetectStackResourceDriftResult><StackResourceDrift>"
+ f"{_stack_resource_drift_xml(drift)}"
+ "</StackResourceDrift></DetectStackResourceDriftResult>")
+
+
+def _describe_stack_resource_drifts(params):
+ stack_name = _p(params, "StackName")
+ if not stack_name:
+ return _error("ValidationError", "StackName is required")
+ stack = _resolve_stack(stack_name)
+ if not stack or stack.get("StackStatus") == "DELETE_COMPLETE":
+ return _error("ValidationError", f"Stack [{stack_name}] does not exist")
+ filters = _extract_string_members(params, "StackResourceDriftStatusFilters")
+ bad = [f for f in filters if f not in _drift.RESOURCE_DRIFT_STATUSES]
+ if bad:
+ return _error(
+ "ValidationError",
+ f"1 validation error detected: Value '[{', '.join(filters)}]' at "
+ "'stackResourceDriftStatusFilters' failed to satisfy constraint: Member "
+ "must satisfy enum value set: [" + ", ".join(_drift.RESOURCE_DRIFT_STATUSES) + "]")
+ page_size = 100
+ max_results = _p(params, "MaxResults")
+ if max_results:
+ if not max_results.isdigit() or not 1 <= int(max_results) <= 100:
+ return _error(
+ "ValidationError",
+ f"1 validation error detected: Value '{max_results}' at 'maxResults' "
+ "failed to satisfy constraint: Member must have value between 1 and 100")
+ page_size = int(max_results)
+ # Only the resources that were checked are listed (API reference).
+ drifts = [
+ res["_drift"] for res in stack.get("_resources", {}).values()
+ if res.get("_drift")
+ and (not filters or res["_drift"]["StackResourceDriftStatus"] in filters)
+ ]
+ drifts, next_token_xml, err = _page(drifts, params, "DescribeStackResourceDrifts",
+ page_size)
+ if err:
+ return err
+ members = "".join(f"<member>{_stack_resource_drift_xml(d)}</member>" for d in drifts)
+ return _xml(200, "DescribeStackResourceDriftsResponse",
+ "<DescribeStackResourceDriftsResult>"
+ f"<StackResourceDrifts>{members}</StackResourceDrifts>"
+ f"{next_token_xml}</DescribeStackResourceDriftsResult>")
+
+
# --- SignalResource ---
def _signal_resource(params):
@@ -1439,5 +1726,10 @@ _ACTION_HANDLERS = {
"GetStackPolicy": _get_stack_policy,
"CancelUpdateStack": _cancel_update_stack,
"ContinueUpdateRollback": _continue_update_rollback,
+ "RollbackStack": _rollback_stack,
"SignalResource": _signal_resource,
+ "DetectStackDrift": _detect_stack_drift,
+ "DescribeStackDriftDetectionStatus": _describe_stack_drift_detection_status,
+ "DetectStackResourceDrift": _detect_stack_resource_drift,
+ "DescribeStackResourceDrifts": _describe_stack_resource_drifts,
}
diff --git a/ministack/services/cloudformation/helpers.py b/ministack/services/cloudformation/helpers.py
index b5c3682d..3708c6e0 100644
--- a/ministack/services/cloudformation/helpers.py
+++ b/ministack/services/cloudformation/helpers.py
@@ -303,12 +303,13 @@ def _extract_string_members(params, prefix):
PAGE_SIZE = 100
-def _page(items, params, action):
+def _page(items, params, action, page_size=PAGE_SIZE):
"""Cut ``items`` down to the page a request asks for.
Real CloudFormation pages ``ListExports`` at 100 values and the other
list and describe actions at 1 MB of output; here every one of them pages
- at 100 items. The token is ``<Action>:<offset of the next page>``, so a
+ at 100 items, or at ``page_size`` for an action with a ``MaxResults``
+ parameter. The token is ``<Action>:<offset of the next page>``, so a
token of one action is refused by another. Returns
``(page, next_token_xml, error)`` — ``next_token_xml`` is empty on the
last page and ``error`` is the response for a token the service did not
@@ -325,8 +326,8 @@ def _page(items, params, action):
if tagged != action or not offset.isdigit():
return [], "", _error("ValidationError", "Invalid NextToken")
start = int(offset)
- page = items[start:start + PAGE_SIZE]
+ page = items[start:start + page_size]
next_token_xml = ""
- if start + PAGE_SIZE < len(items):
- next_token_xml = f"<NextToken>{action}:{start + PAGE_SIZE}</NextToken>"
+ if start + page_size < len(items):
+ next_token_xml = f"<NextToken>{action}:{start + page_size}</NextToken>"
return page, next_token_xml, None
diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.py
index ac580ff8..c9cb87de 100644
--- a/ministack/services/cloudformation/stacks.py
+++ b/ministack/services/cloudformation/stacks.py
@@ -319,6 +319,210 @@ async def _continue_update_rollback_async(stack_name: str, stack_id: str,
"UPDATE_ROLLBACK_COMPLETE", physical_id=stack_id)
+def _failed_operation(is_update, previous_stack, created, failed_update,
+ failed_logical_id, replaced_ids, cancelled, template,
+ param_values, retain_except_on_create, stack_tags,
+ previous_tags) -> dict:
+ """What the rollback of a failed operation needs, kept on the stack record
+ of a ``*_FAILED`` stack (``DisableRollback``) until ``RollbackStack`` runs
+ it. Lists only, so the record survives the JSON persistence round trip."""
+ return {
+ "is_update": bool(is_update),
+ "previous_stack": previous_stack,
+ "created": list(created),
+ "failed_update": list(failed_update) if failed_update is not None else None,
+ "failed_logical_id": failed_logical_id,
+ "replaced_ids": list(replaced_ids),
+ "cancelled": bool(cancelled),
+ "template": template,
+ "param_values": param_values,
+ "retain_except_on_create": bool(retain_except_on_create),
+ "stack_tags": list(stack_tags or []),
+ "previous_tags": list(previous_tags or []),
+ }
+
+
+async def _roll_back_operation(stack_name: str, stack_id: str, stack: dict,
+ operation: dict, reason_override: str = ""):
+ """Roll a failed create or update back: in-place changes are sent back to
+ their previous properties, what the operation created is deleted (subject
+ to ``DeletionPolicy`` and ``RetainExceptOnCreate``), and an update restores
+ the previous template, parameters, tags and outputs. Runs right after the
+ failure, or later from ``RollbackStack`` for a ``*_FAILED`` stack."""
+ is_update = operation.get("is_update", False)
+ previous_stack = operation.get("previous_stack")
+ created_in_this_run = operation.get("created", [])
+ failed_update = operation.get("failed_update")
+ failed_logical_id = operation.get("failed_logical_id")
+ replaced_ids = set(operation.get("replaced_ids", []))
+ cancelled = operation.get("cancelled", False)
+ template = operation.get("template") or {}
+ param_values = operation.get("param_values") or {}
+ retain_except_on_create = operation.get("retain_except_on_create", False)
+ stack_tags = operation.get("stack_tags") or []
+ previous_tags = operation.get("previous_tags") or []
+ mappings = template.get("Mappings", {})
+ conditions = _evaluate_conditions(template, param_values)
+ resources_defs = template.get("Resources", {})
+ provisioned_resources = stack.setdefault("_resources", {})
+ stack.pop("_failed_operation", None)
+
+ # Rollback: delete resources created in this run in reverse order
+ stack["StackStatus"] = "ROLLBACK_IN_PROGRESS" if not is_update else "UPDATE_ROLLBACK_IN_PROGRESS"
+ if reason_override:
+ rollback_reason = reason_override
+ elif cancelled:
+ rollback_reason = "User Initiated"
+ elif is_update and failed_logical_id:
+ verb = "update" if failed_update is not None else "create"
+ rollback_reason = (f"The following resource(s) failed to {verb}: "
+ f"[{failed_logical_id}]. ")
+ else:
+ rollback_reason = "Rollback requested"
+ _add_event(stack_id, stack_name, stack_name,
+ "AWS::CloudFormation::Stack", stack["StackStatus"],
+ rollback_reason, stack_id)
+
+ rollback_failed_records = {}
+ previous_resources = (
+ previous_stack.get("_resources", {})
+ if is_update and previous_stack else {}
+ )
+
+ async def revert(logical_id, rtype, pid, applied, previous, attrs):
+ # A failed revert is kept for ContinueUpdateRollback.
+ try:
+ await _revert_update(stack_id, stack_name, logical_id, rtype,
+ pid, applied, previous, attrs,
+ previous_resources.get(logical_id))
+ except Exception:
+ rollback_failed_records[logical_id] = {
+ "PhysicalResourceId": pid, "ResourceType": rtype,
+ "RevertFrom": applied, "RevertTo": previous,
+ "Attributes": attrs,
+ }
+
+ # In-place changes go back first; what the update created is deleted in cleanup.
+ to_delete = []
+ for logical_id in created_in_this_run:
+ res = provisioned_resources.get(logical_id, {})
+ pid = res.get("PhysicalResourceId", "")
+ prev = previous_resources.get(logical_id)
+ if (prev is None or prev.get("PhysicalResourceId") != pid
+ or logical_id in replaced_ids):
+ to_delete.append(logical_id)
+ continue
+ # Pre-existing and same identity: sent back with the tags each side was called with.
+ rtype = res.get("ResourceType", "")
+ applied = _with_stack_tags(rtype, res.get("Properties", {}), stack_tags,
+ stack_name, stack_id, logical_id)
+ previous = _with_stack_tags(rtype, prev.get("Properties", {}),
+ previous_tags, stack_name, stack_id,
+ logical_id)
+ if applied != previous:
+ await revert(logical_id, rtype, pid, applied, previous,
+ res.get("Attributes", {}))
+ if failed_update is not None:
+ logical_id, rtype, pid, applied, previous, attrs = failed_update
+ if (applied is not None and applied != previous
+ and _sends_back_failed_update(rtype)):
+ await revert(logical_id, rtype, pid, applied, previous, attrs)
+ else:
+ _add_event(stack_id, stack_name, logical_id, rtype,
+ "UPDATE_COMPLETE", physical_id=pid)
+ _mark_rolled_back(previous_resources.get(logical_id))
+ # "rolled back to its previous working state ... still deleting any new
+ # resources" (view-stack-events): a cleanup delete failure does not fail it.
+ cleanup_phase = bool(is_update and previous_stack
+ and not rollback_failed_records)
+ if cleanup_phase:
+ stack["StackStatus"] = "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS"
+ _add_event(stack_id, stack_name, stack_name,
+ "AWS::CloudFormation::Stack", stack["StackStatus"],
+ physical_id=stack_id)
+ for logical_id in reversed(to_delete):
+ res = provisioned_resources.get(logical_id, {})
+ rtype = res.get("ResourceType", "")
+ pid = res.get("PhysicalResourceId", "")
+ res_props = res.get("Properties", {})
+ policy = _resource_policy(
+ resources_defs.get(logical_id), "DeletionPolicy",
+ provisioned_resources, param_values, conditions, mappings,
+ stack_name, stack_id)
+ if policy == "Retain" and not retain_except_on_create:
+ # ``Retain`` survives even the rollback of the operation
+ # that created it; ``RetainExceptOnCreate`` and the API
+ # parameter of that name are exactly the exception.
+ _add_event(stack_id, stack_name, logical_id, rtype,
+ "DELETE_SKIPPED", physical_id=pid)
+ provisioned_resources.pop(logical_id, None)
+ continue
+ _add_event(stack_id, stack_name, logical_id, rtype,
+ "DELETE_IN_PROGRESS", physical_id=pid)
+ try:
+ if _is_custom_resource(rtype):
+ await run_reentrant(
+ _delete_resource, rtype, pid, res_props,
+ stack_name, logical_id
+ )
+ else:
+ _delete_resource(rtype, pid, res_props, stack_name, logical_id)
+ _add_event(stack_id, stack_name, logical_id, rtype,
+ "DELETE_COMPLETE", physical_id=pid)
+ except Exception as del_exc:
+ logger.error("Rollback delete of %s failed: %s",
+ logical_id, del_exc)
+ _add_event(stack_id, stack_name, logical_id, rtype,
+ "DELETE_FAILED", str(del_exc), pid)
+ if cleanup_phase:
+ provisioned_resources.pop(logical_id, None)
+ continue
+ rollback_failed_records[logical_id] = {
+ "PhysicalResourceId": pid, "ResourceType": rtype,
+ "Properties": res_props,
+ }
+ provisioned_resources.pop(logical_id, None)
+
+ if is_update and previous_stack:
+ # Restore previous resources
+ 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:
+ stack["StackStatus"] = "ROLLBACK_COMPLETE"
+ if rollback_failed_records:
+ # A rollback that could not undo what it created or changed
+ # must not report success — real CloudFormation lands the stack
+ # in (UPDATE_)ROLLBACK_FAILED and keeps the failure visible.
+ stack["StackStatus"] = (
+ "UPDATE_ROLLBACK_FAILED" if is_update and previous_stack
+ else "ROLLBACK_FAILED"
+ )
+ reason = _rollback_failure_reason(rollback_failed_records)
+ stack["StackStatusReason"] = reason
+ # What ContinueUpdateRollback retries (or skips).
+ stack["_rollback_failed"] = rollback_failed_records
+ _add_event(stack_id, stack_name, stack_name,
+ "AWS::CloudFormation::Stack", stack["StackStatus"],
+ reason, stack_id)
+ return
+ _add_event(stack_id, stack_name, stack_name,
+ "AWS::CloudFormation::Stack", stack["StackStatus"],
+ "" if is_update and previous_stack else "Rollback complete",
+ stack_id)
+
+
async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
param_values: dict, disable_rollback: bool,
tags: list, is_update: bool = False,
@@ -332,6 +536,7 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
from ministack.services.cloudformation import _exports, _stacks
status_prefix = "UPDATE" if is_update else "CREATE"
stack = _stacks[stack_name]
+ stack.pop("_failed_operation", None)
mappings = template.get("Mappings", {})
conditions = _evaluate_conditions(template, param_values)
@@ -344,6 +549,10 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
except ValueError as exc:
stack["StackStatus"] = f"{status_prefix}_FAILED"
stack["StackStatusReason"] = str(exc)
+ stack["_failed_operation"] = _failed_operation(
+ is_update, previous_stack, [], None, None, [], False, template,
+ param_values, retain_except_on_create, stack.get("Tags") or [],
+ (previous_stack or {}).get("Tags") or [])
_add_event(stack_id, stack_name, stack_name,
"AWS::CloudFormation::Stack", f"{status_prefix}_FAILED",
str(exc), stack_id)
@@ -651,166 +860,21 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
await asyncio.sleep(0)
if failed:
+ operation = _failed_operation(
+ is_update, previous_stack, created_in_this_run, failed_update,
+ failed_logical_id, [entry[0] for entry in replaced_resources],
+ cancelled, template, param_values, retain_except_on_create,
+ stack_tags, previous_tags)
if disable_rollback:
stack["StackStatus"] = f"{status_prefix}_FAILED"
stack["StackStatusReason"] = fail_reason
+ # RollbackStack picks this up (the "last known stable state").
+ stack["_failed_operation"] = operation
_add_event(stack_id, stack_name, stack_name,
"AWS::CloudFormation::Stack", f"{status_prefix}_FAILED",
fail_reason, stack_id)
else:
- # Rollback: delete resources created in this run in reverse order
- stack["StackStatus"] = "ROLLBACK_IN_PROGRESS" if not is_update else "UPDATE_ROLLBACK_IN_PROGRESS"
- if cancelled:
- rollback_reason = "User Initiated"
- elif is_update and failed_logical_id:
- verb = "update" if failed_update is not None else "create"
- rollback_reason = (f"The following resource(s) failed to {verb}: "
- f"[{failed_logical_id}]. ")
- else:
- rollback_reason = "Rollback requested"
- _add_event(stack_id, stack_name, stack_name,
- "AWS::CloudFormation::Stack", stack["StackStatus"],
- rollback_reason, stack_id)
-
- rollback_failed_records = {}
- previous_resources = (
- previous_stack.get("_resources", {})
- if is_update and previous_stack else {}
- )
- replaced_ids = {entry[0] for entry in replaced_resources}
-
- async def revert(logical_id, rtype, pid, applied, previous, attrs):
- # A failed revert is kept for ContinueUpdateRollback.
- try:
- await _revert_update(stack_id, stack_name, logical_id, rtype,
- pid, applied, previous, attrs,
- previous_resources.get(logical_id))
- except Exception:
- rollback_failed_records[logical_id] = {
- "PhysicalResourceId": pid, "ResourceType": rtype,
- "RevertFrom": applied, "RevertTo": previous,
- "Attributes": attrs,
- }
-
- # In-place changes go back first; what the update created is deleted in cleanup.
- to_delete = []
- for logical_id in created_in_this_run:
- res = provisioned_resources.get(logical_id, {})
- pid = res.get("PhysicalResourceId", "")
- prev = previous_resources.get(logical_id)
- if (prev is None or prev.get("PhysicalResourceId") != pid
- or logical_id in replaced_ids):
- to_delete.append(logical_id)
- continue
- # Pre-existing and same identity: sent back with the tags each side was called with.
- rtype = res.get("ResourceType", "")
- applied = _with_stack_tags(rtype, res.get("Properties", {}), stack_tags,
- stack_name, stack_id, logical_id)
- previous = _with_stack_tags(rtype, prev.get("Properties", {}),
- previous_tags, stack_name, stack_id,
- logical_id)
- if applied != previous:
- await revert(logical_id, rtype, pid, applied, previous,
- res.get("Attributes", {}))
- if failed_update is not None:
- logical_id, rtype, pid, applied, previous, attrs = failed_update
- if (applied is not None and applied != previous
- and _sends_back_failed_update(rtype)):
- await revert(logical_id, rtype, pid, applied, previous, attrs)
- else:
- _add_event(stack_id, stack_name, logical_id, rtype,
- "UPDATE_COMPLETE", physical_id=pid)
- _mark_rolled_back(previous_resources.get(logical_id))
- # "rolled back to its previous working state ... still deleting any new
- # resources" (view-stack-events): a cleanup delete failure does not fail it.
- cleanup_phase = bool(is_update and previous_stack
- and not rollback_failed_records)
- if cleanup_phase:
- stack["StackStatus"] = "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS"
- _add_event(stack_id, stack_name, stack_name,
- "AWS::CloudFormation::Stack", stack["StackStatus"],
- physical_id=stack_id)
- for logical_id in reversed(to_delete):
- res = provisioned_resources.get(logical_id, {})
- rtype = res.get("ResourceType", "")
- pid = res.get("PhysicalResourceId", "")
- res_props = res.get("Properties", {})
- policy = _resource_policy(
- resources_defs.get(logical_id), "DeletionPolicy",
- provisioned_resources, param_values, conditions, mappings,
- stack_name, stack_id)
- if policy == "Retain" and not retain_except_on_create:
- # ``Retain`` survives even the rollback of the operation
- # that created it; ``RetainExceptOnCreate`` and the API
- # parameter of that name are exactly the exception.
- _add_event(stack_id, stack_name, logical_id, rtype,
- "DELETE_SKIPPED", physical_id=pid)
- provisioned_resources.pop(logical_id, None)
- continue
- _add_event(stack_id, stack_name, logical_id, rtype,
- "DELETE_IN_PROGRESS", physical_id=pid)
- try:
- if _is_custom_resource(rtype):
- await run_reentrant(
- _delete_resource, rtype, pid, res_props,
- stack_name, logical_id
- )
- else:
- _delete_resource(rtype, pid, res_props, stack_name, logical_id)
- _add_event(stack_id, stack_name, logical_id, rtype,
- "DELETE_COMPLETE", physical_id=pid)
- except Exception as del_exc:
- logger.error("Rollback delete of %s failed: %s",
- logical_id, del_exc)
- _add_event(stack_id, stack_name, logical_id, rtype,
- "DELETE_FAILED", str(del_exc), pid)
- if cleanup_phase:
- provisioned_resources.pop(logical_id, None)
- continue
- rollback_failed_records[logical_id] = {
- "PhysicalResourceId": pid, "ResourceType": rtype,
- "Properties": res_props,
- }
- provisioned_resources.pop(logical_id, None)
-
- if is_update and previous_stack:
- # Restore previous resources
- 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:
- stack["StackStatus"] = "ROLLBACK_COMPLETE"
- if rollback_failed_records:
- # A rollback that could not undo what it created or changed
- # must not report success — real CloudFormation lands the stack
- # in (UPDATE_)ROLLBACK_FAILED and keeps the failure visible.
- stack["StackStatus"] = (
- "UPDATE_ROLLBACK_FAILED" if is_update and previous_stack
- else "ROLLBACK_FAILED"
- )
- reason = _rollback_failure_reason(rollback_failed_records)
- stack["StackStatusReason"] = reason
- # What ContinueUpdateRollback retries (or skips).
- stack["_rollback_failed"] = rollback_failed_records
- _add_event(stack_id, stack_name, stack_name,
- "AWS::CloudFormation::Stack", stack["StackStatus"],
- reason, stack_id)
- return
- _add_event(stack_id, stack_name, stack_name,
- "AWS::CloudFormation::Stack", stack["StackStatus"],
- "" if is_update and previous_stack else "Rollback complete",
- stack_id)
+ await _roll_back_operation(stack_name, stack_id, stack, operation)
return
# Success: publish outputs and exports
diff --git a/tests/test_cfn_drift.py b/tests/test_cfn_drift.py
new file mode 100644
index 00000000..aea4c5be
--- /dev/null
+++ b/tests/test_cfn_drift.py
@@ -0,0 +1,459 @@
+"""RollbackStack and stack drift detection (DetectStackDrift,
+DescribeStackDriftDetectionStatus, DetectStackResourceDrift,
+DescribeStackResourceDrifts, DriftInformation)."""
+
+import json
+import time
+import uuid
+
+import pytest
+from botocore.exceptions import ClientError
+
+_FAILING = {
+ "Type": "AWS::CloudFormation::CustomResource",
+ "Properties": {
+ "ServiceToken": "arn:aws:lambda:us-east-1:000000000000:function:cfn-drift-does-not-exist",
+ },
+}
+
+
+def _name(prefix):
+ return f"{prefix}-{uuid.uuid4().hex[:8]}"
+
+
+def _wait(cfn, name, timeout=30):
+ deadline = time.time() + timeout
+ status = "UNKNOWN"
+ while time.time() < deadline:
+ try:
+ stack = cfn.describe_stacks(StackName=name)["Stacks"][0]
+ except ClientError as exc:
+ if "does not exist" in str(exc):
+ return {"StackStatus": "DELETE_COMPLETE"}
+ raise
+ status = stack["StackStatus"]
+ if not status.endswith("_IN_PROGRESS"):
+ return stack
+ time.sleep(0.3)
+ raise TimeoutError(f"{name} stuck at {status}")
+
+
+def _cleanup(cfn, name):
+ try:
+ cfn.delete_stack(StackName=name)
+ _wait(cfn, name)
+ except ClientError:
+ pass
+
+
+def _statuses(cfn, name):
+ events = cfn.describe_stack_events(StackName=name)["StackEvents"]
+ return [(e["LogicalResourceId"], e["ResourceStatus"], e.get("ResourceStatusReason", ""))
+ for e in reversed(events)]
+
+
+def _queue_exists(sqs, name):
+ try:
+ sqs.get_queue_url(QueueName=name)
+ return True
+ except ClientError:
+ return False
+
+
+def _detect(cfn, name, **kwargs):
+ detection_id = cfn.detect_stack_drift(StackName=name, **kwargs)["StackDriftDetectionId"]
+ for _ in range(50):
+ status = cfn.describe_stack_drift_detection_status(StackDriftDetectionId=detection_id)
+ if status["DetectionStatus"] != "DETECTION_IN_PROGRESS":
+ return status
+ time.sleep(0.2)
+ raise TimeoutError("drift detection did not finish")
+
+
+def _drifts(cfn, name, **kwargs):
+ return {d["LogicalResourceId"]: d for d in
+ cfn.describe_stack_resource_drifts(StackName=name, **kwargs)["StackResourceDrifts"]}
+
+
+# ---------------------------------------------------------------------------
+# RollbackStack
+# ---------------------------------------------------------------------------
+
+def test_rollback_stack_from_create_failed_deletes_what_the_create_made(cfn, sqs):
+ name = _name("rb-create")
+ queue = f"{name}-q"
+ template = {"Resources": {
+ "Q": {"Type": "AWS::SQS::Queue", "Properties": {"QueueName": queue}},
+ "Bad": {**_FAILING, "DependsOn": "Q"},
+ }}
+ try:
+ cfn.create_stack(StackName=name, TemplateBody=json.dumps(template),
+ DisableRollback=True)
+ assert _wait(cfn, name)["StackStatus"] == "CREATE_FAILED"
+ assert _queue_exists(sqs, queue)
+
+ stack_id = cfn.rollback_stack(StackName=name)["StackId"]
+ assert stack_id.startswith("arn:aws:cloudformation:")
+ assert _wait(cfn, name)["StackStatus"] == "ROLLBACK_COMPLETE"
+ assert not _queue_exists(sqs, queue)
+ events = _statuses(cfn, name)
+ assert (name, "ROLLBACK_IN_PROGRESS", "User Initiated") in events
+ assert ("Q", "DELETE_COMPLETE", "") in events
+ assert events[-1][:2] == (name, "ROLLBACK_COMPLETE")
+ assert cfn.describe_stack_resources(StackName=name)["StackResources"] == []
+ finally:
+ _cleanup(cfn, name)
+
+
+def test_rollback_stack_from_update_failed_restores_the_previous_stack(cfn, sqs, ssm):
+ name = _name("rb-update")
+ queue = f"{name}-q"
+ added = f"{name}-added"
+ param = f"/{name}/p"
+
+ def template(visibility, value, extra):
+ resources = {
+ "Q": {"Type": "AWS::SQS::Queue",
+ "Properties": {"QueueName": queue, "VisibilityTimeout": visibility}},
+ "P": {"Type": "AWS::SSM::Parameter",
+ "Properties": {"Name": param, "Type": "String", "Value": value}},
+ }
+ if extra:
+ resources["Added"] = {"Type": "AWS::SQS::Queue",
+ "Properties": {"QueueName": added}}
+ resources["Bad"] = {**_FAILING, "DependsOn": ["P", "Q", "Added"]}
+ return json.dumps({"Resources": resources})
+
+ try:
+ cfn.create_stack(StackName=name, TemplateBody=template(30, "v1", False))
+ assert _wait(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
+ cfn.update_stack(StackName=name, TemplateBody=template(60, "v2", True),
+ DisableRollback=True)
+ failed = _wait(cfn, name)
+ assert failed["StackStatus"] == "UPDATE_FAILED"
+ # DisableRollback kept the partial update in place.
+ assert ssm.get_parameter(Name=param)["Parameter"]["Value"] == "v2"
+ assert _queue_exists(sqs, added)
+
+ cfn.rollback_stack(StackName=name)
+ assert _wait(cfn, name)["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ assert ssm.get_parameter(Name=param)["Parameter"]["Value"] == "v1"
+ url = sqs.get_queue_url(QueueName=queue)["QueueUrl"]
+ attrs = sqs.get_queue_attributes(QueueUrl=url, AttributeNames=["VisibilityTimeout"])
+ assert attrs["Attributes"]["VisibilityTimeout"] == "30"
+ assert not _queue_exists(sqs, added)
+ body = cfn.get_template(StackName=name)["TemplateBody"]
+ assert "Bad" not in json.dumps(body)
+ listed = {r["LogicalResourceId"] for r in
+ cfn.list_stack_resources(StackName=name)["StackResourceSummaries"]}
+ assert listed == {"Q", "P"}
+ statuses = [s for lid, s, _ in _statuses(cfn, name) if lid == name]
+ assert statuses[-3:] == ["UPDATE_ROLLBACK_IN_PROGRESS",
+ "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS",
+ "UPDATE_ROLLBACK_COMPLETE"]
+ finally:
+ _cleanup(cfn, name)
+
+
+def test_rollback_stack_retain_except_on_create_deletes_retained_new_resources(cfn, sqs):
+ name = _name("rb-retain")
+ queue = f"{name}-q"
+ template = {"Resources": {
+ "Q": {"Type": "AWS::SQS::Queue", "DeletionPolicy": "Retain",
+ "Properties": {"QueueName": queue}},
+ "Bad": {**_FAILING, "DependsOn": "Q"},
+ }}
+ try:
+ cfn.create_stack(StackName=name, TemplateBody=json.dumps(template),
+ DisableRollback=True)
+ assert _wait(cfn, name)["StackStatus"] == "CREATE_FAILED"
+ cfn.rollback_stack(StackName=name, RetainExceptOnCreate=True)
+ assert _wait(cfn, name)["StackStatus"] == "ROLLBACK_COMPLETE"
+ assert not _queue_exists(sqs, queue)
+ finally:
+ _cleanup(cfn, name)
+
+
+def test_rollback_stack_wrong_state_and_missing_stack(cfn):
+ name = _name("rb-wrong")
+ try:
+ cfn.create_stack(StackName=name, TemplateBody=json.dumps(
+ {"Resources": {"Q": {"Type": "AWS::SQS::Queue"}}}))
+ assert _wait(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
+ with pytest.raises(ClientError) as exc:
+ cfn.rollback_stack(StackName=name)
+ assert exc.value.response["Error"]["Code"] == "ValidationError"
+ assert "cannot be called from current stack status" in exc.value.response["Error"]["Message"]
+ with pytest.raises(ClientError) as exc:
+ cfn.rollback_stack(StackName=_name("rb-missing"))
+ assert exc.value.response["Error"]["Code"] == "ValidationError"
+ assert "does not exist" in exc.value.response["Error"]["Message"]
+ finally:
+ _cleanup(cfn, name)
+
+
+# ---------------------------------------------------------------------------
+# Drift detection
+# ---------------------------------------------------------------------------
+
+def _drift_template(name):
+ return json.dumps({"Resources": {
+ "Q": {"Type": "AWS::SQS::Queue", "Properties": {
+ "QueueName": f"{name}-q", "VisibilityTimeout": 45,
+ "Tags": [{"Key": "team", "Value": "a"}]}},
+ "P": {"Type": "AWS::SSM::Parameter", "Properties": {
+ "Name": f"/{name}/p", "Type": "String", "Value": "expected"}},
+ # No drift reader for queue policies: NOT_CHECKED.
+ "Policy": {"Type": "AWS::SQS::QueuePolicy", "Properties": {
+ "Queues": [{"Ref": "Q"}],
+ "PolicyDocument": {"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Principal": "*", "Action": "sqs:SendMessage",
+ "Resource": "*"}]}}},
+ }})
+
+
+def drift_stack(cfn):
+ name = _name("drift")
+ cfn.create_stack(StackName=name, TemplateBody=_drift_template(name),
+ Tags=[{"Key": "env", "Value": "test"}])
+ assert _wait(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
+ yield name
+ _cleanup(cfn, name)
+
+
+def test_drift_in_sync_after_create(cfn, drift_stack):
+ name = drift_stack
+ stack = cfn.describe_stacks(StackName=name)["Stacks"][0]
+ assert stack["DriftInformation"] == {"StackDriftStatus": "NOT_CHECKED"}
+ summary = next(s for s in cfn.list_stacks()["StackSummaries"] if s["StackName"] == name)
+ assert summary["DriftInformation"]["StackDriftStatus"] == "NOT_CHECKED"
+
+ status = _detect(cfn, name)
+ assert status["DetectionStatus"] == "DETECTION_COMPLETE"
+ assert status["StackDriftStatus"] == "IN_SYNC"
+ assert status["DriftedStackResourceCount"] == 0
+ assert status["StackId"] == stack["StackId"]
+
+ drifts = _drifts(cfn, name)
+ # Only the checked resources are listed; the queue policy has no support.
+ assert set(drifts) == {"Q", "P"}
+ q = drifts["Q"]
+ assert q["StackResourceDriftStatus"] == "IN_SYNC"
+ assert json.loads(q["ExpectedProperties"]) == json.loads(q["ActualProperties"])
+ # The stack-level tag is part of the expected tags; aws: tags are not.
+ assert json.loads(q["ExpectedProperties"])["Tags"] == [
+ {"Key": "team", "Value": "a"}, {"Key": "env", "Value": "test"}]
+ assert "PropertyDifferences" not in q or q["PropertyDifferences"] == []
+
+ after = cfn.describe_stacks(StackName=name)["Stacks"][0]["DriftInformation"]
+ assert after["StackDriftStatus"] == "IN_SYNC"
+ assert "LastCheckTimestamp" in after
+ resources = {r["LogicalResourceId"]: r["DriftInformation"]
+ for r in cfn.describe_stack_resources(StackName=name)["StackResources"]}
+ assert resources["Q"]["StackResourceDriftStatus"] == "IN_SYNC"
+ assert "LastCheckTimestamp" in resources["Q"]
+ assert resources["Policy"] == {"StackResourceDriftStatus": "NOT_CHECKED"}
+ summaries = {r["LogicalResourceId"]: r["DriftInformation"]
+ for r in cfn.list_stack_resources(StackName=name)["StackResourceSummaries"]}
+ assert summaries["P"]["StackResourceDriftStatus"] == "IN_SYNC"
+ detail = cfn.describe_stack_resource(StackName=name, LogicalResourceId="Policy")
+ assert detail["StackResourceDetail"]["DriftInformation"]["StackResourceDriftStatus"] == "NOT_CHECKED"
+
+
+def test_drift_modified_after_out_of_band_changes(cfn, sqs, ssm, drift_stack):
+ name = drift_stack
+ url = sqs.get_queue_url(QueueName=f"{name}-q")["QueueUrl"]
+ sqs.set_queue_attributes(QueueUrl=url, Attributes={"VisibilityTimeout": "99"})
+ sqs.tag_queue(QueueUrl=url, Tags={"added": "x"})
+ ssm.put_parameter(Name=f"/{name}/p", Value="changed", Type="String", Overwrite=True)
+
+ status = _detect(cfn, name)
+ assert status["StackDriftStatus"] == "DRIFTED"
+ assert status["DriftedStackResourceCount"] == 2
+
+ drifts = _drifts(cfn, name)
+ q = drifts["Q"]
+ assert q["StackResourceDriftStatus"] == "MODIFIED"
+ diffs = {d["PropertyPath"]: d for d in q["PropertyDifferences"]}
+ assert diffs["/VisibilityTimeout"] == {
+ "PropertyPath": "/VisibilityTimeout", "ExpectedValue": "45",
+ "ActualValue": "99", "DifferenceType": "NOT_EQUAL"}
+ added = [d for d in q["PropertyDifferences"] if d["DifferenceType"] == "ADD"]
+ assert len(added) == 1 and added[0]["PropertyPath"].startswith("/Tags/")
+ assert json.loads(added[0]["ActualValue"]) == {"Key": "added", "Value": "x"}
+ assert json.loads(q["ActualProperties"])["VisibilityTimeout"] == 99
+ assert json.loads(q["ExpectedProperties"])["VisibilityTimeout"] == 45
+
+ p = drifts["P"]
+ assert p["StackResourceDriftStatus"] == "MODIFIED"
+ assert p["PropertyDifferences"] == [{
+ "PropertyPath": "/Value", "ExpectedValue": "expected",
+ "ActualValue": "changed", "DifferenceType": "NOT_EQUAL"}]
+
+ assert cfn.describe_stacks(StackName=name)["Stacks"][0]["DriftInformation"][
+ "StackDriftStatus"] == "DRIFTED"
+ modified = _drifts(cfn, name, StackResourceDriftStatusFilters=["MODIFIED"])
+ assert set(modified) == {"Q", "P"}
+ assert _drifts(cfn, name, StackResourceDriftStatusFilters=["IN_SYNC", "DELETED"]) == {}
+ assert _drifts(cfn, name, StackResourceDriftStatusFilters=["NOT_CHECKED"]) == {}
+
+
+def test_drift_removed_tag_is_reported_as_remove(cfn, sqs, drift_stack):
+ name = drift_stack
+ url = sqs.get_queue_url(QueueName=f"{name}-q")["QueueUrl"]
+ sqs.untag_queue(QueueUrl=url, TagKeys=["team"])
+ drift = cfn.detect_stack_resource_drift(StackName=name, LogicalResourceId="Q")[
+ "StackResourceDrift"]
+ assert drift["StackResourceDriftStatus"] == "MODIFIED"
+ assert drift["PropertyDifferences"] == [{
+ "PropertyPath": "/Tags/0", "ExpectedValue": json.dumps(
+ {"Key": "team", "Value": "a"}, sort_keys=True),
+ "ActualValue": "null", "DifferenceType": "REMOVE"}]
+
+
+def test_drift_deleted_after_out_of_band_delete(cfn, sqs, drift_stack):
+ name = drift_stack
+ url = sqs.get_queue_url(QueueName=f"{name}-q")["QueueUrl"]
+ sqs.delete_queue(QueueUrl=url)
+
+ drift = cfn.detect_stack_resource_drift(StackName=name, LogicalResourceId="Q")[
+ "StackResourceDrift"]
+ assert drift["StackResourceDriftStatus"] == "DELETED"
+ assert "ExpectedProperties" not in drift and "ActualProperties" not in drift
+ assert drift["PhysicalResourceId"] == url
+ # A single-resource check moves the stack's LastCheckTimestamp only.
+ info = cfn.describe_stacks(StackName=name)["Stacks"][0]["DriftInformation"]
+ assert info["StackDriftStatus"] == "NOT_CHECKED" and "LastCheckTimestamp" in info
+ assert set(_drifts(cfn, name, StackResourceDriftStatusFilters=["DELETED"])) == {"Q"}
+
+ status = _detect(cfn, name)
+ assert status["StackDriftStatus"] == "DRIFTED"
+ assert status["DriftedStackResourceCount"] == 1
+
+
+def test_drift_logical_resource_ids_filter(cfn, ssm, drift_stack):
+ name = drift_stack
+ ssm.put_parameter(Name=f"/{name}/p", Value="changed", Type="String", Overwrite=True)
+ status = _detect(cfn, name, LogicalResourceIds=["Q"])
+ assert status["StackDriftStatus"] == "IN_SYNC"
+ assert set(_drifts(cfn, name)) == {"Q"}
+ with pytest.raises(ClientError) as exc:
+ cfn.detect_stack_drift(StackName=name, LogicalResourceIds=["Nope"])
+ assert exc.value.response["Error"]["Code"] == "ValidationError"
+
+
+def test_drift_unsupported_type_and_missing_resource(cfn, drift_stack):
+ name = drift_stack
+ with pytest.raises(ClientError) as exc:
+ cfn.detect_stack_resource_drift(StackName=name, LogicalResourceId="Policy")
+ assert exc.value.response["Error"]["Code"] == "ValidationError"
+ assert "AWS::SQS::QueuePolicy" in exc.value.response["Error"]["Message"]
+ with pytest.raises(ClientError) as exc:
+ cfn.detect_stack_resource_drift(StackName=name, LogicalResourceId="Nope")
+ assert exc.value.response["Error"]["Code"] == "ValidationError"
+ with pytest.raises(ClientError) as exc:
+ cfn.describe_stack_drift_detection_status(StackDriftDetectionId=str(uuid.uuid4()))
+ assert exc.value.response["Error"]["Code"] == "ValidationError"
+
+
+def test_drift_refused_on_unstable_stack(cfn):
+ name = _name("drift-failed")
+ template = {"Resources": {"Q": {"Type": "AWS::SQS::Queue"}, "Bad": _FAILING}}
+ try:
+ cfn.create_stack(StackName=name, TemplateBody=json.dumps(template),
+ DisableRollback=True)
+ assert _wait(cfn, name)["StackStatus"] == "CREATE_FAILED"
+ with pytest.raises(ClientError) as exc:
+ cfn.detect_stack_drift(StackName=name)
+ assert exc.value.response["Error"]["Code"] == "ValidationError"
+ assert "CREATE_FAILED" in exc.value.response["Error"]["Message"]
+ finally:
+ _cleanup(cfn, name)
+
+
+def test_drift_property_readers_for_more_types(cfn, iam, lam, ddb, sns, s3):
+ name = _name("drift-types")
+ template = {"Resources": {
+ "Role": {"Type": "AWS::IAM::Role", "Properties": {
+ "RoleName": f"{name}-role", "MaxSessionDuration": 3600,
+ "AssumeRolePolicyDocument": {"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"},
+ "Action": "sts:AssumeRole"}]}}},
+ "Fn": {"Type": "AWS::Lambda::Function", "Properties": {
+ "FunctionName": f"{name}-fn", "Runtime": "python3.12", "Handler": "index.handler",
+ "Role": {"Fn::GetAtt": ["Role", "Arn"]}, "Timeout": 10,
+ "Code": {"ZipFile": "def handler(e, c):\n return 1\n"},
+ "Environment": {"Variables": {"A": "1"}}}},
+ "Table": {"Type": "AWS::DynamoDB::Table", "Properties": {
+ "TableName": f"{name}-t", "BillingMode": "PROVISIONED",
+ "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
+ "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}}},
+ "Topic": {"Type": "AWS::SNS::Topic", "Properties": {
+ "TopicName": f"{name}-topic", "DisplayName": "before"}},
+ "Bucket": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": f"{name}-b"}},
+ }}
+ try:
+ cfn.create_stack(StackName=name, TemplateBody=json.dumps(template),
+ Capabilities=["CAPABILITY_NAMED_IAM"])
+ assert _wait(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
+ assert _detect(cfn, name)["StackDriftStatus"] == "IN_SYNC"
+ assert {d["StackResourceDriftStatus"] for d in _drifts(cfn, name).values()} == {"IN_SYNC"}
+
+ iam.update_role(RoleName=f"{name}-role", MaxSessionDuration=7200)
+ lam.update_function_configuration(FunctionName=f"{name}-fn", Timeout=20,
+ Environment={"Variables": {"A": "2"}})
+ ddb.update_table(TableName=f"{name}-t", ProvisionedThroughput={
+ "ReadCapacityUnits": 7, "WriteCapacityUnits": 5})
+ topic_arn = cfn.describe_stack_resource(StackName=name, LogicalResourceId="Topic")[
+ "StackResourceDetail"]["PhysicalResourceId"]
+ sns.set_topic_attributes(TopicArn=topic_arn, AttributeName="DisplayName",
+ AttributeValue="after")
+ s3.delete_bucket(Bucket=f"{name}-b")
+
+ status = _detect(cfn, name)
+ assert status["DriftedStackResourceCount"] == 5
+ drifts = _drifts(cfn, name)
+ paths = {lid: {(d["PropertyPath"], d["ExpectedValue"], d["ActualValue"])
+ for d in d_.get("PropertyDifferences", [])}
+ for lid, d_ in drifts.items()}
+ assert paths["Role"] == {("/MaxSessionDuration", "3600", "7200")}
+ assert paths["Fn"] == {("/Timeout", "10", "20"), ("/Environment/Variables/A", "1", "2")}
+ assert paths["Table"] == {("/ProvisionedThroughput/ReadCapacityUnits", "5", "7")}
+ assert paths["Topic"] == {("/DisplayName", "before", "after")}
+ assert drifts["Bucket"]["StackResourceDriftStatus"] == "DELETED"
+ finally:
+ try:
+ s3.create_bucket(Bucket=f"{name}-b")
+ except ClientError:
+ pass
+ _cleanup(cfn, name)
+
+
+def test_describe_stack_resource_drifts_pagination(cfn):
+ name = _name("drift-page")
+ resources = {
+ f"P{i}": {"Type": "AWS::SSM::Parameter", "Properties": {
+ "Name": f"/{name}/p{i}", "Type": "String", "Value": str(i)}}
+ for i in range(3)
+ }
+ try:
+ cfn.create_stack(StackName=name, TemplateBody=json.dumps({"Resources": resources}))
+ assert _wait(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
+ _detect(cfn, name)
+ first = cfn.describe_stack_resource_drifts(StackName=name, MaxResults=2)
+ assert len(first["StackResourceDrifts"]) == 2
+ assert first.get("NextToken")
+ second = cfn.describe_stack_resource_drifts(StackName=name, MaxResults=2,
+ NextToken=first["NextToken"])
+ assert len(second["StackResourceDrifts"]) == 1
+ assert "NextToken" not in second
+ ids = {d["LogicalResourceId"] for d in
+ first["StackResourceDrifts"] + second["StackResourceDrifts"]}
+ assert ids == {"P0", "P1", "P2"}
+ with pytest.raises(ClientError) as exc:
+ cfn.describe_stack_resource_drifts(StackName=name, NextToken="ListStacks:1")
+ assert exc.value.response["Error"]["Code"] == "ValidationError"
+ finally:
+ _cleanup(cfn, name)
diff --git a/tests/test_persistence.py b/tests/test_persistence.py
index 3ce3f322..19b8de5f 100644
--- a/tests/test_persistence.py
+++ b/tests/test_persistence.py
@@ -919,6 +919,47 @@ def test_cloudformation_round_trip():
_round_trip("cloudformation", "cloudformation", populate, observe)
+def test_cloudformation_drift_and_failed_operation_round_trip():
+ """Drift results and the failed operation RollbackStack needs live on the
+ stack record, so they survive a PERSIST_STATE stop/restore cycle."""
+ stack_id = "arn:aws:cloudformation:us-east-1:000000000000:stack/stk-drift/rt"
+
+ def populate(mod):
+ drift = {"StackId": stack_id, "LogicalResourceId": "Q", "ResourceType": "AWS::SQS::Queue",
+ "StackResourceDriftStatus": "MODIFIED", "Timestamp": "2026-09-30T00:00:00.000Z",
+ "PropertyDifferences": [{"PropertyPath": "/VisibilityTimeout",
+ "ExpectedValue": "30", "ActualValue": "60",
+ "DifferenceType": "NOT_EQUAL"}]}
+ mod._stacks["stk-drift"] = {
+ "StackName": "stk-drift",
+ "StackId": stack_id,
+ "StackStatus": "UPDATE_FAILED",
+ "DriftInformation": {"StackDriftStatus": "DRIFTED",
+ "LastCheckTimestamp": "2026-09-30T00:00:00.000Z"},
+ "_drift_detections": {"det-1": {"StackId": stack_id,
+ "StackDriftDetectionId": "det-1",
+ "StackDriftStatus": "DRIFTED",
+ "DetectionStatus": "DETECTION_COMPLETE",
+ "DriftedStackResourceCount": 1,
+ "Timestamp": "2026-09-30T00:00:00.000Z"}},
+ "_resources": {"Q": {"ResourceType": "AWS::SQS::Queue", "_drift": drift,
+ "DriftInformation": {"StackResourceDriftStatus": "MODIFIED"}}},
+ "_failed_operation": {"is_update": True, "created": ["Q"],
+ "failed_update": ["Q", "AWS::SQS::Queue", "url", None, None, None],
+ "replaced_ids": [], "previous_stack": {"_resources": {}}},
+ }
+
+ def observe(mod):
+ stack = mod._stacks.get("stk-drift")
+ assert stack["DriftInformation"]["StackDriftStatus"] == "DRIFTED"
+ assert stack["_drift_detections"]["det-1"]["DriftedStackResourceCount"] == 1
+ assert stack["_resources"]["Q"]["_drift"]["PropertyDifferences"][0]["ActualValue"] == "60"
+ assert stack["_failed_operation"]["failed_update"][0] == "Q"
+ assert stack["_failed_operation"]["created"] == ["Q"]
+
+ _round_trip("cloudformation", "cloudformation", populate, observe)
+
+
def test_backup_region_scoped_v3_state_is_idempotent(monkeypatch, tmp_path):
import json as _json