Skip to content

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

feat(cloudformation): update 16 more types in place, roll back in-place changes, ECS cluster settings and EC2 stack tags (#1796)

iot-rocket6b00c55d69c0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d1487ec8..121bdefb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,30 @@ All notable changes to MiniStack will be documented here.
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
Versioning follows [Semantic Versioning](https://semver.org/).
+## [Unreleased]
+
+### Added
+
+- **CloudFormation — AppConfig applications, environments, configuration profiles and deployment strategies update in place** — none of the four had an update handler, so any property change re-ran the create and the resource came back under a new id. The environments, configuration profiles and hosted configuration versions keyed by the old id were orphaned. Each type now updates in place what its resource reference lists as No interruption and replaces on the rest. Contributed by @iot-rocket.
+- **CloudFormation — AppSync GraphQL APIs and API keys update in place** — every property of `AWS::AppSync::GraphQLApi` is No interruption, but a change re-ran the create, which minted a new api id with empty key, data source, resolver and type stores, so a renamed API came back empty. The API now keeps its id and applies the change in place. It stores `AdditionalAuthenticationProviders`, `XrayEnabled`, `QueryDepthLimit`, `ResolverCountLimit`, `IntrospectionConfig`, `EnvironmentVariables`, `OwnerContact`, `LogConfig`, `UserPoolConfig`, `OpenIDConnectConfig`, `LambdaAuthorizerConfig`, `EnhancedMetricsConfig` and `MergedApiExecutionRoleArn` in AppSync's camelCase, and a removed member goes back to AppSync's default. A `Visibility` change fails with AWS's message. The API carries the stack-level tags, its id has `CreateGraphqlApi`'s 26 characters (eight made an ARN botocore refuses) and it answers the `REALTIME` endpoint. `AWS::AppSync::ApiKey` keeps its key on a `Description` or `Expires` change, and its record carries `description` and `createdAt`, as `CreateApiKey` writes them. Contributed by @iot-rocket.
+- **CloudFormation — Auto Scaling groups, scaling policies and scheduled actions update in place** — a change re-ran the create, which mints a new ARN from a uuid, and the group also lost its instances and its creation time. The three types now update in place. An `AutoScalingGroupName` or `InstanceId` change replaces the group, and a group tag change keeps tags added through `CreateOrUpdateTags`. As on AWS, `PolicyName` names a scaling policy at create and is ignored after that, and CloudFormation names a scheduled action itself, ignores `ScheduledActionName` and answers the generated name through `Ref` (it answered the ARN). `DescribeAutoScalingGroups` answers the launch template's name beside its id. Contributed by @iot-rocket.
+- **CloudFormation — a VPC updates in place and is deleted with its default children** — `EnableDnsSupport`, `EnableDnsHostnames` and `Tags` are No interruption, but a change re-ran the create, which mints a new `vpc-` id. The delete removed only the VPC, so each change left its default security group, main route table and network ACL behind. The VPC now updates in place, and a removed DNS property goes back to its default. The delete goes through `DeleteVpc`, which removes the default children and fails with `DependencyViolation` while a security group created outside the stack is still in the VPC; AWS keeps that VPC too and retries the delete for a long time. The create applies the two DNS properties and the template's tags, which it ignored. `Ipv4IpamPoolId`, `Ipv4NetmaskLength` and `VpcEncryptionControl` replace the VPC, like `CidrBlock`. Contributed by @iot-rocket.
+- **CloudFormation — a subnet updates in place** — `MapPublicIpOnLaunch`, `PrivateDnsNameOptionsOnLaunch`, `EnableDns64` and `Tags` are No interruption, but a change re-ran the create, which mints a new `subnet-` id and left every instance, network interface and NAT gateway on an id that no longer resolves. They are applied in place now, and a property the template removes keeps its value, as on AWS. `EnableDns64` without an IPv6 block fails with AWS's message. `AvailabilityZoneId` is honoured, and it, the IPAM members, `Ipv6Native` and `OutpostArn` replace the subnet. A `MapPublicIpOnLaunch` of `"false"` reads false. Contributed by @iot-rocket.
+- **CloudFormation — a security group updates its rules in place** — `SecurityGroupIngress` and `SecurityGroupEgress` are updated in place on AWS and `Tags` is No interruption, but a change re-ran the create, which mints a new `sg-` id and lost every rule authorized outside the template. The rules are reconciled now: dropped ones are removed, new ones added, a changed `Description` is applied, and rules added outside the template stay. The create applies `SecurityGroupEgress`, which it ignored, and adds the allow-all egress rule only when the template declares none. An update that declares egress removes that rule, and one that drops the declaration leaves no egress rule, as on AWS. A rule's `Description`, `CidrIpv6`, prefix-list source or destination and a source group's name and owner are kept. Contributed by @iot-rocket.
+- **CloudFormation — a launch template change adds a version** — `LaunchTemplateData`, `TagSpecifications` and `VersionDescription` are No interruption, but a change re-ran the create, which minted a new `lt-` id and reset `LatestVersionNumber` and `DefaultVersionNumber` to 1. Each change now adds a version to the same template and the default version stays where it is, as measured on AWS. A rollback adds a version with the old data. The template's own tags come from its `TagSpecifications` entry for `launch-template` and are applied at create only (the create read a `Tags` property the type does not have). Contributed by @iot-rocket.
+- **CloudFormation — an internet gateway keeps its id and its attachment** — `Tags` is the only property of `AWS::EC2::InternetGateway` and it is No interruption, but the create ignored it, so a tag change minted a new `igw-` id, reset `Attachments` and applied no tags. The gateway now keeps its id and attachment and its tags are applied. Contributed by @iot-rocket.
+- **CloudFormation — a route table keeps its routes and associations** — `Tags` is No interruption on `AWS::EC2::RouteTable`, but a tag change re-ran the create, which minted a new `rtb-` id with only the local route and no associations, so everything added through `CreateRoute` or `AssociateRouteTable` was lost. The table now keeps its id, routes and associations, and its tags are applied. Contributed by @iot-rocket.
+- **CloudFormation — a route target change updates the route in place** — every target property of `AWS::EC2::Route` is No interruption, but the physical id `"{table}|{destination}"` did not move, so the create appended a second route for the same destination. The update and the create now replace the route for that destination, and the ten targets the create dropped are read, `OdbNetworkArn` included. The destination is read from `DestinationCidrBlock`, `DestinationIpv6CidrBlock` or `DestinationPrefixListId`: an IPv6 or prefix-list route overwrote the IPv4 default route, where AWS keeps them side by side. Contributed by @iot-rocket.
+
+### Fixed
+
+- **Auto Scaling — scaling policies and scheduled actions keep their members** — `PutScalingPolicy` and `DescribePolicies` dropped `TargetTrackingConfiguration`, `StepAdjustments`, `PredictiveScalingConfiguration`, `EstimatedInstanceWarmup`, `MetricAggregationType` and `MinAdjustmentMagnitude`. They are stored and answered typed as on AWS, with only the members the policy type has, and `MaxCapacityBreachBehavior` defaults to `HonorMaxCapacity`. A member that is not a number gives `ValidationError` instead of a 500. `Alarms` stays empty where AWS lists the target tracking alarms. Scheduled actions keep `StartTime`, `EndTime` and `TimeZone`, and `DescribeScheduledActions` answers them with `Recurrence` and the sizes. Contributed by @iot-rocket.
+- **EC2 — subnets answer their DNS and IPv6 attributes** — `DescribeSubnets` answers `PrivateDnsNameOptionsOnLaunch`, `EnableDns64`, `Ipv6Native` and `AssignIpv6AddressOnCreation`, which it did not render, with AWS's defaults for a subnet created without them. `ModifySubnetAttribute` changes the private DNS name options. Contributed by @iot-rocket.
+- **EC2 — launch templates answer their tags and list versions newest first** — `CreateLaunchTemplate` and `DescribeLaunchTemplates` rendered tags under `tags`, so botocore dropped them; they answer `tagSet` now. `DescribeLaunchTemplateVersions` lists the newest version first, as AWS does. Contributed by @iot-rocket.
+- **EC2 — `DescribeRouteTables` answers every route destination and target** — an IPv6 or prefix-list route came back with an empty `destinationCidrBlock`, and only five target types were rendered. All destinations and targets are answered now, a VPC endpoint target as `gatewayId`. Contributed by @iot-rocket.
+- **CloudFormation — a failed update rolls back its in-place changes** — the rollback kept every resource that existed before the update but did not undo what the update had changed on it, the limitation 1.5.8 shipped with. Each changed resource now goes back through its type's update handler with `UPDATE_IN_PROGRESS` / `UPDATE_COMPLETE` events, before the cleanup deletes what the update created. A custom resource whose own update failed is sent back too, and a revert that fails lands the stack in `UPDATE_ROLLBACK_FAILED`, which `ContinueUpdateRollback` retries or skips. `UPDATE_ROLLBACK_IN_PROGRESS` names the failed resource, the cleanup runs in `UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS` with `DELETE_IN_PROGRESS` events, and a delete that fails there no longer fails the rollback. An executed change set that rolls back restores the stack's parameters. AWS reverts resources in parallel, the emulator one after the other. Contributed by @iot-rocket.
+- **CloudFormation — an ECS cluster reads its settings back** — `ClusterSettings`, `DefaultCapacityProviderStrategy` and `Configuration` of `AWS::ECS::Cluster` were stored in the template's PascalCase (`Configuration` not at all), so `DescribeClusters` answered `[{}]` for the settings and the strategy. All three are stored in the API's camelCase now. `DescribeClusters` answers them also without `include`, where AWS needs `SETTINGS` or `CONFIGURATIONS`. Contributed by @iot-rocket.
+- **CloudFormation — VPCs, subnets, security groups, internet gateways and route tables carry the stack's tags** — the five types carried only the template's own tags. They now also get the stack-level tags and the three `aws:cloudformation:` tags, as on AWS, and a stack tag change is applied to them in place. Contributed by @iot-rocket.
## [1.5.16] — 2026-09-23
### Added
diff --git a/ministack/services/autoscaling.py b/ministack/services/autoscaling.py
index d96c07b4..11abe80a 100644
--- a/ministack/services/autoscaling.py
+++ b/ministack/services/autoscaling.py
@@ -21,6 +21,7 @@ Supports:
import copy
import logging
import os
+from xml.sax.saxutils import escape
from ministack.core.responses import (
AccountRegionScopedDict,
@@ -515,6 +516,103 @@ def _delete_lc(p):
# Scaling Policy
# ---------------------------------------------------------------------------
+# The typed scalars of a policy's members; every other leaf is a string.
+# DescribePolicies serializes TargetValue and the step bounds as doubles, the
+# switches as booleans (measured on AWS 2026-09-21: TargetValue 40.0,
+# MetricIntervalLowerBound 0.0, DisableScaleIn false).
+_POLICY_FLOATS = frozenset({"TargetValue", "MetricIntervalLowerBound", "MetricIntervalUpperBound"})
+_POLICY_INTS = frozenset({"ScalingAdjustment", "EstimatedInstanceWarmup",
+ "MinAdjustmentMagnitude", "Period", "SchedulingBufferTime",
+ "MaxCapacityBuffer"})
+_POLICY_BOOLS = frozenset({"DisableScaleIn", "ReturnData", "Enabled"})
+# The optional members a policy keeps as given, in DescribePolicies' names.
+_POLICY_OPTIONAL = ("EstimatedInstanceWarmup", "MetricAggregationType",
+ "MinAdjustmentMagnitude", "PredictiveScalingConfiguration",
+ "StepAdjustments", "TargetTrackingConfiguration")
+
+
+def _policy_typed(value, key=None):
+ if isinstance(value, dict):
+ return {k: _policy_typed(v, k) for k, v in value.items()}
+ if isinstance(value, list):
+ return [_policy_typed(v) for v in value]
+ if key in _POLICY_FLOATS:
+ return float(value)
+ if key in _POLICY_INTS:
+ return int(value)
+ if key in _POLICY_BOOLS:
+ return value if isinstance(value, bool) else str(value).lower() == "true"
+ return value
+
+
+def _parse_nested(params, prefix):
+ """The query members under ``prefix`` as nested dicts, each
+ ``.member.N`` level as a list: ``Dimensions.member.1.Name`` becomes
+ ``{"Dimensions": [{"Name": ...}]}``."""
+ tree = {}
+ for key in params:
+ if not key.startswith(prefix + "."):
+ continue
+ tokens = key[len(prefix) + 1:].split(".")
+ path = []
+ i = 0
+ while i < len(tokens):
+ if tokens[i] == "member" and i + 1 < len(tokens) and tokens[i + 1].isdigit():
+ path.append(int(tokens[i + 1]))
+ i += 2
+ else:
+ path.append(tokens[i])
+ i += 1
+ node = tree
+ for step in path[:-1]:
+ node = node.setdefault(step, {})
+ node[path[-1]] = _p(params, key)
+
+ def listify(node):
+ if isinstance(node, dict):
+ if node and all(isinstance(k, int) for k in node):
+ return [listify(node[k]) for k in sorted(node)]
+ return {k: listify(v) for k, v in node.items()}
+ return node
+
+ return listify(tree)
+
+
+def _policy_record(asg_name, policy_name, arn, fields):
+ """A scaling policy as the store keeps it, from PutScalingPolicy's members
+ or an AWS::AutoScaling::ScalingPolicy's properties (the same PascalCase
+ names). Only the members the policy type has are kept, which is what
+ DescribePolicies answers on AWS: a target-tracking policy carries no
+ AdjustmentType, ScalingAdjustment or Cooldown, a step policy no
+ ScalingAdjustment or Cooldown."""
+ policy_type = fields.get("PolicyType") or "SimpleScaling"
+ record = {
+ "PolicyARN": arn,
+ "PolicyName": policy_name,
+ "AutoScalingGroupName": asg_name,
+ "PolicyType": policy_type,
+ "Enabled": _policy_typed(fields.get("Enabled", True), "Enabled"),
+ }
+ if policy_type in ("SimpleScaling", "StepScaling"):
+ record["AdjustmentType"] = fields.get("AdjustmentType") or "ChangeInCapacity"
+ if policy_type == "SimpleScaling":
+ record["ScalingAdjustment"] = int(fields.get("ScalingAdjustment") or 0)
+ record["Cooldown"] = int(fields.get("Cooldown") or 300)
+ for member in _POLICY_OPTIONAL:
+ value = fields.get(member)
+ if value not in (None, "", [], {}):
+ record[member] = _policy_typed(value, member)
+ tracking = record.get("TargetTrackingConfiguration")
+ if tracking is not None:
+ tracking.setdefault("DisableScaleIn", False)
+ predictive = record.get("PredictiveScalingConfiguration")
+ if predictive is not None:
+ # AWS answers the default when the caller leaves it out (measured
+ # 2026-09-21).
+ predictive.setdefault("MaxCapacityBreachBehavior", "HonorMaxCapacity")
+ return record
+
+
def _put_scaling_policy(p):
asg_name = _p(p, "AutoScalingGroupName")
policy_name = _p(p, "PolicyName")
@@ -522,34 +620,53 @@ def _put_scaling_policy(p):
return _error("ValidationError", "PolicyName is required")
arn = f"arn:aws:autoscaling:{get_region()}:{get_account_id()}:scalingPolicy:{new_uuid()}:autoScalingGroupName/{asg_name}:policyName/{policy_name}"
key = f"{asg_name}/{policy_name}"
- _policies[key] = {
- "PolicyARN": arn,
- "PolicyName": policy_name,
- "AutoScalingGroupName": asg_name,
- "PolicyType": _p(p, "PolicyType") or "SimpleScaling",
- "AdjustmentType": _p(p, "AdjustmentType") or "ChangeInCapacity",
- "ScalingAdjustment": int(_p(p, "ScalingAdjustment") or 0),
- "Cooldown": int(_p(p, "Cooldown") or 300),
- }
+ fields = {k: _p(p, k) for k in ("PolicyType", "AdjustmentType", "ScalingAdjustment",
+ "Cooldown", "Enabled", "EstimatedInstanceWarmup",
+ "MetricAggregationType", "MinAdjustmentMagnitude")
+ if _p(p, k) != ""}
+ fields["StepAdjustments"] = _parse_nested(p, "StepAdjustments")
+ fields["TargetTrackingConfiguration"] = _parse_nested(p, "TargetTrackingConfiguration")
+ fields["PredictiveScalingConfiguration"] = _parse_nested(p, "PredictiveScalingConfiguration")
+ try:
+ record = _policy_record(asg_name, policy_name, arn, fields)
+ except ValueError as exc:
+ # A number member (TargetValue, a step bound, ScalingAdjustment) that
+ # does not parse is the caller's error, not a 500.
+ return _error("ValidationError", f"Invalid numeric value in the scaling policy: {escape(str(exc))}")
+ _policies[key] = record
return _xml(200, "PutScalingPolicyResponse",
f"<PutScalingPolicyResult><PolicyARN>{arn}</PolicyARN></PutScalingPolicyResult>")
+def _member_xml(value):
+ """A stored member in the query protocol's XML: a dict as its members, a
+ list as ``<member>`` entries, a boolean as true/false."""
+ if isinstance(value, dict):
+ return "".join(f"<{k}>{_member_xml(v)}</{k}>" for k, v in value.items())
+ if isinstance(value, list):
+ return "".join(f"<member>{_member_xml(v)}</member>" for v in value)
+ if isinstance(value, bool):
+ return "true" if value else "false"
+ return escape(str(value))
+
+
def _describe_policies(p):
asg_name = _p(p, "AutoScalingGroupName")
members = ""
for key, pol in _policies.items():
if asg_name and pol["AutoScalingGroupName"] != asg_name:
continue
- members += (f"<member>"
- f"<PolicyARN>{pol['PolicyARN']}</PolicyARN>"
- f"<PolicyName>{pol['PolicyName']}</PolicyName>"
- f"<AutoScalingGroupName>{pol['AutoScalingGroupName']}</AutoScalingGroupName>"
- f"<PolicyType>{pol['PolicyType']}</PolicyType>"
- f"<AdjustmentType>{pol.get('AdjustmentType', '')}</AdjustmentType>"
- f"<ScalingAdjustment>{pol.get('ScalingAdjustment', 0)}</ScalingAdjustment>"
- f"<Cooldown>{pol.get('Cooldown', 300)}</Cooldown>"
- f"</member>")
+ # The optional members were dropped here, so a target-tracking or step
+ # policy read back without its whole configuration. AWS answers the
+ # type's members only, StepAdjustments and Alarms as (empty) lists,
+ # and MinAdjustmentStep beside MinAdjustmentMagnitude.
+ body = dict(pol)
+ body.setdefault("Enabled", True)
+ body.setdefault("StepAdjustments", [])
+ body.setdefault("Alarms", [])
+ if "MinAdjustmentMagnitude" in body:
+ body["MinAdjustmentStep"] = body["MinAdjustmentMagnitude"]
+ members += f"<member>{_member_xml(body)}</member>"
return _xml(200, "DescribePoliciesResponse",
f"<DescribePoliciesResult><ScalingPolicies>{members}</ScalingPolicies></DescribePoliciesResult>")
@@ -618,20 +735,40 @@ def _record_lifecycle_heartbeat(p):
# Scheduled Action
# ---------------------------------------------------------------------------
+def _scheduled_action_record(asg_name, action_name, arn, fields):
+ """A scheduled action as the store keeps it, from
+ PutScheduledUpdateGroupAction's members or an
+ AWS::AutoScaling::ScheduledAction's properties (the same PascalCase
+ names). A capacity the caller omitted is -1, which DescribeScheduledActions
+ leaves out; StartTime, EndTime and TimeZone are kept only when given."""
+ def capacity(member):
+ value = fields.get(member)
+ return -1 if value in (None, "") else int(value)
+
+ record = {
+ "ScheduledActionARN": arn,
+ "ScheduledActionName": action_name,
+ "AutoScalingGroupName": asg_name,
+ "Recurrence": fields.get("Recurrence") or "",
+ "MinSize": capacity("MinSize"),
+ "MaxSize": capacity("MaxSize"),
+ "DesiredCapacity": capacity("DesiredCapacity"),
+ }
+ for member in ("StartTime", "EndTime", "TimeZone"):
+ if fields.get(member):
+ record[member] = str(fields[member])
+ return record
+
+
def _put_scheduled_action(p):
asg_name = _p(p, "AutoScalingGroupName")
action_name = _p(p, "ScheduledActionName")
key = f"{asg_name}/{action_name}"
arn = f"arn:aws:autoscaling:{get_region()}:{get_account_id()}:scheduledUpdateGroupAction:{new_uuid()}:autoScalingGroupName/{asg_name}:scheduledActionName/{action_name}"
- _scheduled_actions[key] = {
- "ScheduledActionARN": arn,
- "ScheduledActionName": action_name,
- "AutoScalingGroupName": asg_name,
- "Recurrence": _p(p, "Recurrence") or "",
- "MinSize": int(_p(p, "MinSize") or -1),
- "MaxSize": int(_p(p, "MaxSize") or -1),
- "DesiredCapacity": int(_p(p, "DesiredCapacity") or -1),
- }
+ _scheduled_actions[key] = _scheduled_action_record(asg_name, action_name, arn, {
+ member: _p(p, member) for member in (
+ "Recurrence", "MinSize", "MaxSize", "DesiredCapacity",
+ "StartTime", "EndTime", "TimeZone")})
return _xml(200, "PutScheduledUpdateGroupActionResponse", "<PutScheduledUpdateGroupActionResult/>")
@@ -641,11 +778,29 @@ def _describe_scheduled_actions(p):
for key, sa in _scheduled_actions.items():
if asg_name and sa["AutoScalingGroupName"] != asg_name:
continue
+ # Recurrence and the three capacity members are what the action is
+ # for, and PutScheduledUpdateGroupAction stores all four; leaving them
+ # out of the response made a scheduled action's whole payload
+ # unreadable. The capacities carry -1 when the caller omitted them,
+ # and AWS leaves an omitted one out rather than answering -1.
members += (f"<member>"
f"<ScheduledActionARN>{sa['ScheduledActionARN']}</ScheduledActionARN>"
f"<ScheduledActionName>{sa['ScheduledActionName']}</ScheduledActionName>"
f"<AutoScalingGroupName>{sa['AutoScalingGroupName']}</AutoScalingGroupName>"
- f"</member>")
+ f"<Recurrence>{escape(sa.get('Recurrence', ''))}</Recurrence>")
+ for member in ("MinSize", "MaxSize", "DesiredCapacity"):
+ value = sa.get(member, -1)
+ if value is not None and int(value) >= 0:
+ members += f"<{member}>{int(value)}</{member}>"
+ # AWS answers StartTime twice, the second time as the deprecated Time
+ # (measured 2026-09-21).
+ if sa.get("StartTime"):
+ members += (f"<StartTime>{escape(sa['StartTime'])}</StartTime>"
+ f"<Time>{escape(sa['StartTime'])}</Time>")
+ for member in ("EndTime", "TimeZone"):
+ if sa.get(member):
+ members += f"<{member}>{escape(sa[member])}</{member}>"
+ members += "</member>"
return _xml(200, "DescribeScheduledActionsResponse",
f"<DescribeScheduledActionsResult><ScheduledUpdateGroupActions>{members}</ScheduledUpdateGroupActions></DescribeScheduledActionsResult>")
diff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.py
index 30485123..588a43fe 100644
--- a/ministack/services/cloudformation/changesets.py
+++ b/ministack/services/cloudformation/changesets.py
@@ -729,6 +729,9 @@ def _execute_change_set(params):
"_template_body": stack.get("_template_body", ""),
"_resolved_params": copy.deepcopy(stack.get("_resolved_params", {})),
"_conditions": copy.deepcopy(stack.get("_conditions", {})),
+ # A rollback restores what DescribeStacks reports, parameters
+ # included, as the UpdateStack snapshot does.
+ "Parameters": copy.deepcopy(stack.get("Parameters", [])),
"Tags": copy.deepcopy(stack.get("Tags", [])),
"Outputs": copy.deepcopy(stack.get("Outputs", [])),
}
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 04f6b3ba..999467a7 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -948,6 +948,7 @@ _STACK_TAG_PROPERTY: dict[str, tuple[str, str]] = {
"AWS::AppConfig::Deployment": ("Tags", "list"),
"AWS::AppConfig::DeploymentStrategy": ("Tags", "list"),
"AWS::AppConfig::Environment": ("Tags", "list"),
+ "AWS::AppSync::GraphQLApi": ("Tags", "list"),
"AWS::AutoScaling::AutoScalingGroup": ("Tags", "list"),
"AWS::Backup::BackupPlan": ("BackupPlanTags", "map"),
"AWS::Backup::BackupVault": ("BackupVaultTags", "map"),
@@ -959,6 +960,11 @@ _STACK_TAG_PROPERTY: dict[str, tuple[str, str]] = {
"AWS::Cognito::IdentityPool": ("IdentityPoolTags", "map"),
"AWS::Cognito::UserPool": ("UserPoolTags", "map"),
"AWS::DynamoDB::Table": ("Tags", "list"),
+ "AWS::EC2::InternetGateway": ("Tags", "list"),
+ "AWS::EC2::RouteTable": ("Tags", "list"),
+ "AWS::EC2::SecurityGroup": ("Tags", "list"),
+ "AWS::EC2::Subnet": ("Tags", "list"),
+ "AWS::EC2::VPC": ("Tags", "list"),
"AWS::EC2::VPCEndpoint": ("Tags", "list"),
"AWS::ECR::Repository": ("Tags", "list"),
"AWS::ECS::Cluster": ("Tags", "list"),
@@ -2657,6 +2663,15 @@ def _ssm_delete(physical_id, props):
# --- AppConfig Application ---
+def _appconfig_reconcile_tags(arn, old_props, new_props):
+ """AppConfig keeps tags in a per-ARN map beside the record rather than on
+ it, so the shared reconcile runs against that map. Tags set through
+ TagResource stay, as they do on AWS."""
+ if not old_props.get("Tags") and not new_props.get("Tags"):
+ return
+ _reconcile_tag_map(_appconfig._tags.setdefault(arn, {}), old_props, new_props)
+
+
def _appconfig_application_create(logical_id, props, stack_name):
name = props.get("Name") or _physical_name(stack_name, logical_id)
app_id = _appconfig._gen_id()
@@ -2674,6 +2689,27 @@ def _appconfig_application_create(logical_id, props, stack_name):
return app_id, {"ApplicationId": app_id}
+def _appconfig_application_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update an application in place. Description, Name and Tags are each
+ No interruption on the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-appconfig-application.html),
+ and the type declares no replacing property at all: Ref answers the
+ generated application id, which no update changes. Without this the
+ create-fallback minted a second application and orphaned the first,
+ taking its environments and configuration profiles with it (they are
+ keyed by the old id)."""
+ app = _appconfig._applications.get(physical_id)
+ if app is None:
+ return _appconfig_application_create(
+ logical_id or physical_id, new_props, stack_name)
+ if new_props.get("Name"):
+ app["Name"] = new_props["Name"]
+ app["Description"] = new_props.get("Description", "")
+ _appconfig_reconcile_tags(_appconfig._app_arn(physical_id), old_props, new_props)
+ return physical_id, {"ApplicationId": physical_id}
+
+
def _appconfig_application_delete(physical_id, props):
_appconfig._applications.pop(physical_id, None)
_appconfig._tags.pop(_appconfig._app_arn(physical_id), None)
@@ -2706,6 +2742,39 @@ def _appconfig_environment_create(logical_id, props, stack_name):
return env_id, {"EnvironmentId": env_id}
+def _appconfig_environment_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update an environment in place. DeletionProtectionCheck, Description,
+ Monitors, Name and Tags are No interruption on the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-appconfig-environment.html);
+ ApplicationId is Replacement, and the environment moves to the other
+ application under a freshly generated id. State belongs to the service,
+ not the template, so a replacement re-reads it and an in-place update
+ leaves it alone."""
+ app_id = new_props.get("ApplicationId", "")
+ # Keyed by the OLD application id: under a changed ApplicationId the new
+ # key holds nothing, and _rename_replacement would then read the record as
+ # gone and create the replacement without deleting the predecessor.
+ env = _appconfig._environments.get(
+ f"{old_props.get('ApplicationId', '')}/{physical_id}")
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ app_id, env["ApplicationId"] if env else None,
+ _appconfig_environment_create, _appconfig_environment_delete,
+ )
+ if replaced is not None:
+ return replaced
+ if new_props.get("Name"):
+ env["Name"] = new_props["Name"]
+ env["Description"] = new_props.get("Description", "")
+ env["Monitors"] = new_props.get("Monitors", [])
+ env["DeletionProtectionCheck"] = new_props.get(
+ "DeletionProtectionCheck", "ACCOUNT_DEFAULT")
+ _appconfig_reconcile_tags(
+ _appconfig._env_arn(app_id, physical_id), old_props, new_props)
+ return physical_id, {"EnvironmentId": physical_id}
+
+
def _appconfig_environment_delete(physical_id, props):
app_id = props.get("ApplicationId", "")
_appconfig._environments.pop(f"{app_id}/{physical_id}", None)
@@ -2747,6 +2816,48 @@ def _appconfig_configuration_profile_create(logical_id, props, stack_name):
}
+def _appconfig_configuration_profile_update(physical_id, old_props, new_props,
+ stack_name, logical_id=None):
+ """Update a configuration profile in place. DeletionProtectionCheck,
+ Description, KmsKeyIdentifier, Name, RetrievalRoleArn, Tags and Validators
+ are No interruption on the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-appconfig-configurationprofile.html);
+ ApplicationId, LocationUri and Type are Replacement, so the three are read
+ as one key. The create-fallback re-created the profile under a new id and
+ left every hosted configuration version behind it (they are keyed by
+ application and profile id)."""
+ app_id = new_props.get("ApplicationId", "")
+ # The old key, for the same reason the environment handler uses it.
+ profile = _appconfig._config_profiles.get(
+ f"{old_props.get('ApplicationId', '')}/{physical_id}")
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ (app_id,
+ new_props.get("LocationUri", "hosted"),
+ new_props.get("Type", "AWS.Freeform")),
+ (profile["ApplicationId"], profile["LocationUri"], profile["Type"])
+ if profile else None,
+ _appconfig_configuration_profile_create,
+ _appconfig_configuration_profile_delete,
+ )
+ if replaced is not None:
+ return replaced
+ if new_props.get("Name"):
+ profile["Name"] = new_props["Name"]
+ profile["Description"] = new_props.get("Description", "")
+ profile["RetrievalRoleArn"] = new_props.get("RetrievalRoleArn", "")
+ profile["Validators"] = new_props.get("Validators", [])
+ profile["KmsKeyIdentifier"] = new_props.get("KmsKeyIdentifier", "")
+ profile["DeletionProtectionCheck"] = new_props.get(
+ "DeletionProtectionCheck", "ACCOUNT_DEFAULT")
+ _appconfig_reconcile_tags(
+ _appconfig._profile_arn(app_id, physical_id), old_props, new_props)
+ return physical_id, {
+ "ConfigurationProfileId": physical_id,
+ "KmsKeyArn": new_props.get("KmsKeyIdentifier", ""),
+ }
+
+
def _appconfig_configuration_profile_delete(physical_id, props):
app_id = props.get("ApplicationId", "")
_appconfig._config_profiles.pop(f"{app_id}/{physical_id}", None)
@@ -2827,6 +2938,38 @@ def _appconfig_deployment_strategy_create(logical_id, props, stack_name):
return strategy_id, {"Id": strategy_id}
+def _appconfig_deployment_strategy_update(physical_id, old_props, new_props,
+ stack_name, logical_id=None):
+ """Update a deployment strategy in place. DeploymentDurationInMinutes,
+ Description, FinalBakeTimeInMinutes, GrowthFactor, GrowthType and Tags are
+ No interruption on the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-appconfig-deploymentstrategy.html);
+ Name and ReplicateTo are Replacement, and both are read as one key. The
+ name is not the physical id here (Ref answers the generated strategy id),
+ so a rename is a plain replacement with nothing to refuse."""
+ strategy = _appconfig._deployment_strategies.get(physical_id)
+ name = new_props.get("Name") or _physical_name(
+ stack_name, logical_id or physical_id, max_len=64)
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ (name, new_props.get("ReplicateTo", "NONE")),
+ (strategy["Name"], strategy["ReplicateTo"]) if strategy else None,
+ _appconfig_deployment_strategy_create,
+ _appconfig_deployment_strategy_delete,
+ )
+ if replaced is not None:
+ return replaced
+ strategy["Description"] = new_props.get("Description", "")
+ strategy["DeploymentDurationInMinutes"] = new_props.get(
+ "DeploymentDurationInMinutes", 0)
+ strategy["GrowthType"] = new_props.get("GrowthType", "LINEAR")
+ strategy["GrowthFactor"] = new_props.get("GrowthFactor", 100.0)
+ strategy["FinalBakeTimeInMinutes"] = new_props.get("FinalBakeTimeInMinutes", 0)
+ _appconfig_reconcile_tags(
+ _appconfig._strategy_arn(physical_id), old_props, new_props)
+ return physical_id, {"Id": physical_id}
+
+
def _appconfig_deployment_strategy_delete(physical_id, props):
_appconfig._deployment_strategies.pop(physical_id, None)
_appconfig._tags.pop(_appconfig._strategy_arn(physical_id), None)
@@ -5469,21 +5612,75 @@ def _sns_topic_policy_delete(physical_id, props):
# --- AppSync resource provisioners ---
+# The GraphQLApi members that map one to one onto a camelCase API member and
+# are absent from the API when the template does not set them.
+_APPSYNC_API_OPTIONAL = (
+ "AdditionalAuthenticationProviders", "EnhancedMetricsConfig",
+ "LambdaAuthorizerConfig", "LogConfig", "MergedApiExecutionRoleArn",
+ "OpenIDConnectConfig", "OwnerContact", "UserPoolConfig",
+)
+
+
+def _appsync_api_members(props):
+ """A GraphQLApi's properties as the API record's members. The scalar
+ members take AppSync's defaults when the template leaves them out, which
+ is what GetGraphqlApi answers on AWS for an API created without them, and
+ after an update that removed them (measured 2026-09-21); the others are
+ set only when present. AppSync is rest-json, so a nested member is stored
+ in the API's camelCase: kept in the template's PascalCase, botocore reads
+ [{}]."""
+ members = {
+ "authenticationType": props.get("AuthenticationType", "API_KEY"),
+ "xrayEnabled": str(props.get("XrayEnabled", False)).lower() == "true",
+ "apiType": props.get("ApiType", "GRAPHQL"),
+ "visibility": props.get("Visibility", "GLOBAL"),
+ "introspectionConfig": props.get("IntrospectionConfig", "ENABLED"),
+ "queryDepthLimit": int(props.get("QueryDepthLimit", 0)),
+ "resolverCountLimit": int(props.get("ResolverCountLimit", 0)),
+ }
+ for prop in _APPSYNC_API_OPTIONAL:
+ if props.get(prop) not in (None, "", [], {}):
+ members[prop[:1].lower() + prop[1:]] = _pascal_to_camel(props[prop])
+ oidc = members.get("openIDConnectConfig")
+ if oidc is not None:
+ # AppSync answers both TTLs, 0 when unset (measured 2026-09-21).
+ oidc.setdefault("authTTL", 0)
+ oidc.setdefault("iatTTL", 0)
+ # A map of the caller's own names: its keys are not converted.
+ if props.get("EnvironmentVariables"):
+ members["environmentVariables"] = dict(props["EnvironmentVariables"])
+ return members
+
+
+def _appsync_api_tags(props):
+ """The tags AppSync lists for the API: the template's and the stack-level
+ ones, without the aws:cloudformation:* tags, which AppSync does not list
+ on an API CloudFormation created (measured 2026-09-21)."""
+ return {"Tags": [t for t in (props.get("Tags") or [])
+ if isinstance(t, dict) and not str(t.get("Key", "")).startswith("aws:")]}
+
+
def _appsync_api_create(logical_id, props, stack_name):
import time as _time
name = props.get("Name") or _physical_name(stack_name, logical_id)
- auth_type = props.get("AuthenticationType", "API_KEY")
- api_id = new_uuid()[:8]
+ # The id shape CreateGraphqlApi mints; eight characters made an ARN that
+ # botocore refuses as too short for ListTagsForResource.
+ api_id = new_uuid().replace("-", "")[:26]
arn = f"arn:aws:appsync:{get_region()}:{get_account_id()}:apis/{api_id}"
now = _time.time()
_appsync._apis[api_id] = {
- "apiId": api_id, "name": name, "authenticationType": auth_type,
+ "apiId": api_id, "name": name,
"arn": arn,
- "uris": {"GRAPHQL": f"https://{api_id}.appsync-api.{get_region()}.amazonaws.com/graphql"},
+ "uris": {
+ "GRAPHQL": f"https://{api_id}.appsync-api.{get_region()}.amazonaws.com/graphql",
+ "REALTIME": f"wss://{api_id}.appsync-realtime-api.{get_region()}.amazonaws.com/graphql",
+ },
"createdAt": now, "lastUpdatedAt": now,
- "additionalAuthenticationProviders": props.get("AdditionalAuthenticationProviders", []),
- "xrayEnabled": False,
+ **_appsync_api_members(props),
}
+ tags = _tag_map(_appsync_api_tags(props)["Tags"])
+ if tags:
+ _appsync._tags[arn] = tags
_appsync._api_keys[api_id] = {}
_appsync._data_sources[api_id] = {}
_appsync._resolvers[api_id] = {}
@@ -5491,6 +5688,49 @@ def _appsync_api_create(logical_id, props, stack_name):
return api_id, {"ApiId": api_id, "Arn": arn, "GraphQLUrl": f"https://{api_id}.appsync-api.{get_region()}.amazonaws.com/graphql"}
+def _appsync_api_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update a GraphQL API in place. Every property of the type is No
+ interruption on the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-appsync-graphqlapi.html),
+ so the API is never replaced and keeps its id, ARN and endpoint URLs.
+ Visibility is the exception the page does not state: AWS fails the update
+ with the handler's message (measured 2026-09-21). An OpenIDConnectConfig
+ ClientId or Issuer change is in place (the registry lists the nested
+ members as conditionally create-only; measured the same day), and a
+ member the template removes goes back to its default or away.
+
+ This is the worst of the create-fallbacks: the create mints a new api id
+ AND re-seeds _api_keys, _data_sources, _resolvers and _types for it, so a
+ renamed API came back empty while the real one was orphaned under the old
+ id, still holding every child the stack had provisioned."""
+ import time as _time
+ api = _appsync._apis.get(physical_id)
+ if api is None:
+ return _appsync_api_create(logical_id or physical_id, new_props, stack_name)
+ members = _appsync_api_members(new_props)
+ if members["visibility"] != api.get("visibility", "GLOBAL"):
+ raise ValueError(
+ "Property Visibility can only be set when creating a GraphQL API. "
+ "Rename the resource to force a replacement")
+ if new_props.get("Name"):
+ api["name"] = new_props["Name"]
+ # UpdateGraphqlApi has no apiType member; a change is not applied.
+ members.pop("apiType")
+ for prop in (*_APPSYNC_API_OPTIONAL, "EnvironmentVariables"):
+ api.pop(prop[:1].lower() + prop[1:], None)
+ api.update(members)
+ tags = _appsync._tags.setdefault(api["arn"], {})
+ _reconcile_tag_map(tags, _appsync_api_tags(old_props), _appsync_api_tags(new_props))
+ if not tags:
+ _appsync._tags.pop(api["arn"], None)
+ api["lastUpdatedAt"] = _time.time()
+ return physical_id, {
+ "ApiId": physical_id,
+ "Arn": api["arn"],
+ "GraphQLUrl": api["uris"]["GRAPHQL"],
+ }
+
+
def _appsync_api_delete(physical_id, props):
# Route through the service's own delete so every child store the API owns
# — functions, schema, cache, cache entries, tags, the built-schema cache —
@@ -5616,13 +5856,46 @@ def _appsync_apikey_create(logical_id, props, stack_name):
import time
key = {
"id": key_id, "apiKeyId": key_id,
+ # description and createdAt are part of the record CreateApiKey
+ # writes, so ListApiKeys answered a stunted one for a key the
+ # template had created, and a Description change was unobservable.
+ "description": props.get("Description", ""),
"expires": props.get("Expires", int(time.time()) + 604800),
+ "createdAt": int(time.time()),
}
_appsync._api_keys.setdefault(api_id, {})[key_id] = key
return key_id, {"ApiKeyId": key_id, "ApiKey": key_id,
"Arn": f"arn:aws:appsync:{get_region()}:{get_account_id()}:apis/{api_id}/apikeys/{key_id}"}
+def _appsync_apikey_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update an API key in place. Description and Expires are No interruption
+ on the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-appsync-apikey.html);
+ ApiId is Replacement.
+
+ The create mints a fresh key id, so under the fallback every expiry change
+ handed clients a new key and left the previous one valid on the API."""
+ import time
+ api_id = new_props.get("ApiId", "")
+ old_api_id = old_props.get("ApiId", "")
+ key = _appsync._api_keys.get(old_api_id, {}).get(physical_id)
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ api_id, old_api_id if key else None,
+ _appsync_apikey_create, _appsync_apikey_delete,
+ )
+ if replaced is not None:
+ return replaced
+ key["description"] = new_props.get("Description", "")
+ key["expires"] = new_props.get("Expires", int(time.time()) + 604800)
+ return physical_id, {
+ "ApiKeyId": physical_id, "ApiKey": physical_id,
+ "Arn": f"arn:aws:appsync:{get_region()}:{get_account_id()}:apis/{api_id}/apikeys/{physical_id}",
+ }
+
+
def _appsync_apikey_delete(physical_id, props):
api_id = props.get("ApiId", "")
_appsync._api_keys.get(api_id, {}).pop(physical_id, None)
@@ -6660,6 +6933,40 @@ def _kms_alias_delete(physical_id, props):
# --- EC2 resource provisioners ---
+def _ec2_apply_tags(physical_id, props, old_props=None):
+ """The template's tags in the EC2 tag store, which is what every EC2
+ Describe renders through ``_tag_set_xml``. The networking provisioners
+ never wrote it, so no tag a template declared on a VPC, subnet, security
+ group, gateway or route table was readable at all.
+
+ An update passes ``old_props``: the change is reconciled, so a tag added
+ through CreateTags survives a template tag change, as on AWS (measured
+ 2026-09-21 on a VPC)."""
+ tags = list(_ec2._tags.get(physical_id) or [])
+ _reconcile_tag_list(tags, old_props or {}, props)
+ if tags:
+ _ec2._tags[physical_id] = tags
+ else:
+ _ec2._tags.pop(physical_id, None)
+
+
+def _ec2_vpc_dns_attributes(vpc, props, reset_absent=False):
+ """EnableDnsSupport and EnableDnsHostnames on the record, in the shape
+ ModifyVpcAttribute writes and DescribeVpcAttribute reads. The create never
+ read either, so a template that set them was ignored.
+
+ With ``reset_absent`` (an update), a property the template no longer sets
+ goes back to the default DescribeVpcAttribute reads, support on and
+ hostnames off, which is what AWS does (measured 2026-09-21: a removed
+ EnableDnsHostnames reads false, a removed EnableDnsSupport true)."""
+ for prop in ("EnableDnsSupport", "EnableDnsHostnames"):
+ if prop in props:
+ value = props[prop]
+ vpc[prop] = value if isinstance(value, bool) else str(value).lower() == "true"
+ elif reset_absent:
+ vpc.pop(prop, None)
+
+
def _ec2_vpc_create(logical_id, props, stack_name):
import random
import string
@@ -6698,12 +7005,75 @@ def _ec2_vpc_create(logical_id, props, stack_name):
"OwnerId": get_account_id(), "DefaultNetworkAclId": acl_id,
"DefaultSecurityGroupId": sg_id, "MainRouteTableId": rtb_id,
}
+ _ec2_vpc_dns_attributes(_ec2._vpcs[vpc_id], props)
+ _ec2_apply_tags(vpc_id, props)
arn = f"arn:aws:ec2:{get_region()}:{get_account_id()}:vpc/{vpc_id}"
return vpc_id, {"VpcId": vpc_id, "DefaultSecurityGroup": sg_id, "DefaultNetworkAcl": acl_id}
+# Create-only on AWS::EC2::VPC beside CidrBlock (the registry's
+# createOnlyProperties); the create does not model them.
+_EC2_VPC_CREATE_ONLY = ("Ipv4IpamPoolId", "Ipv4NetmaskLength", "VpcEncryptionControl")
+
+
+def _ec2_vpc_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update a VPC in place. EnableDnsSupport, EnableDnsHostnames and Tags are
+ No interruption on the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html);
+ CidrBlock, Ipv4IpamPoolId, Ipv4NetmaskLength and VpcEncryptionControl are
+ Replacement. InstanceTenancy is "Some interruptions", and the page is
+ explicit about the direction: dedicated to default is in place, default to
+ dedicated replaces.
+
+ The create mints a new vpc- id AND writes a default security group, main
+ route table and network ACL, none of which the delete removed, so every
+ property change left all three behind pointing at a VPC id nothing claims.
+ """
+ vpc = _ec2._vpcs.get(physical_id)
+ tenancy = new_props.get("InstanceTenancy", "default")
+ replaces_tenancy = (
+ old_props.get("InstanceTenancy", "default") == "default"
+ and tenancy == "dedicated"
+ )
+ # The record keeps none of the three create-only IPAM and encryption
+ # members, so they compare template to template.
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ (new_props.get("CidrBlock", "10.0.0.0/16"), replaces_tenancy,
+ *(new_props.get(p) for p in _EC2_VPC_CREATE_ONLY)),
+ (vpc["CidrBlock"], False, *(old_props.get(p) for p in _EC2_VPC_CREATE_ONLY))
+ if vpc else None,
+ _ec2_vpc_create, _ec2_vpc_delete,
+ )
+ if replaced is not None:
+ return replaced
+ vpc["InstanceTenancy"] = tenancy
+ _ec2_vpc_dns_attributes(vpc, new_props, reset_absent=True)
+ _ec2_apply_tags(physical_id, new_props, old_props)
+ return physical_id, {
+ "VpcId": physical_id,
+ "DefaultSecurityGroup": vpc.get("DefaultSecurityGroupId", ""),
+ "DefaultNetworkAcl": vpc.get("DefaultNetworkAclId", ""),
+ }
+
+
def _ec2_vpc_delete(physical_id, props):
- _ec2._vpcs.pop(physical_id, None)
+ # Go through DeleteVpc: it removes the default security group, main route
+ # table and network ACL the create writes (popping only the VPC left all
+ # three behind for good), and it refuses with DependencyViolation while
+ # something made outside the stack still lives in the VPC, as AWS does.
+ children = [
+ child_id
+ for store in (_ec2._security_groups, _ec2._route_tables, _ec2._network_acls)
+ for child_id, child in store.items()
+ if child.get("VpcId") == physical_id
+ ]
+ status, _headers, body = _ec2._delete_vpc({"VpcId": [physical_id]})
+ if status >= 400 and b"InvalidVpcID.NotFound" not in body:
+ raise ValueError(f"AWS::EC2::VPC delete failed: {body!r}")
+ for child_id in children:
+ _ec2._tags.pop(child_id, None)
+ _ec2._tags.pop(physical_id, None)
def _ec2_vpc_endpoint_attributes(endpoint):
@@ -6775,10 +7145,53 @@ def _ec2_vpc_endpoint_delete(physical_id, props):
_ec2._tags.pop(physical_id, None)
+# Create-only on AWS::EC2::Subnet beside VpcId, CidrBlock and the zone (the
+# registry's createOnlyProperties); the record keeps none of them.
+_EC2_SUBNET_CREATE_ONLY = (
+ "Ipv4IpamPoolId", "Ipv4NetmaskLength", "Ipv6IpamPoolId", "Ipv6Native",
+ "Ipv6NetmaskLength", "OutpostArn",
+)
+
+
+def _ec2_subnet_zone(props):
+ """The subnet's zone name: AvailabilityZone, or the zone AvailabilityZoneId
+ names, as CreateSubnet resolves it; the create ignored the id."""
+ if props.get("AvailabilityZone"):
+ return props["AvailabilityZone"]
+ if props.get("AvailabilityZoneId"):
+ zone = _ec2._zone_name_for_az_id(props["AvailabilityZoneId"])
+ if zone:
+ return zone
+ return f"{get_region()}a"
+
+
+def _ec2_subnet_attributes(subnet, props):
+ """PrivateDnsNameOptionsOnLaunch and EnableDns64 onto the record, in the
+ shape DescribeSubnets renders. Only the members the template sets are
+ written: AWS keeps a removed one as it is (measured 2026-09-21, as for
+ MapPublicIpOnLaunch). EnableDns64 needs an IPv6 block, which no subnet
+ here has; AWS fails the operation with the handler's message."""
+ if str(props.get("EnableDns64", False)).lower() == "true" and not (
+ props.get("Ipv6CidrBlock") or props.get("Ipv6IpamPoolId")):
+ raise ValueError("Invalid request provided: Property Ipv6CidrBlock or "
+ "Ipv6IpamPoolId cannot be empty.")
+ if "EnableDns64" in props:
+ subnet["EnableDns64"] = str(props["EnableDns64"]).lower() == "true"
+ options = props.get("PrivateDnsNameOptionsOnLaunch")
+ if isinstance(options, dict):
+ current = dict(_ec2._subnet_dns_name_options(subnet))
+ if "HostnameType" in options:
+ current["HostnameType"] = options["HostnameType"]
+ for member in ("EnableResourceNameDnsARecord", "EnableResourceNameDnsAAAARecord"):
+ if member in options:
+ current[member] = str(options[member]).lower() == "true"
+ subnet["PrivateDnsNameOptionsOnLaunch"] = current
+
+
def _ec2_subnet_create(logical_id, props, stack_name):
vpc_id = props.get("VpcId", "")
cidr = props.get("CidrBlock", "10.0.1.0/24")
- az = props.get("AvailabilityZone", f"{get_region()}a")
+ az = _ec2_subnet_zone(props)
subnet_id = _ec2._new_subnet_id()
_ec2._subnets[subnet_id] = {
"SubnetId": subnet_id,
@@ -6789,14 +7202,69 @@ def _ec2_subnet_create(logical_id, props, stack_name):
"State": "available",
"AvailableIpAddressCount": 251,
"DefaultForAz": False,
- "MapPublicIpOnLaunch": props.get("MapPublicIpOnLaunch", False),
+ "MapPublicIpOnLaunch": _ec2_subnet_public_ip(props),
"OwnerId": get_account_id(),
}
+ try:
+ _ec2_subnet_attributes(_ec2._subnets[subnet_id], props)
+ except ValueError:
+ _ec2._subnets.pop(subnet_id, None)
+ raise
+ _ec2_apply_tags(subnet_id, props)
return subnet_id, {"SubnetId": subnet_id, "AvailabilityZone": az}
+def _ec2_subnet_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update a subnet in place. AssignIpv6AddressOnCreation, EnableDns64,
+ EnableLniAtDeviceIndex, MapPublicIpOnLaunch, PrivateDnsNameOptionsOnLaunch
+ and Tags are No interruption on the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html);
+ VpcId, CidrBlock, the zone (by name or id), the IPAM members, Ipv6Native
+ and OutpostArn are Replacement (the registry's createOnlyProperties) and
+ are read as one key.
+
+ The create mints a new subnet- id, so the fallback replaced the subnet and
+ left every instance, network interface, NAT gateway and load balancer
+ subnet list holding an id that no longer resolves."""
+ subnet = _ec2._subnets.get(physical_id)
+ key = (new_props.get("VpcId", ""),
+ new_props.get("CidrBlock", "10.0.1.0/24"),
+ _ec2_subnet_zone(new_props),
+ *(new_props.get(p) for p in _EC2_SUBNET_CREATE_ONLY))
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ key,
+ (subnet["VpcId"], subnet["CidrBlock"], subnet["AvailabilityZone"],
+ *(old_props.get(p) for p in _EC2_SUBNET_CREATE_ONLY))
+ if subnet else None,
+ _ec2_subnet_create, _ec2_subnet_delete,
+ )
+ if replaced is not None:
+ return replaced
+ # A template that stops setting one of these leaves the attribute as it
+ # is: on AWS a removed MapPublicIpOnLaunch keeps reading true, and so does
+ # a removed PrivateDnsNameOptionsOnLaunch (measured 2026-09-21), unlike a
+ # VPC's DNS attributes. AssignIpv6AddressOnCreation and
+ # EnableLniAtDeviceIndex have nothing to act on without an IPv6 block or
+ # an Outpost, neither of which is modelled.
+ _ec2_subnet_attributes(subnet, new_props)
+ if "MapPublicIpOnLaunch" in new_props:
+ subnet["MapPublicIpOnLaunch"] = _ec2_subnet_public_ip(new_props)
+ _ec2_apply_tags(physical_id, new_props, old_props)
+ return physical_id, {"SubnetId": physical_id,
+ "AvailabilityZone": subnet["AvailabilityZone"]}
+
+
+def _ec2_subnet_public_ip(props):
+ """MapPublicIpOnLaunch as a boolean: DescribeSubnets renders the record's
+ truthiness, so a YAML template's string "false" read back as true."""
+ value = props.get("MapPublicIpOnLaunch", False)
+ return value if isinstance(value, bool) else str(value).lower() == "true"
+
+
def _ec2_subnet_delete(physical_id, props):
_ec2._subnets.pop(physical_id, None)
+ _ec2._tags.pop(physical_id, None)
def _ec2_sg_create(logical_id, props, stack_name):
@@ -6811,14 +7279,24 @@ def _ec2_sg_create(logical_id, props, stack_name):
"Description": desc,
"VpcId": vpc_id,
"OwnerId": get_account_id(),
- "IpPermissions": [],
- "IpPermissionsEgress": [
- {"IpProtocol": "-1", "IpRanges": [{"CidrIp": "0.0.0.0/0"}],
- "Ipv6Ranges": [], "PrefixListIds": [], "UserIdGroupPairs": []},
- ],
+ "IpPermissions": _ec2_sg_permissions(props.get("SecurityGroupIngress")),
+ "IpPermissionsEgress": _ec2_sg_egress_permissions(props.get("SecurityGroupEgress")),
}
- # Apply ingress rules from props
- for rule in props.get("SecurityGroupIngress", []):
+ _ec2_apply_tags(sg_id, props)
+ arn = f"arn:aws:ec2:{get_region()}:{get_account_id()}:security-group/{sg_id}"
+ return sg_id, {"GroupId": sg_id, "VpcId": vpc_id, "Arn": arn}
+
+
+def _ec2_sg_permissions(rules):
+ """A template's ingress or egress rules in the shape the EC2 store keeps
+ and DescribeSecurityGroups renders, each source with the rule's
+ Description. A prefix-list source (SourcePrefixListId, and
+ DestinationPrefixListId on egress) and a source group's name and owner are
+ rule members too; dropping them lost a prefix-list rule outright."""
+ permissions = []
+ for rule in (rules or []):
+ if not isinstance(rule, dict):
+ continue
perm = {
"IpProtocol": rule.get("IpProtocol", "tcp"),
"IpRanges": [],
@@ -6830,32 +7308,143 @@ def _ec2_sg_create(logical_id, props, stack_name):
perm["FromPort"] = int(rule["FromPort"])
if "ToPort" in rule:
perm["ToPort"] = int(rule["ToPort"])
+ described = {"Description": rule["Description"]} if rule.get("Description") else {}
if "CidrIp" in rule:
- perm["IpRanges"].append({"CidrIp": rule["CidrIp"]})
- _ec2._security_groups[sg_id]["IpPermissions"].append(perm)
+ perm["IpRanges"].append({"CidrIp": rule["CidrIp"], **described})
+ if "CidrIpv6" in rule:
+ perm["Ipv6Ranges"].append({"CidrIpv6": rule["CidrIpv6"], **described})
+ prefix_list = rule.get("SourcePrefixListId") or rule.get("DestinationPrefixListId")
+ if prefix_list:
+ perm["PrefixListIds"].append({"PrefixListId": prefix_list, **described})
+ group_id = rule.get("SourceSecurityGroupId") or rule.get("DestinationSecurityGroupId")
+ group_name = rule.get("SourceSecurityGroupName")
+ if group_id or group_name:
+ pair = {"GroupId": group_id} if group_id else {"GroupName": group_name}
+ if group_id and group_name:
+ pair["GroupName"] = group_name
+ if rule.get("SourceSecurityGroupOwnerId"):
+ pair["UserId"] = str(rule["SourceSecurityGroupOwnerId"])
+ perm["UserIdGroupPairs"].append({**pair, **described})
+ permissions.append(perm)
+ return permissions
+
+
+def _ec2_sg_egress_permissions(rules):
+ """The egress a create gives a group from its SecurityGroupEgress: the
+ template's own rules, or the allow-all rule AWS adds when it declares
+ none (the create used to hard-code allow-all and drop the template's
+ egress entirely)."""
+ return _ec2_sg_permissions(rules) or [
+ {"IpProtocol": "-1", "IpRanges": [{"CidrIp": "0.0.0.0/0"}],
+ "Ipv6Ranges": [], "PrefixListIds": [], "UserIdGroupPairs": []},
+ ]
- arn = f"arn:aws:ec2:{get_region()}:{get_account_id()}:security-group/{sg_id}"
- return sg_id, {"GroupId": sg_id, "VpcId": vpc_id, "Arn": arn}
+
+def _ec2_sg_permission_key(perm):
+ """A permission reduced to what identifies it, its protocol, ports and
+ sources, so the same rule declared twice compares equal whatever its
+ description."""
+ return (
+ perm.get("IpProtocol"),
+ perm.get("FromPort"),
+ perm.get("ToPort"),
+ tuple(sorted(r.get("CidrIp", "") for r in perm.get("IpRanges", []))),
+ tuple(sorted(r.get("CidrIpv6", "") for r in perm.get("Ipv6Ranges", []))),
+ tuple(sorted(r.get("PrefixListId", "") for r in perm.get("PrefixListIds", []))),
+ tuple(sorted((p.get("GroupId", ""), p.get("GroupName", ""), p.get("UserId", ""))
+ for p in perm.get("UserIdGroupPairs", []))),
+ )
+
+
+def _ec2_sg_reconcile(store, old_perms, new_perms):
+ """Apply a rule-property change the way the tag reconcilers apply a tag
+ change: rules the template dropped are revoked, the new ones authorized,
+ a rule whose description changed is replaced by its new form, and a rule
+ added through AuthorizeSecurityGroupIngress/Egress outside the template is
+ left alone, as it is on AWS. Both sides are what the create would write
+ for that template, so the allow-all egress rule comes and goes with the
+ template's own egress rules."""
+ if old_perms == new_perms:
+ return
+ keys = ({_ec2_sg_permission_key(p) for p in old_perms}
+ | {_ec2_sg_permission_key(p) for p in new_perms})
+ store[:] = [p for p in store if _ec2_sg_permission_key(p) not in keys] + new_perms
+
+
+def _ec2_sg_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update a security group in place. SecurityGroupIngress and
+ SecurityGroupEgress are "Some interruptions" on the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-securitygroup.html),
+ which is an in-place update, and Tags is No interruption; GroupDescription,
+ GroupName and VpcId are Replacement and are read as one key.
+
+ The create mints a new sg- id, so the fallback replaced the group and took
+ every rule authorized outside the template with it, while each instance
+ still held the old group id."""
+ _ec2._ensure_defaults_initialized()
+ group = _ec2._security_groups.get(physical_id)
+ name = new_props.get("GroupName", f"{stack_name}-{logical_id or physical_id}")
+ key = (name,
+ new_props.get("GroupDescription", name),
+ new_props.get("VpcId", _ec2._DEFAULT_VPC_ID))
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ key,
+ (group["GroupName"], group["Description"], group["VpcId"]) if group else None,
+ _ec2_sg_create, _ec2_sg_delete,
+ )
+ if replaced is not None:
+ return replaced
+ _ec2_sg_reconcile(group.setdefault("IpPermissions", []),
+ _ec2_sg_permissions(old_props.get("SecurityGroupIngress")),
+ _ec2_sg_permissions(new_props.get("SecurityGroupIngress")))
+ if old_props.get("SecurityGroupEgress") != new_props.get("SecurityGroupEgress"):
+ # Declaring egress takes the create's allow-all rule away. Dropping the
+ # declaration again does not bring it back: measured on AWS, the group
+ # is left with no egress rule from the template.
+ _ec2_sg_reconcile(group.setdefault("IpPermissionsEgress", []),
+ _ec2_sg_egress_permissions(old_props.get("SecurityGroupEgress")),
+ _ec2_sg_permissions(new_props.get("SecurityGroupEgress")))
+ _ec2_apply_tags(physical_id, new_props, old_props)
+ arn = f"arn:aws:ec2:{get_region()}:{get_account_id()}:security-group/{physical_id}"
+ return physical_id, {"GroupId": physical_id, "VpcId": group["VpcId"], "Arn": arn}
def _ec2_sg_delete(physical_id, props):
_ec2._security_groups.pop(physical_id, None)
+ _ec2._tags.pop(physical_id, None)
def _ec2_igw_create(logical_id, props, stack_name):
- import random
- import string
- igw_id = "igw-" + "".join(random.choices(string.hexdigits[:16], k=17))
+ igw_id = _ec2._new_igw_id()
_ec2._internet_gateways[igw_id] = {
"InternetGatewayId": igw_id,
"OwnerId": get_account_id(),
"Attachments": [],
}
+ _ec2_apply_tags(igw_id, props)
return igw_id, {"InternetGatewayId": igw_id}
+def _ec2_igw_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update an internet gateway in place. Tags is the only property
+ AWS::EC2::InternetGateway has and it is No interruption
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-internetgateway.html),
+ so nothing about this type can ever require a replacement.
+
+ The create ignored props entirely, so the one change a template can make
+ to a gateway minted a new igw- id, reset Attachments to empty and still
+ applied no tags."""
+ gateway = _ec2._internet_gateways.get(physical_id)
+ if gateway is None:
+ return _ec2_igw_create(logical_id or physical_id, new_props, stack_name)
+ _ec2_apply_tags(physical_id, new_props, old_props)
+ return physical_id, {"InternetGatewayId": physical_id}
+
+
def _ec2_igw_delete(physical_id, props):
_ec2._internet_gateways.pop(physical_id, None)
+ _ec2._tags.pop(physical_id, None)
def _ec2_vpc_gw_attach_create(logical_id, props, stack_name):
@@ -6892,25 +7481,116 @@ def _ec2_rtb_create(logical_id, props, stack_name):
],
"Associations": [],
}
+ _ec2_apply_tags(rtb_id, props)
return rtb_id, {"RouteTableId": rtb_id}
+def _ec2_rtb_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update a route table in place. Tags is No interruption and VpcId is
+ Replacement on the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-routetable.html).
+
+ The create mints a new rtb- id and rebuilds the record with Routes back to
+ the local route and Associations empty, so a tag change destroyed every
+ route and association added through CreateRoute or AssociateRouteTable."""
+ table = _ec2._route_tables.get(physical_id)
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ new_props.get("VpcId", _ec2._DEFAULT_VPC_ID),
+ table["VpcId"] if table else None,
+ _ec2_rtb_create, _ec2_rtb_delete,
+ )
+ if replaced is not None:
+ return replaced
+ _ec2_apply_tags(physical_id, new_props, old_props)
+ return physical_id, {"RouteTableId": physical_id}
+
+
def _ec2_rtb_delete(physical_id, props):
_ec2._route_tables.pop(physical_id, None)
+ _ec2._tags.pop(physical_id, None)
+
+
+# The route target properties, every one of them No interruption on the
+# resource reference, in the order CreateRoute resolves them.
+_EC2_ROUTE_TARGETS = (
+ "GatewayId", "NatGatewayId", "InstanceId", "NetworkInterfaceId",
+ "TransitGatewayId", "VpcPeeringConnectionId", "EgressOnlyInternetGatewayId",
+ "CarrierGatewayId", "LocalGatewayId", "VpcEndpointId", "CoreNetworkArn",
+ "OdbNetworkArn",
+)
+# The three destination properties, each create-only and each naming its own
+# route: a table holds an IPv4, an IPv6 and a prefix-list route side by side
+# (measured 2026-09-21), so the destination has to be read from the property
+# the template set, not defaulted to 0.0.0.0/0.
+_EC2_ROUTE_DESTINATIONS = (
+ "DestinationCidrBlock", "DestinationIpv6CidrBlock", "DestinationPrefixListId",
+)
+
+
+def _ec2_route_destination(props):
+ """(destination property, value) of a route's properties."""
+ for prop in _EC2_ROUTE_DESTINATIONS:
+ if props.get(prop):
+ return prop, props[prop]
+ return "DestinationCidrBlock", "0.0.0.0/0"
+
+
+def _ec2_route_record(props, dest):
+ prop, value = dest
+ route = {prop: value, "State": "active", "Origin": "CreateRoute"}
+ for target in _EC2_ROUTE_TARGETS:
+ if props.get(target):
+ route[target] = props[target]
+ break
+ return route
+
+
+def _ec2_route_put(rtb, props, dest):
+ """Put the route for ``dest`` into the table, replacing the one already
+ holding that destination rather than appending beside it."""
+ prop, value = dest
+ rtb["Routes"] = [
+ r for r in rtb["Routes"] if r.get(prop) != value
+ ] + [_ec2_route_record(props, dest)]
def _ec2_route_create(logical_id, props, stack_name):
rtb_id = props.get("RouteTableId", "")
- dest = props.get("DestinationCidrBlock", "0.0.0.0/0")
+ dest = _ec2_route_destination(props)
rtb = _ec2._route_tables.get(rtb_id)
if rtb:
- route = {"DestinationCidrBlock": dest, "State": "active", "Origin": "CreateRoute"}
- if props.get("GatewayId"):
- route["GatewayId"] = props["GatewayId"]
- elif props.get("NatGatewayId"):
- route["NatGatewayId"] = props["NatGatewayId"]
- rtb["Routes"].append(route)
- physical_id = f"{rtb_id}|{dest}"
+ # Put, not append: a route the table already holds for this
+ # destination is replaced rather than duplicated.
+ _ec2_route_put(rtb, props, dest)
+ physical_id = f"{rtb_id}|{dest[1]}"
+ return physical_id, {}
+
+
+def _ec2_route_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update a route in place. Every target property is No interruption on the
+ resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html),
+ which is what ReplaceRoute does; RouteTableId and the three destination
+ properties are Replacement, and all four are already carried by the
+ physical id "{table}|{destination}".
+
+ That deterministic id is what made this the one type in the family to
+ corrupt state rather than replace it: a changed target left the id
+ unmoved, so the engine declared no replacement and ran no predecessor
+ delete, while the create appended a second entry. The table then held two
+ routes for one destination, both rendered by DescribeRouteTables."""
+ rtb_id, _, dest_value = physical_id.partition("|")
+ dest = _ec2_route_destination(new_props)
+ if (new_props.get("RouteTableId", "") != rtb_id or dest[1] != dest_value
+ or dest != _ec2_route_destination(old_props)):
+ created = _ec2_route_create(logical_id or physical_id, new_props, stack_name)
+ _delete_predecessor(_ec2_route_delete, physical_id, old_props)
+ return created
+ rtb = _ec2._route_tables.get(rtb_id)
+ if rtb is None:
+ return _ec2_route_create(logical_id or physical_id, new_props, stack_name)
+ _ec2_route_put(rtb, new_props, dest)
return physical_id, {}
@@ -6919,7 +7599,8 @@ def _ec2_route_delete(physical_id, props):
if len(parts) == 2:
rtb = _ec2._route_tables.get(parts[0])
if rtb:
- rtb["Routes"] = [r for r in rtb["Routes"] if r.get("DestinationCidrBlock") != parts[1]]
+ rtb["Routes"] = [r for r in rtb["Routes"]
+ if all(r.get(p) != parts[1] for p in _EC2_ROUTE_DESTINATIONS)]
def _ec2_subnet_rtb_assoc_create(logical_id, props, stack_name):
@@ -6958,11 +7639,18 @@ def _ecs_cluster_create(logical_id, props, stack_name):
"runningTasksCount": 0,
"pendingTasksCount": 0,
"activeServicesCount": 0,
- "settings": props.get("ClusterSettings", []),
+ # ECS is a JSON API with camelCase members: kept in the template's
+ # PascalCase, botocore dropped every member and DescribeClusters
+ # answered [{}] for the settings and the strategy.
+ "settings": _pascal_to_camel(props.get("ClusterSettings") or []),
"capacityProviders": props.get("CapacityProviders", []),
- "defaultCapacityProviderStrategy": props.get("DefaultCapacityProviderStrategy", []),
+ "defaultCapacityProviderStrategy": _pascal_to_camel(
+ props.get("DefaultCapacityProviderStrategy") or []),
"tags": [{"key": t["Key"], "value": t["Value"]} for t in props.get("Tags", [])],
}
+ if props.get("Configuration"):
+ # Where UpdateCluster keeps it, in the same shape.
+ _ecs._clusters[name]["configuration"] = _pascal_to_camel(props["Configuration"])
return name, {"Arn": arn, "ClusterName": name}
@@ -7135,8 +7823,21 @@ def _ec2_launch_template_create(logical_id, props, stack_name):
"DefaultVersionNumber": 1,
"LatestVersionNumber": 1,
"Versions": [version],
- "Tags": [{"Key": t["Key"], "Value": t["Value"]} for t in props.get("Tags", [])],
}
+ # The type has no Tags property: the template's own tags come from the
+ # TagSpecifications entry for "launch-template", the rest of which tag
+ # what the template launches. Kept where CreateLaunchTemplate keeps them
+ # (the record and the tag store share one list), so CreateTags stays
+ # visible; the dead Tags read left every template untagged.
+ tags = [
+ {"Key": str(t.get("Key", "")), "Value": str(t.get("Value", ""))}
+ for spec in (props.get("TagSpecifications") or [])
+ if isinstance(spec, dict) and spec.get("ResourceType") == "launch-template"
+ for t in (spec.get("Tags") or []) if isinstance(t, dict)
+ ]
+ if tags:
+ lt["Tags"] = tags
+ _ec2._tags[lt_id] = tags
_ec2._launch_templates[lt_id] = lt
return lt_id, {
"LaunchTemplateId": lt_id,
@@ -7146,8 +7847,56 @@ def _ec2_launch_template_create(logical_id, props, stack_name):
}
+def _ec2_launch_template_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update a launch template in place. LaunchTemplateData, TagSpecifications
+ and VersionDescription are No interruption on the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html)
+ and LaunchTemplateName is Replacement.
+
+ A data change adds version N+1 on AWS and leaves the template's id alone.
+ The create instead minted a new lt- id, threw the Versions list away and
+ reset LatestVersionNumber and DefaultVersionNumber to 1, which is exactly
+ what an Auto Scaling group reads through Fn::GetAtt LatestVersionNumber.
+
+ Measured on AWS 2026-09-21, one property per update: a LaunchTemplateData,
+ a TagSpecifications and a VersionDescription change each add a version
+ (latest 2, 3, 4), the default version stays 1 throughout, and a
+ TagSpecifications change leaves the template's own tags as they were;
+ they are applied at creation only."""
+ import time as _time
+ template = _ec2._launch_templates.get(physical_id)
+ name = new_props.get("LaunchTemplateName", _physical_name(
+ stack_name, logical_id or physical_id))
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ name, template["LaunchTemplateName"] if template else None,
+ _ec2_launch_template_create, _ec2_launch_template_delete,
+ )
+ if replaced is not None:
+ return replaced
+ version_number = int(template.get("LatestVersionNumber", 1)) + 1
+ template.setdefault("Versions", []).append({
+ "LaunchTemplateId": physical_id,
+ "LaunchTemplateName": template["LaunchTemplateName"],
+ "VersionNumber": version_number,
+ "VersionDescription": new_props.get("VersionDescription", ""),
+ "DefaultVersion": False,
+ "CreateTime": _time.strftime("%Y-%m-%dT%H:%M:%SZ", _time.gmtime()),
+ "LaunchTemplateData": new_props.get("LaunchTemplateData", {}),
+ })
+ template["LatestVersionNumber"] = version_number
+ return physical_id, {
+ "LaunchTemplateId": physical_id,
+ "LaunchTemplateName": template["LaunchTemplateName"],
+ "DefaultVersionNumber": str(template.get("DefaultVersionNumber", 1)),
+ "LatestVersionNumber": str(version_number),
+ }
+
+
def _ec2_launch_template_delete(physical_id, props):
_ec2._launch_templates.pop(physical_id, None)
+ _ec2._tags.pop(physical_id, None)
# --- ELBv2 (Load Balancer + Listener) provisioners ---
@@ -9389,13 +10138,7 @@ def _asg_create(logical_id, props, stack_name):
"Tags": [],
"Status": "",
}
- lt = props.get("LaunchTemplate", {})
- if lt:
- asg["LaunchTemplate"] = {
- "LaunchTemplateId": lt.get("LaunchTemplateId", lt.get("LaunchTemplateName", "")),
- "LaunchTemplateName": lt.get("LaunchTemplateName", ""),
- "Version": lt.get("Version", "$Default"),
- }
+ asg["LaunchTemplate"] = _asg_launch_template(props.get("LaunchTemplate"))
tags = []
for t in props.get("Tags", []):
tags.append({
@@ -9403,7 +10146,7 @@ def _asg_create(logical_id, props, stack_name):
"Value": t.get("Value", ""),
"ResourceId": name,
"ResourceType": "auto-scaling-group",
- "PropagateAtLaunch": t.get("PropagateAtLaunch", False),
+ "PropagateAtLaunch": _asg_propagate_at_launch(t),
})
asg["Tags"] = tags
_asg._asgs[name] = asg
@@ -9411,6 +10154,96 @@ def _asg_create(logical_id, props, stack_name):
return name, {"AutoScalingGroupARN": arn, "Arn": arn}
+def _asg_launch_template(spec):
+ """A group's LaunchTemplate as DescribeAutoScalingGroups answers it: the
+ template's id and name, whichever of the two the group was given, and the
+ version as given. A template references its launch template through Ref,
+ the id, and the provisioner copied only that, so LaunchTemplateName read
+ "" where AWS answers the real name (measured 2026-09-21)."""
+ if not spec:
+ return {}
+ lt_id = spec.get("LaunchTemplateId", "")
+ lt_name = spec.get("LaunchTemplateName", "")
+ record = _ec2._launch_templates.get(lt_id) if lt_id else next(
+ (t for t in _ec2._launch_templates.values()
+ if t.get("LaunchTemplateName") == lt_name), None)
+ if record:
+ lt_id, lt_name = record["LaunchTemplateId"], record["LaunchTemplateName"]
+ return {
+ "LaunchTemplateId": lt_id or lt_name,
+ "LaunchTemplateName": lt_name,
+ "Version": spec.get("Version", "$Default"),
+ }
+
+
+def _asg_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update an Auto Scaling group in place. The sizes, cooldown, health
+ check, zones, subnets, termination policies, launch configuration and
+ launch template are No interruption on the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-autoscaling-autoscalinggroup.html);
+ AutoScalingGroupName and InstanceId are Replacement (the registry's
+ createOnlyProperties).
+
+ The create mints a fresh ARN off a uuid, re-stamps CreatedTime and resets
+ Instances to an empty list, so the fallback handed every consumer of the
+ ARN a new value and dropped the group's instances on a size change."""
+ name = new_props.get("AutoScalingGroupName") or _physical_name(
+ stack_name, logical_id or physical_id, max_len=255)
+ asg = _asg._asgs.get(physical_id)
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ (name, new_props.get("InstanceId")),
+ (asg["AutoScalingGroupName"], old_props.get("InstanceId")) if asg else None,
+ _asg_create, _asg_delete,
+ )
+ if replaced is not None:
+ return replaced
+ asg["LaunchConfigurationName"] = new_props.get("LaunchConfigurationName", "")
+ asg["MinSize"] = int(new_props.get("MinSize", 0))
+ asg["MaxSize"] = int(new_props.get("MaxSize", 0))
+ asg["DesiredCapacity"] = int(
+ new_props.get("DesiredCapacity", new_props.get("MinSize", 0)))
+ asg["DefaultCooldown"] = int(new_props.get("Cooldown", 300))
+ asg["AvailabilityZones"] = new_props.get(
+ "AvailabilityZones", [f"{get_region()}a"])
+ asg["HealthCheckType"] = new_props.get("HealthCheckType", "EC2")
+ asg["HealthCheckGracePeriod"] = int(new_props.get("HealthCheckGracePeriod", 300))
+ zone_id = new_props.get("VPCZoneIdentifier", "")
+ asg["VPCZoneIdentifier"] = ",".join(zone_id) if isinstance(zone_id, list) else zone_id
+ asg["TerminationPolicies"] = new_props.get("TerminationPolicies", ["Default"])
+ asg["NewInstancesProtectedFromScaleIn"] = new_props.get(
+ "NewInstancesProtectedFromScaleIn", False)
+ asg["LaunchTemplate"] = _asg_launch_template(new_props.get("LaunchTemplate"))
+ # Reconciled rather than overwritten: a tag added through CreateOrUpdateTags
+ # survives a template tag change, as on AWS (measured 2026-09-21), and the
+ # template's own tags take its PropagateAtLaunch.
+ tags = _asg._tags.get(physical_id)
+ if tags is None:
+ tags = list(asg.get("Tags") or [])
+ _reconcile_tag_list(tags, old_props, new_props)
+ declared = {
+ str(t["Key"]): t for t in (new_props.get("Tags") or [])
+ if isinstance(t, dict) and "Key" in t
+ }
+ for tag in tags:
+ spec = declared.get(tag.get("Key"))
+ if spec is not None:
+ tag["ResourceId"] = physical_id
+ tag["ResourceType"] = "auto-scaling-group"
+ tag["PropagateAtLaunch"] = _asg_propagate_at_launch(spec)
+ asg["Tags"] = tags
+ _asg._tags[physical_id] = tags
+ arn = asg["AutoScalingGroupARN"]
+ return physical_id, {"AutoScalingGroupARN": arn, "Arn": arn}
+
+
+def _asg_propagate_at_launch(tag):
+ """A template tag's PropagateAtLaunch as a boolean; a YAML template can
+ carry it as the string "false", which is truthy."""
+ value = tag.get("PropagateAtLaunch", False)
+ return value if isinstance(value, bool) else str(value).lower() == "true"
+
+
def _asg_delete(physical_id, props):
_asg._asgs.pop(physical_id, None)
_asg._tags.pop(physical_id, None)
@@ -9436,23 +10269,58 @@ def _asg_lc_delete(physical_id, props):
_asg._launch_configs.pop(physical_id, None)
+def _asg_policy_name(props, stack_name, logical_id):
+ """The registry lists PolicyName among the read-only attributes of
+ AWS::AutoScaling::ScalingPolicy, but AWS applies one the template sets
+ when it creates the policy (measured 2026-09-21: the policy carries
+ exactly that name), and never after: the update ignores it. Without one,
+ CloudFormation generates ``{stack}-{LogicalId}-{suffix}`` (measured the
+ same day)."""
+ return props.get("PolicyName") or _physical_name(stack_name, logical_id, max_len=255)
+
+
def _asg_policy_create(logical_id, props, stack_name):
asg_name = props.get("AutoScalingGroupName", "")
- policy_name = props.get("PolicyName") or _physical_name(stack_name, logical_id, max_len=255)
+ policy_name = _asg_policy_name(props, stack_name, logical_id)
arn = f"arn:aws:autoscaling:{get_region()}:{get_account_id()}:scalingPolicy:{new_uuid()}:autoScalingGroupName/{asg_name}:policyName/{policy_name}"
key = f"{asg_name}/{policy_name}"
- _asg._policies[key] = {
- "PolicyARN": arn,
- "PolicyName": policy_name,
- "AutoScalingGroupName": asg_name,
- "PolicyType": props.get("PolicyType", "SimpleScaling"),
- "AdjustmentType": props.get("AdjustmentType", "ChangeInCapacity"),
- "ScalingAdjustment": int(props.get("ScalingAdjustment", 0)),
- "Cooldown": int(props.get("Cooldown", 300)),
- }
+ # The service's own record builder, so a target-tracking or step policy
+ # keeps its configuration the way PutScalingPolicy stores it.
+ _asg._policies[key] = _asg._policy_record(asg_name, policy_name, arn, props)
return arn, {"Arn": arn, "PolicyName": policy_name}
+def _asg_policy_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update a scaling policy in place. AdjustmentType, Cooldown,
+ EstimatedInstanceWarmup, MetricAggregationType, MinAdjustmentMagnitude,
+ PolicyType, PredictiveScalingConfiguration, ScalingAdjustment,
+ StepAdjustments and TargetTrackingConfiguration are No interruption on the
+ resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-autoscaling-scalingpolicy.html);
+ AutoScalingGroupName is Replacement. PolicyName is read-only in the
+ registry: a change or removal leaves the policy's name and ARN as they are
+ (measured 2026-09-21), so it is no part of the replacement key.
+
+ The physical id is the policy ARN and the create mints a new one off a
+ uuid, so the fallback answered a different Ref for an unchanged policy."""
+ asg_name = new_props.get("AutoScalingGroupName", "")
+ current = next(
+ (p for p in _asg._policies.values() if p.get("PolicyARN") == physical_id), None)
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ asg_name, current["AutoScalingGroupName"] if current else None,
+ _asg_policy_create, _asg_policy_delete,
+ )
+ if replaced is not None:
+ return replaced
+ # Rebuilt from the new properties rather than patched, so a member the
+ # template dropped (a step list, a warmup) goes with it.
+ record = _asg._policy_record(asg_name, current["PolicyName"], physical_id, new_props)
+ current.clear()
+ current.update(record)
+ return physical_id, {"Arn": physical_id, "PolicyName": current["PolicyName"]}
+
+
def _asg_policy_delete(physical_id, props):
# physical_id is the ARN, find matching key
for k, v in list(_asg._policies.items()):
@@ -9483,27 +10351,69 @@ def _asg_hook_delete(physical_id, props):
def _asg_scheduled_create(logical_id, props, stack_name):
+ """CloudFormation names a scheduled action itself and Ref answers that
+ name. The registry lists ScheduledActionName as read-only, and AWS
+ ignores one the template sets (measured 2026-09-21: the action carries a
+ generated name, and a changed or removed ScheduledActionName leaves it as
+ it is)."""
asg_name = props.get("AutoScalingGroupName", "")
- action_name = props.get("ScheduledActionName") or _physical_name(stack_name, logical_id, max_len=255)
+ action_name = _physical_name(stack_name, logical_id, max_len=255)
arn = f"arn:aws:autoscaling:{get_region()}:{get_account_id()}:scheduledUpdateGroupAction:{new_uuid()}:autoScalingGroupName/{asg_name}:scheduledActionName/{action_name}"
- key = f"{asg_name}/{action_name}"
- _asg._scheduled_actions[key] = {
- "ScheduledActionARN": arn,
- "ScheduledActionName": action_name,
- "AutoScalingGroupName": asg_name,
- "Recurrence": props.get("Recurrence", ""),
- "MinSize": int(props.get("MinSize", -1)),
- "MaxSize": int(props.get("MaxSize", -1)),
- "DesiredCapacity": int(props.get("DesiredCapacity", -1)),
- }
- return arn, {"Arn": arn, "ScheduledActionName": action_name}
+ # The service's own record builder, as for a scaling policy.
+ _asg._scheduled_actions[f"{asg_name}/{action_name}"] = _asg._scheduled_action_record(
+ asg_name, action_name, arn, props)
+ return action_name, {"Arn": arn, "ScheduledActionName": action_name}
+
+
+def _asg_scheduled_find(physical_id, props):
+ """The store key and record of a scheduled action: by name within the
+ group the properties name, or by ARN, the physical id before Ref answered
+ the name."""
+ asg_name = props.get("AutoScalingGroupName", "")
+ for key, action in _asg._scheduled_actions.items():
+ if (action.get("ScheduledActionARN") == physical_id
+ or (action.get("ScheduledActionName") == physical_id
+ and action.get("AutoScalingGroupName") == asg_name)):
+ return key, action
+ return None, None
+
+
+def _asg_scheduled_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update a scheduled action in place. DesiredCapacity, EndTime, MaxSize,
+ MinSize, Recurrence, StartTime and TimeZone are No interruption on the
+ resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-autoscaling-scheduledaction.html),
+ and AWS applies each in place with the ARN unchanged (measured
+ 2026-09-21); AutoScalingGroupName is Replacement. ScheduledActionName is
+ read-only and ignored (see _asg_scheduled_create).
+
+ The create minted a new ARN on every change, so an unchanged action came
+ back under a new identity."""
+ asg_name = new_props.get("AutoScalingGroupName", "")
+ _key, current = _asg_scheduled_find(physical_id, old_props)
+ # The replacement keeps the generated name, so the physical id does not
+ # move and the predecessor in the old group has to go explicitly.
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ asg_name, current["AutoScalingGroupName"] if current else None,
+ _asg_scheduled_create, _asg_scheduled_delete,
+ delete_when_id_unchanged=True,
+ )
+ if replaced is not None:
+ return replaced
+ record = _asg._scheduled_action_record(
+ asg_name, current["ScheduledActionName"], current["ScheduledActionARN"], new_props)
+ current.clear()
+ current.update(record)
+ return physical_id, {"Arn": current["ScheduledActionARN"],
+ "ScheduledActionName": current["ScheduledActionName"]}
def _asg_scheduled_delete(physical_id, props):
- for k, v in list(_asg._scheduled_actions.items()):
- if v.get("ScheduledActionARN") == physical_id:
- _asg._scheduled_actions.pop(k, None)
- break
+ key, _action = _asg_scheduled_find(physical_id, props)
+ if key is not None:
+ _asg._scheduled_actions.pop(key, None)
# Resource Handler Registry
@@ -10665,14 +11575,20 @@ _RESOURCE_HANDLERS = {
"AWS::SSM::Parameter": {"create": _ssm_create, "update": _ssm_update, "delete": _ssm_delete},
"AWS::AppConfig::Application": {
"create": _appconfig_application_create,
+ "update": _appconfig_application_update,
+ "update_with_logical_id": True,
"delete": _appconfig_application_delete,
},
"AWS::AppConfig::Environment": {
"create": _appconfig_environment_create,
+ "update": _appconfig_environment_update,
+ "update_with_logical_id": True,
"delete": _appconfig_environment_delete,
},
"AWS::AppConfig::ConfigurationProfile": {
"create": _appconfig_configuration_profile_create,
+ "update": _appconfig_configuration_profile_update,
+ "update_with_logical_id": True,
"delete": _appconfig_configuration_profile_delete,
},
"AWS::AppConfig::HostedConfigurationVersion": {
@@ -10681,6 +11597,8 @@ _RESOURCE_HANDLERS = {
},
"AWS::AppConfig::DeploymentStrategy": {
"create": _appconfig_deployment_strategy_create,
+ "update": _appconfig_deployment_strategy_update,
+ "update_with_logical_id": True,
"delete": _appconfig_deployment_strategy_delete,
},
"AWS::AppConfig::Deployment": {
@@ -10847,7 +11765,12 @@ _RESOURCE_HANDLERS = {
"update": _sns_topic_policy_update,
"delete": _sns_topic_policy_delete,
},
- "AWS::AppSync::GraphQLApi": {"create": _appsync_api_create, "delete": _appsync_api_delete},
+ "AWS::AppSync::GraphQLApi": {
+ "create": _appsync_api_create,
+ "update": _appsync_api_update,
+ "update_with_logical_id": True,
+ "delete": _appsync_api_delete,
+ },
"AWS::AppSync::DataSource": {"create": _appsync_ds_create, "delete": _appsync_ds_delete},
"AWS::AppSync::FunctionConfiguration": {
"create": _appsync_function_create,
@@ -10856,7 +11779,12 @@ _RESOURCE_HANDLERS = {
},
"AWS::AppSync::Resolver": {"create": _appsync_resolver_create, "delete": _appsync_resolver_delete},
"AWS::AppSync::GraphQLSchema": {"create": _appsync_schema_create, "delete": _appsync_schema_delete},
- "AWS::AppSync::ApiKey": {"create": _appsync_apikey_create, "delete": _appsync_apikey_delete},
+ "AWS::AppSync::ApiKey": {
+ "create": _appsync_apikey_create,
+ "update": _appsync_apikey_update,
+ "update_with_logical_id": True,
+ "delete": _appsync_apikey_delete,
+ },
"AWS::SecretsManager::Secret": {
"create": _sm_secret_create,
"update": _sm_secret_update,
@@ -10931,18 +11859,48 @@ _RESOURCE_HANDLERS = {
"update_with_logical_id": True,
"delete": _kms_alias_delete,
},
- "AWS::EC2::VPC": {"create": _ec2_vpc_create, "delete": _ec2_vpc_delete},
+ "AWS::EC2::VPC": {
+ "create": _ec2_vpc_create,
+ "update": _ec2_vpc_update,
+ "update_with_logical_id": True,
+ "delete": _ec2_vpc_delete,
+ },
"AWS::EC2::VPCEndpoint": {
"create": _ec2_vpc_endpoint_create,
"update": _ec2_vpc_endpoint_update,
"delete": _ec2_vpc_endpoint_delete,
},
- "AWS::EC2::Subnet": {"create": _ec2_subnet_create, "delete": _ec2_subnet_delete},
- "AWS::EC2::SecurityGroup": {"create": _ec2_sg_create, "delete": _ec2_sg_delete},
- "AWS::EC2::InternetGateway": {"create": _ec2_igw_create, "delete": _ec2_igw_delete},
+ "AWS::EC2::Subnet": {
+ "create": _ec2_subnet_create,
+ "update": _ec2_subnet_update,
+ "update_with_logical_id": True,
+ "delete": _ec2_subnet_delete,
+ },
+ "AWS::EC2::SecurityGroup": {
+ "create": _ec2_sg_create,
+ "update": _ec2_sg_update,
+ "update_with_logical_id": True,
+ "delete": _ec2_sg_delete,
+ },
+ "AWS::EC2::InternetGateway": {
+ "create": _ec2_igw_create,
+ "update": _ec2_igw_update,
+ "update_with_logical_id": True,
+ "delete": _ec2_igw_delete,
+ },
"AWS::EC2::VPCGatewayAttachment": {"create": _ec2_vpc_gw_attach_create, "delete": _ec2_vpc_gw_attach_delete},
- "AWS::EC2::RouteTable": {"create": _ec2_rtb_create, "delete": _ec2_rtb_delete},
- "AWS::EC2::Route": {"create": _ec2_route_create, "delete": _ec2_route_delete},
+ "AWS::EC2::RouteTable": {
+ "create": _ec2_rtb_create,
+ "update": _ec2_rtb_update,
+ "update_with_logical_id": True,
+ "delete": _ec2_rtb_delete,
+ },
+ "AWS::EC2::Route": {
+ "create": _ec2_route_create,
+ "update": _ec2_route_update,
+ "update_with_logical_id": True,
+ "delete": _ec2_route_delete,
+ },
"AWS::EC2::SubnetRouteTableAssociation": {"create": _ec2_subnet_rtb_assoc_create, "delete": _ec2_subnet_rtb_assoc_delete},
"AWS::ECS::Cluster": {"create": _ecs_cluster_create, "delete": _ecs_cluster_delete},
"AWS::ECS::TaskDefinition": {"create": _ecs_task_def_create, "delete": _ecs_task_def_delete},
@@ -11152,9 +12110,24 @@ _RESOURCE_HANDLERS = {
# CDK metadata — safe to ignore
"AWS::CDK::Metadata": {"create": lambda lid, props, sn: (f"CDKMetadata-{lid}", {}), "delete": lambda pid, props: None},
# AutoScaling
- "AWS::AutoScaling::AutoScalingGroup": {"create": _asg_create, "delete": _asg_delete},
+ "AWS::AutoScaling::AutoScalingGroup": {
+ "create": _asg_create,
+ "update": _asg_update,
+ "update_with_logical_id": True,
+ "delete": _asg_delete,
+ },
"AWS::AutoScaling::LaunchConfiguration": {"create": _asg_lc_create, "delete": _asg_lc_delete},
- "AWS::AutoScaling::ScalingPolicy": {"create": _asg_policy_create, "delete": _asg_policy_delete},
+ "AWS::AutoScaling::ScalingPolicy": {
+ "create": _asg_policy_create,
+ "update": _asg_policy_update,
+ "update_with_logical_id": True,
+ "delete": _asg_policy_delete,
+ },
"AWS::AutoScaling::LifecycleHook": {"create": _asg_hook_create, "delete": _asg_hook_delete},
- "AWS::AutoScaling::ScheduledAction": {"create": _asg_scheduled_create, "delete": _asg_scheduled_delete},
+ "AWS::AutoScaling::ScheduledAction": {
+ "create": _asg_scheduled_create,
+ "update": _asg_scheduled_update,
+ "update_with_logical_id": True,
+ "delete": _asg_scheduled_delete,
+ },
}
diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.py
index 8573481b..ec37d8a2 100644
--- a/ministack/services/cloudformation/stacks.py
+++ b/ministack/services/cloudformation/stacks.py
@@ -23,6 +23,7 @@ from .provisioners import (
_DEFERRED_PREDECESSOR_DELETES,
_RETAIN_REPLACED,
_RETAINING_POLICIES,
+ _custom_named_replacement_error,
_delete_resource,
_property_recreation,
_provision_resource,
@@ -187,13 +188,91 @@ def _resolve_stack_outputs(outputs_defs, conditions, resources, param_values,
return resolved_outputs, exports
+def _rollback_failure_reason(failed_records: dict) -> str:
+ """The StackStatusReason of a rollback that could not finish: the
+ resources whose revert failed, then those whose delete failed, in the
+ wording AWS uses for each."""
+ reverts = sorted(k for k, v in failed_records.items() if "RevertTo" in v)
+ deletes = sorted(k for k, v in failed_records.items() if "RevertTo" not in v)
+ parts = []
+ if reverts:
+ parts.append(f"The following resource(s) failed to update: [{', '.join(reverts)}].")
+ if deletes:
+ parts.append(f"The following resource(s) failed to delete: [{', '.join(deletes)}].")
+ return " ".join(parts)
+
+
+def _sends_back_failed_update(resource_type: str) -> bool:
+ """Whether the rollback sends the resource whose own update failed back to
+ its previous properties. AWS does for a custom resource (measured
+ 2026-09-21: the provider that answered FAILED gets UPDATE_IN_PROGRESS /
+ UPDATE_COMPLETE in the rollback), whose provider may have changed state
+ before it failed. A resource type's own handler that failed is taken to
+ have changed nothing: AWS records a lone UPDATE_COMPLETE for it without
+ calling it again (a scaling policy refused with AlreadyExists, the same
+ day). A nested stack is sent back so its own in-place changes are undone,
+ as AWS rolls the child stack back."""
+ return (resource_type.startswith("Custom::")
+ or resource_type in ("AWS::CloudFormation::CustomResource",
+ "AWS::CloudFormation::Stack"))
+
+
+def _mark_rolled_back(record):
+ """A restored stack record of a resource the rollback updated reports
+ that update, as DescribeStackResources does on AWS afterwards."""
+ if record is not None:
+ record["ResourceStatus"] = "UPDATE_COMPLETE"
+ record["Timestamp"] = now_iso()
+
+
+async def _revert_update(stack_id, stack_name, logical_id, rtype, physical_id,
+ applied_props, previous_props, attrs, record=None):
+ """Undo an in-place update during an update rollback: run the type's
+ update handler from the properties the update applied back to the ones
+ the stack held before it, as AWS does in UPDATE_ROLLBACK_IN_PROGRESS,
+ with the UPDATE_IN_PROGRESS / UPDATE_COMPLETE events it records for that.
+
+ ``record`` is the restored stack record of the resource; it takes the
+ attributes the handler answers now (a launch template's rollback adds a
+ version, for one). On failure the UPDATE_FAILED event is recorded and the
+ handler's exception propagates."""
+ _add_event(stack_id, stack_name, logical_id, rtype, "UPDATE_IN_PROGRESS",
+ physical_id=physical_id)
+ try:
+ if _is_custom_resource(rtype):
+ new_pid, new_attrs = await run_reentrant(
+ _update_resource, rtype, physical_id, applied_props,
+ previous_props, stack_name, logical_id, attrs)
+ else:
+ new_pid, new_attrs = _update_resource(
+ rtype, physical_id, applied_props, previous_props,
+ stack_name, logical_id, attrs)
+ except Exception as exc:
+ logger.error("Rollback update of %s failed: %s", logical_id, exc)
+ _add_event(stack_id, stack_name, logical_id, rtype, "UPDATE_FAILED",
+ str(exc), physical_id)
+ raise
+ if record is not None:
+ if new_pid != physical_id:
+ # The revert itself replaced the resource; the stack has to
+ # follow it or it records an id that no longer exists.
+ logger.warning("Rollback update of %s moved it from %s to %s",
+ logical_id, physical_id, new_pid)
+ record["PhysicalResourceId"] = new_pid
+ if new_attrs:
+ record["Attributes"] = {**record.get("Attributes", {}), **new_attrs}
+ _mark_rolled_back(record)
+ _add_event(stack_id, stack_name, logical_id, rtype, "UPDATE_COMPLETE",
+ physical_id=new_pid)
+
+
async def _continue_update_rollback_async(stack_name: str, stack_id: str,
resources_to_skip):
- """Background task for ContinueUpdateRollback: retry the deletes that
- failed the update rollback, skipping the logical ids the caller named
- (their status becomes UPDATE_COMPLETE and the resource stays, as on AWS),
- and land the stack in UPDATE_ROLLBACK_COMPLETE or, if a delete fails
- again, UPDATE_ROLLBACK_FAILED."""
+ """Background task for ContinueUpdateRollback: retry the reverts and
+ deletes that failed the update rollback, skipping the logical ids the
+ caller named (their status becomes UPDATE_COMPLETE and the resource stays
+ as it is, as on AWS), and land the stack in UPDATE_ROLLBACK_COMPLETE or,
+ if a retry fails again, UPDATE_ROLLBACK_FAILED."""
from ministack.services.cloudformation import _stacks
stack = _stacks.get(stack_name)
if not stack:
@@ -210,6 +289,15 @@ async def _continue_update_rollback_async(stack_name: str, stack_id: str,
_add_event(stack_id, stack_name, logical_id, rtype,
"UPDATE_COMPLETE", "Resource rollback skipped by user", pid)
continue
+ if "RevertTo" in res:
+ try:
+ await _revert_update(
+ stack_id, stack_name, logical_id, rtype, pid,
+ res["RevertFrom"], res["RevertTo"], res.get("Attributes"),
+ stack.get("_resources", {}).get(logical_id))
+ except Exception:
+ still_failed[logical_id] = res
+ continue
try:
if _is_custom_resource(rtype):
await run_reentrant(_delete_resource, rtype, pid,
@@ -227,8 +315,7 @@ async def _continue_update_rollback_async(stack_name: str, stack_id: str,
await asyncio.sleep(0)
if still_failed:
stack["_rollback_failed"] = still_failed
- reason = ("The following resource(s) failed to delete: "
- f"[{', '.join(sorted(still_failed))}].")
+ reason = _rollback_failure_reason(still_failed)
stack["StackStatus"] = "UPDATE_ROLLBACK_FAILED"
stack["StackStatusReason"] = reason
_add_event(stack_id, stack_name, stack_name, "AWS::CloudFormation::Stack",
@@ -291,6 +378,15 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
fail_reason = ""
cancelled = False
replaced_resources = []
+ # The resource that failed the update, when it existed before it, as
+ # (logical id, type, physical id, applied props, previous props, attrs):
+ # a custom resource's provider may have changed state before it failed,
+ # so the rollback sends it back too (_sends_back_failed_update). The three
+ # props are None when the update never reached the handler.
+ failed_update = None
+ # The logical id of the resource whose create or update failed, which the
+ # rollback's reason names.
+ failed_logical_id = None
stack.pop("_cancel_requested", None)
for logical_id in ordered:
@@ -307,6 +403,7 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
resource_type = res_def.get("Type", "AWS::CloudFormation::CustomResource")
raw_props = res_def.get("Properties", {})
+ update_attempt = None
try:
# Resolve properties
@@ -374,6 +471,11 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
stack_name, stack_id, logical_id)
pending_deletes = []
deferred_token = _DEFERRED_PREDECESSOR_DELETES.set(pending_deletes)
+ if not _custom_named_replacement_error(
+ resource_type, old_tagged, new_tagged):
+ # Refused above the handler, the update changes nothing
+ # and there is nothing to send back.
+ update_attempt = (old_pid, new_tagged, old_tagged, old_attrs)
try:
if _is_custom_resource(resource_type):
physical_id, attrs = await run_reentrant(
@@ -415,6 +517,16 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
f"{status_prefix}_FAILED", str(exc))
failed = True
fail_reason = f"Resource {logical_id} failed: {exc}"
+ failed_logical_id = logical_id
+ if update_attempt is not None:
+ failed_update = (logical_id, resource_type, *update_attempt)
+ elif is_update and previous_stack and logical_id in previous_stack.get(
+ "_resources", {}):
+ failed_update = (
+ logical_id, resource_type,
+ previous_stack["_resources"][logical_id].get(
+ "PhysicalResourceId", logical_id),
+ None, None, None)
break
provisioned_resources[logical_id] = {
@@ -554,34 +666,100 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
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:
+ # AWS names the resource and whether it existed before the
+ # update (measured 2026-09-21), trailing space included.
+ 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"],
- "User Initiated" if cancelled else "Rollback requested",
- stack_id)
+ rollback_reason, stack_id)
- rollback_delete_failures = []
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}
- for logical_id in reversed(created_in_this_run):
+
+ async def revert(logical_id, rtype, pid, applied, previous, attrs):
+ # An in-place change goes back through the update handler; one
+ # that fails is kept for ContinueUpdateRollback to retry or skip.
+ 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,
+ }
+
+ # AWS rolls an update back as an update to the previous template
+ # (measured 2026-09-21): what the update changed in place goes back
+ # through the update handler, in the template's dependency order,
+ # and the resource that failed comes last. What the update created
+ # is deleted after that, in the cleanup phase, in reverse order.
+ to_delete = []
+ for logical_id in created_in_this_run:
res = provisioned_resources.get(logical_id, {})
- rtype = res.get("ResourceType", "")
pid = res.get("PhysicalResourceId", "")
- res_props = res.get("Properties", {})
prev = previous_resources.get(logical_id)
- if (prev is not None and prev.get("PhysicalResourceId") == pid
- and logical_id not in replaced_ids):
- # The resource existed before this update and kept its
- # identity (untouched, or updated in place), so it is not
- # something this run created: deleting it would destroy a
- # resource the restored stack still records. Only new
- # resources and replacements are undone, a replacement
- # under an unchanged id by its new properties. An in-place
- # change is not reverted here.
+ if (prev is None or prev.get("PhysicalResourceId") != pid
+ or logical_id in replaced_ids):
+ to_delete.append(logical_id)
continue
+ # The resource existed before this update and kept its
+ # identity (untouched, or updated in place), so it is not
+ # something this run created: it goes back to the properties
+ # it had, with the tags the forward update gave it on one side
+ # and the previous tags on the other, exactly as that update
+ # was called. An untouched one has nothing to send back.
+ 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:
+ # Nothing to send back: the update never reached a handler
+ # (a custom-named replacement refused above it), or the
+ # type's own handler refused it. AWS still records the
+ # resource as complete.
+ _add_event(stack_id, stack_name, logical_id, rtype,
+ "UPDATE_COMPLETE", physical_id=pid)
+ _mark_rolled_back(previous_resources.get(logical_id))
+ # Everything is back; what the update created goes in the cleanup
+ # phase, which AWS reports as a stack status of its own. The
+ # rollback is complete by then, so a delete that fails in it is a
+ # DELETE_FAILED event and nothing more: it cannot turn the stack
+ # into UPDATE_ROLLBACK_FAILED.
+ 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,
@@ -594,6 +772,8 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
"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(
@@ -609,7 +789,9 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
logical_id, del_exc)
_add_event(stack_id, stack_name, logical_id, rtype,
"DELETE_FAILED", str(del_exc), pid)
- rollback_delete_failures.append(logical_id)
+ if cleanup_phase:
+ provisioned_resources.pop(logical_id, None)
+ continue
rollback_failed_records[logical_id] = {
"PhysicalResourceId": pid, "ResourceType": rtype,
"Properties": res_props,
@@ -634,16 +816,15 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
stack["StackStatus"] = "UPDATE_ROLLBACK_COMPLETE"
else:
stack["StackStatus"] = "ROLLBACK_COMPLETE"
- if rollback_delete_failures:
- # A rollback that could not undo what it created must not
- # report success — real CloudFormation lands the stack in
- # (UPDATE_)ROLLBACK_FAILED and keeps the failure visible.
+ 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 = ("The following resource(s) failed to delete: "
- f"[{', '.join(sorted(rollback_delete_failures))}].")
+ reason = _rollback_failure_reason(rollback_failed_records)
stack["StackStatusReason"] = reason
# What ContinueUpdateRollback retries (or skips).
stack["_rollback_failed"] = rollback_failed_records
@@ -651,9 +832,12 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
"AWS::CloudFormation::Stack", stack["StackStatus"],
reason, stack_id)
return
+ # AWS's final UPDATE_ROLLBACK_COMPLETE carries no reason
+ # (measured 2026-09-21).
_add_event(stack_id, stack_name, stack_name,
"AWS::CloudFormation::Stack", stack["StackStatus"],
- "Rollback complete", stack_id)
+ "" if is_update and previous_stack else "Rollback complete",
+ stack_id)
return
# Success: publish outputs and exports
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index 603d2067..97df8d3d 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -3128,14 +3128,37 @@ def _describe_vpc_classic_link_dns_support(p):
return _xml(200, "DescribeVpcClassicLinkDnsSupportResponse", "<vpcs/>")
+def _subnet_dns_name_options(subnet):
+ """A subnet's PrivateDnsNameOptionsOnLaunch, with AWS's defaults for a
+ subnet created without them: IP-based host names, no resource-name DNS
+ records."""
+ return subnet.get("PrivateDnsNameOptionsOnLaunch") or {
+ "HostnameType": "ip-name",
+ "EnableResourceNameDnsARecord": False,
+ "EnableResourceNameDnsAAAARecord": False,
+ }
+
+
def _modify_subnet_attribute(p):
subnet_id = _p(p, "SubnetId")
if subnet_id not in _subnets:
return _error("InvalidSubnetID.NotFound",
f"The subnet ID '{subnet_id}' does not exist", 400)
+ subnet = _subnets[subnet_id]
val = _p(p, "MapPublicIpOnLaunch.Value")
if val:
- _subnets[subnet_id]["MapPublicIpOnLaunch"] = val.lower() == "true"
+ subnet["MapPublicIpOnLaunch"] = val.lower() == "true"
+ # One DNS name option per call, as on AWS; the others keep their values.
+ options = dict(_subnet_dns_name_options(subnet))
+ hostname_type = _p(p, "PrivateDnsHostnameTypeOnLaunch")
+ if hostname_type:
+ options["HostnameType"] = hostname_type
+ for member in ("EnableResourceNameDnsARecord", "EnableResourceNameDnsAAAARecord"):
+ val = _p(p, f"{member}OnLaunch.Value")
+ if val:
+ options[member] = val.lower() == "true"
+ if options != _subnet_dns_name_options(subnet):
+ subnet["PrivateDnsNameOptionsOnLaunch"] = options
return _xml(200, "ModifySubnetAttributeResponse", "<return>true</return>")
@@ -4321,6 +4344,9 @@ def _vpc_xml(vpc):
def _subnet_fields_xml(subnet, tag="item"):
+ # A subnet has no IPv6 block here, so it is never IPv6-native and assigns
+ # no IPv6 address on creation; DescribeSubnets answers both as false.
+ dns_options = _subnet_dns_name_options(subnet)
return f"""<{tag}>
<subnetId>{subnet['SubnetId']}</subnetId>
<subnetArn>arn:aws:ec2:{get_region()}:{get_account_id()}:subnet/{subnet['SubnetId']}</subnetArn>
@@ -4333,6 +4359,14 @@ def _subnet_fields_xml(subnet, tag="item"):
<defaultForAz>{'true' if subnet['DefaultForAz'] else 'false'}</defaultForAz>
<mapPublicIpOnLaunch>{'true' if subnet['MapPublicIpOnLaunch'] else 'false'}</mapPublicIpOnLaunch>
<ownerId>{subnet['OwnerId']}</ownerId>
+ <assignIpv6AddressOnCreation>false</assignIpv6AddressOnCreation>
+ <enableDns64>{'true' if subnet.get('EnableDns64') else 'false'}</enableDns64>
+ <ipv6Native>false</ipv6Native>
+ <privateDnsNameOptionsOnLaunch>
+ <hostnameType>{dns_options['HostnameType']}</hostnameType>
+ <enableResourceNameDnsARecord>{'true' if dns_options['EnableResourceNameDnsARecord'] else 'false'}</enableResourceNameDnsARecord>
+ <enableResourceNameDnsAAAARecord>{'true' if dns_options['EnableResourceNameDnsAAAARecord'] else 'false'}</enableResourceNameDnsAAAARecord>
+ </privateDnsNameOptionsOnLaunch>
{_tag_set_xml(subnet['SubnetId'])}
</{tag}>"""
@@ -4358,21 +4392,37 @@ def _igw_xml(igw):
return _igw_fields_xml(igw, tag="item")
+# A route record's members as DescribeRouteTables names them. A gateway
+# endpoint target is answered as gatewayId, as on AWS.
+_ROUTE_MEMBERS = (
+ ("DestinationIpv6CidrBlock", "destinationIpv6CidrBlock"),
+ ("DestinationPrefixListId", "destinationPrefixListId"),
+ ("GatewayId", "gatewayId"),
+ ("VpcEndpointId", "gatewayId"),
+ ("NatGatewayId", "natGatewayId"),
+ ("InstanceId", "instanceId"),
+ ("VpcPeeringConnectionId", "vpcPeeringConnectionId"),
+ ("TransitGatewayId", "transitGatewayId"),
+ ("NetworkInterfaceId", "networkInterfaceId"),
+ ("EgressOnlyInternetGatewayId", "egressOnlyInternetGatewayId"),
+ ("CarrierGatewayId", "carrierGatewayId"),
+ ("LocalGatewayId", "localGatewayId"),
+ ("CoreNetworkArn", "coreNetworkArn"),
+ ("OdbNetworkArn", "odbNetworkArn"),
+)
+
+
def _rtb_fields_xml(rtb, tag="item"):
def _route_xml(r):
- target = ""
- if r.get("GatewayId"):
- target = f"<gatewayId>{r['GatewayId']}</gatewayId>"
- if r.get("NatGatewayId"):
- target += f"<natGatewayId>{r['NatGatewayId']}</natGatewayId>"
- if r.get("InstanceId"):
- target += f"<instanceId>{r['InstanceId']}</instanceId>"
- if r.get("VpcPeeringConnectionId"):
- target += f"<vpcPeeringConnectionId>{r['VpcPeeringConnectionId']}</vpcPeeringConnectionId>"
- if r.get("TransitGatewayId"):
- target += f"<transitGatewayId>{r['TransitGatewayId']}</transitGatewayId>"
+ # Every target and destination member a route can carry; an IPv6 or
+ # prefix-list route has no destinationCidrBlock, and one rendered
+ # empty read back as a route to "".
+ target = "".join(
+ f"<{element}>{_esc(r[key])}</{element}>"
+ for key, element in _ROUTE_MEMBERS if r.get(key))
+ if not any(r.get(key) for key in ("DestinationIpv6CidrBlock", "DestinationPrefixListId")):
+ target = f"<destinationCidrBlock>{r.get('DestinationCidrBlock', '')}</destinationCidrBlock>" + target
return f"""<item>
- <destinationCidrBlock>{r.get('DestinationCidrBlock','')}</destinationCidrBlock>
{target}
<state>{r.get('State','active')}</state>
<origin>{r.get('Origin','')}</origin>
@@ -6666,7 +6716,7 @@ def _create_launch_template(p):
<createdBy>arn:aws:iam::{get_account_id()}:root</createdBy>
<defaultVersionNumber>1</defaultVersionNumber>
<latestVersionNumber>1</latestVersionNumber>
- <tags>{tags_xml}</tags>
+ <tagSet>{tags_xml}</tagSet>
</launchTemplate>""")
@@ -6741,7 +6791,7 @@ def _describe_launch_templates(p):
<createdBy>arn:aws:iam::{get_account_id()}:root</createdBy>
<defaultVersionNumber>{lt['DefaultVersionNumber']}</defaultVersionNumber>
<latestVersionNumber>{lt['LatestVersionNumber']}</latestVersionNumber>
- <tags>{tags_xml}</tags>
+ <tagSet>{tags_xml}</tagSet>
</item>"""
return _xml(200, "DescribeLaunchTemplatesResponse",
f"<launchTemplates>{items}</launchTemplates>")
@@ -6763,7 +6813,8 @@ def _describe_launch_template_versions(p):
"The specified launch template does not exist", 400)
# Filter by version numbers
req_versions = _parse_member_list(p, "LaunchTemplateVersion")
- versions = lt["Versions"]
+ # Newest first, as AWS lists them (measured 2026-09-21).
+ versions = sorted(lt["Versions"], key=lambda v: v["VersionNumber"], reverse=True)
if req_versions:
filtered = []
for rv in req_versions:
diff --git a/tests/test_autoscaling.py b/tests/test_autoscaling.py
index 54a26882..e178d43f 100644
--- a/tests/test_autoscaling.py
+++ b/tests/test_autoscaling.py
@@ -1,4 +1,8 @@
+import datetime
import os
+import urllib.error
+import urllib.parse
+import urllib.request
import uuid
import boto3
@@ -437,6 +441,127 @@ def test_put_and_describe_scaling_policy(autoscaling):
autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)
+def test_put_scaling_policy_target_tracking_and_step_read_back(autoscaling):
+ """PutScalingPolicy stored neither TargetTrackingConfiguration nor
+ StepAdjustments (nor the warmup, aggregation and magnitude members), and
+ DescribePolicies answered AdjustmentType, ScalingAdjustment and Cooldown
+ for every type. The shape is AWS's, measured 2026-09-21: a
+ target-tracking policy has none of those three, a step policy no
+ ScalingAdjustment or Cooldown, and both carry Enabled and
+ StepAdjustments."""
+ asg = _uid("asg-ttpol")
+ autoscaling.create_auto_scaling_group(
+ AutoScalingGroupName=asg, MinSize=0, MaxSize=2,
+ AvailabilityZones=["us-east-1a"], LaunchConfigurationName="dummy-lc",
+ )
+ tracking = {
+ "CustomizedMetricSpecification": {
+ "MetricName": "CPUUtilization", "Namespace": "AWS/EC2",
+ "Dimensions": [{"Name": "AutoScalingGroupName", "Value": asg}],
+ "Statistic": "Average", "Unit": "Percent",
+ },
+ "TargetValue": 50.5,
+ "DisableScaleIn": True,
+ }
+ steps = [
+ {"MetricIntervalLowerBound": 0.0, "MetricIntervalUpperBound": 10.0, "ScalingAdjustment": 10},
+ {"MetricIntervalLowerBound": 10.0, "ScalingAdjustment": 20},
+ ]
+ try:
+ autoscaling.put_scaling_policy(
+ AutoScalingGroupName=asg, PolicyName="tt", PolicyType="TargetTrackingScaling",
+ TargetTrackingConfiguration=tracking, EstimatedInstanceWarmup=120,
+ )
+ autoscaling.put_scaling_policy(
+ AutoScalingGroupName=asg, PolicyName="step", PolicyType="StepScaling",
+ AdjustmentType="PercentChangeInCapacity", MinAdjustmentMagnitude=1,
+ MetricAggregationType="Average", StepAdjustments=steps,
+ )
+ policies = {p["PolicyName"]: p for p in autoscaling.describe_policies(
+ AutoScalingGroupName=asg)["ScalingPolicies"]}
+ tt, step = policies["tt"], policies["step"]
+ assert tt["TargetTrackingConfiguration"] == tracking
+ assert tt["EstimatedInstanceWarmup"] == 120
+ assert tt["Enabled"] is True and tt["StepAdjustments"] == []
+ assert not {"AdjustmentType", "ScalingAdjustment", "Cooldown"} & set(tt)
+ assert step["StepAdjustments"] == steps
+ assert step["AdjustmentType"] == "PercentChangeInCapacity"
+ assert step["MinAdjustmentMagnitude"] == 1
+ assert step["MetricAggregationType"] == "Average"
+ assert not {"ScalingAdjustment", "Cooldown"} & set(step)
+ finally:
+ for name in ("tt", "step"):
+ autoscaling.delete_policy(AutoScalingGroupName=asg, PolicyName=name)
+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)
+
+
+def test_put_scaling_policy_predictive_read_back(autoscaling):
+ """PutScalingPolicy dropped PredictiveScalingConfiguration. AWS answers it
+ with MaxCapacityBreachBehavior defaulted to HonorMaxCapacity and
+ TargetValue as a double (measured 2026-09-21)."""
+ asg = _uid("asg-pred")
+ autoscaling.create_auto_scaling_group(
+ AutoScalingGroupName=asg, MinSize=0, MaxSize=2,
+ AvailabilityZones=["us-east-1a"], LaunchConfigurationName="dummy-lc",
+ )
+ config = {"Mode": "ForecastOnly", "MetricSpecifications": [{
+ "TargetValue": 40.0,
+ "PredefinedMetricPairSpecification": {"PredefinedMetricType": "ASGCPUUtilization"}}]}
+ try:
+ autoscaling.put_scaling_policy(
+ AutoScalingGroupName=asg, PolicyName="pred", PolicyType="PredictiveScaling",
+ PredictiveScalingConfiguration=config)
+ policy = autoscaling.describe_policies(AutoScalingGroupName=asg)["ScalingPolicies"][0]
+ assert policy["PredictiveScalingConfiguration"] == {
+ **config, "MaxCapacityBreachBehavior": "HonorMaxCapacity"}
+ assert not {"AdjustmentType", "ScalingAdjustment", "Cooldown"} & set(policy)
+ finally:
+ autoscaling.delete_policy(AutoScalingGroupName=asg, PolicyName="pred")
+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)
+
+
[email protected]("members", [
+ {"PolicyType": "TargetTrackingScaling",
+ "TargetTrackingConfiguration.PredefinedMetricSpecification.PredefinedMetricType":
+ "ASGAverageCPUUtilization",
+ "TargetTrackingConfiguration.TargetValue": "fifty"},
+ {"PolicyType": "StepScaling", "AdjustmentType": "ChangeInCapacity",
+ "StepAdjustments.member.1.MetricIntervalLowerBound": "zero",
+ "StepAdjustments.member.1.ScalingAdjustment": "1"},
+ {"PolicyType": "SimpleScaling", "ScalingAdjustment": "one"},
+], ids=["target-value", "step-bound", "scaling-adjustment"])
+def test_put_scaling_policy_non_numeric_member_is_a_validation_error(autoscaling, members):
+ """A number member that does not parse (a TargetValue, a step bound, a
+ ScalingAdjustment) is refused with a ValidationError. The float()/int()
+ conversion raised out of the handler, so the call answered 500. Sent raw:
+ boto3 will not serialize a string where the model has a number."""
+ asg = _uid("asg-badnum")
+ autoscaling.create_auto_scaling_group(
+ AutoScalingGroupName=asg, MinSize=0, MaxSize=2,
+ AvailabilityZones=["us-east-1a"], LaunchConfigurationName="dummy-lc",
+ )
+ body = urllib.parse.urlencode({
+ "Action": "PutScalingPolicy", "Version": "2011-01-01",
+ "AutoScalingGroupName": asg, "PolicyName": "bad", **members,
+ }).encode()
+ req = urllib.request.Request(
+ os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566") + "/",
+ data=body, method="POST",
+ headers={"Content-Type": "application/x-www-form-urlencoded",
+ "Authorization": ("AWS4-HMAC-SHA256 Credential=test/20260921/"
+ "us-east-1/autoscaling/aws4_request, "
+ "SignedHeaders=, Signature=x")},
+ )
+ try:
+ with pytest.raises(urllib.error.HTTPError) as exc:
+ urllib.request.urlopen(req, timeout=10)
+ assert exc.value.code == 400
+ assert b"<Code>ValidationError</Code>" in exc.value.read()
+ assert autoscaling.describe_policies(AutoScalingGroupName=asg)["ScalingPolicies"] == []
+ finally:
+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)
+
+
def test_describe_policies_empty(autoscaling):
resp = autoscaling.describe_policies(AutoScalingGroupName=_uid("no-asg"))
assert resp["ScalingPolicies"] == []
@@ -670,6 +795,30 @@ def test_put_and_describe_scheduled_action(autoscaling):
autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)
+def test_scheduled_action_times_read_back(autoscaling):
+ """PutScheduledUpdateGroupAction dropped StartTime, EndTime and TimeZone.
+ AWS answers all three, StartTime also as Time (measured 2026-09-21)."""
+ asg = _uid("asg-stimes")
+ autoscaling.create_auto_scaling_group(
+ AutoScalingGroupName=asg, MinSize=0, MaxSize=2,
+ AvailabilityZones=["us-east-1a"], LaunchConfigurationName="dummy-lc",
+ )
+ start = datetime.datetime(2027, 1, 4, 9, tzinfo=datetime.timezone.utc)
+ end = datetime.datetime(2027, 6, 1, tzinfo=datetime.timezone.utc)
+ try:
+ autoscaling.put_scheduled_update_group_action(
+ AutoScalingGroupName=asg, ScheduledActionName="times",
+ Recurrence="0 9 * * *", StartTime=start, EndTime=end,
+ TimeZone="Europe/Berlin", MinSize=0, MaxSize=1)
+ action = autoscaling.describe_scheduled_actions(
+ AutoScalingGroupName=asg)["ScheduledUpdateGroupActions"][0]
+ assert (action["StartTime"], action["Time"], action["EndTime"], action["TimeZone"]) == (
+ start, start, end, "Europe/Berlin")
+ finally:
+ autoscaling.delete_scheduled_action(AutoScalingGroupName=asg, ScheduledActionName="times")
+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)
+
+
def test_describe_scheduled_actions_empty(autoscaling):
resp = autoscaling.describe_scheduled_actions(
AutoScalingGroupName=_uid("no-sched")
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index aa66f317..06c527af 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -55,6 +55,14 @@ _FAILING_RESOURCE = {
}
+def _cfn_with_failing_resource(body, depends_on):
+ """The template ``body`` plus _FAILING_RESOURCE after ``depends_on``, so
+ an update to it fails once that resource is updated and rolls back."""
+ template = json.loads(body)
+ template["Resources"]["Bad"] = {**_FAILING_RESOURCE, "DependsOn": depends_on}
+ return json.dumps(template)
+
+
def _wait_stack(cfn, name, timeout=30):
"""Poll until stack reaches terminal status.
@@ -16882,12 +16890,16 @@ def test_cfn_create_rollback_delete_failure_lands_rollback_failed(cfn, lam):
pass
-def test_cfn_update_rollback_delete_failure_lands_update_rollback_failed(cfn, lam):
- """An update rollback whose delete fails lands UPDATE_ROLLBACK_FAILED and
- keeps the previous resources on the stack."""
+def test_cfn_update_rollback_cleanup_delete_failure_still_completes(cfn, lam):
+ """What the failed update created is deleted in the cleanup phase, after
+ the rollback is complete (UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS on
+ AWS, measured 2026-09-21). A delete that fails there is a DELETE_FAILED
+ event on the resource and the stack still lands UPDATE_ROLLBACK_COMPLETE
+ with the previous resources; it used to turn the stack into
+ UPDATE_ROLLBACK_FAILED."""
suffix = _uuid_mod.uuid4().hex[:8]
fn = f"cr-urb-fail-{suffix}"
- stack_name = f"cfn-update-rollback-failed-{suffix}"
+ stack_name = f"cfn-update-rollback-cleanup-{suffix}"
topic_name = f"cfn-urb-topic-{suffix}"
lam.create_function(
FunctionName=fn,
@@ -16923,9 +16935,95 @@ def test_cfn_update_rollback_delete_failure_lands_update_rollback_failed(cfn, la
cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(updated))
stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+
+ retained = cfn.describe_stack_resources(StackName=stack_name)["StackResources"]
+ assert [r["LogicalResourceId"] for r in retained] == ["Topic"]
+
+ events = cfn.describe_stack_events(StackName=stack_name)["StackEvents"]
+ assert any(e["LogicalResourceId"] == "CR" and e["ResourceStatus"] == "DELETE_FAILED"
+ for e in events)
+ assert not any(e["ResourceType"] == "AWS::CloudFormation::Stack"
+ and e["ResourceStatus"] == "UPDATE_ROLLBACK_FAILED"
+ for e in events)
+ finally:
+ try:
+ lam.update_function_code(
+ FunctionName=fn, ZipFile=_cr_make_zip(_CR_HANDLER_SUCCESS)
+ )
+ except ClientError:
+ pass
+ _delete_cfn_test_stack(cfn, stack_name)
+ try:
+ lam.delete_function(FunctionName=fn)
+ except ClientError:
+ pass
+
+
+# Refuses the Update that takes Mode back to "before", which is what the
+# rollback of a before -> after update sends; every other request succeeds.
+_CR_HANDLER_REVERT_FAILS = """\
+import json, urllib.request
+
+def handler(event, context):
+ reverting = (event["RequestType"] == "Update"
+ and event["ResourceProperties"].get("Mode") == "before")
+ payload = json.dumps({
+ "Status": "FAILED" if reverting else "SUCCESS",
+ "Reason": "revert refused for testing",
+ "RequestId": event["RequestId"],
+ "StackId": event["StackId"],
+ "LogicalResourceId": event["LogicalResourceId"],
+ "PhysicalResourceId": event.get("PhysicalResourceId", "revert-fails-cr"),
+ }).encode()
+ req = urllib.request.Request(
+ event["ResponseURL"],
+ data=payload,
+ method="PUT",
+ headers={"content-type": "", "content-length": str(len(payload))},
+ )
+ urllib.request.urlopen(req, timeout=10)
+"""
+
+
+def _cr_revert_fails_templates(fn, topic_name):
+ """A stack whose custom resource goes from Mode before to after beside a
+ resource that fails, so the rollback has to send the custom resource back
+ and _CR_HANDLER_REVERT_FAILS refuses that."""
+ def template(mode, with_bad):
+ resources = {
+ "Topic": {"Type": "AWS::SNS::Topic", "Properties": {"TopicName": topic_name}},
+ "CR": {"Type": "Custom::Tester", "Properties": {
+ "ServiceToken": f"arn:aws:lambda:us-east-1:000000000000:function:{fn}",
+ "Mode": mode}},
+ }
+ if with_bad:
+ resources["Bad"] = {**_FAILING_RESOURCE, "DependsOn": "CR"}
+ return json.dumps({"Resources": resources})
+ return template("before", False), template("after", True)
+
+
+def test_cfn_update_rollback_revert_failure_lands_update_rollback_failed(cfn, lam):
+ """An update rollback that cannot send a resource back to its previous
+ properties lands UPDATE_ROLLBACK_FAILED and keeps the previous resources
+ on the stack."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ fn = f"cr-urb-revert-{suffix}"
+ stack_name = f"cfn-update-rollback-failed-{suffix}"
+ lam.create_function(
+ FunctionName=fn, Runtime="python3.12", Role=_CR_LAMBDA_ROLE, Handler="index.handler",
+ Code={"ZipFile": _cr_make_zip(_CR_HANDLER_REVERT_FAILS)},
+ )
+ base, updated = _cr_revert_fails_templates(fn, f"cfn-urb-topic-{suffix}")
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=base)
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=updated)
+ stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "UPDATE_ROLLBACK_FAILED", stack.get("StackStatusReason")
- # The pre-update resources survive on the stack.
retained = cfn.describe_stack_resources(StackName=stack_name)["StackResources"]
assert "Topic" in [r["LogicalResourceId"] for r in retained]
@@ -16982,16 +17080,11 @@ def test_cfn_continue_update_rollback_recovers_the_stack(cfn, lam):
stack_name = f"cfn-continue-rollback-{suffix}"
lam.create_function(
FunctionName=fn, Runtime="python3.12", Role=_CR_LAMBDA_ROLE, Handler="index.handler",
- Code={"ZipFile": _cr_make_zip(_CR_HANDLER_DELETE_FAILS)},
+ Code={"ZipFile": _cr_make_zip(_CR_HANDLER_REVERT_FAILS)},
)
- base = {"Resources": {"Topic": {"Type": "AWS::SNS::Topic",
- "Properties": {"TopicName": f"cfn-cur-{suffix}"}}}}
- updated = json.loads(json.dumps(base))
- updated["Resources"]["CR"] = {"Type": "Custom::Tester", "Properties": {
- "ServiceToken": f"arn:aws:lambda:us-east-1:000000000000:function:{fn}"}}
- updated["Resources"]["Bad"] = {**_FAILING_RESOURCE, "DependsOn": "CR"}
+ base, updated = _cr_revert_fails_templates(fn, f"cfn-cur-{suffix}")
try:
- cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(base))
+ cfn.create_stack(StackName=stack_name, TemplateBody=base)
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
with pytest.raises(ClientError) as exc:
@@ -16999,7 +17092,7 @@ def test_cfn_continue_update_rollback_recovers_the_stack(cfn, lam):
assert "cannot be called from current stack status" in (
exc.value.response["Error"]["Message"])
- cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(updated))
+ cfn.update_stack(StackName=stack_name, TemplateBody=updated)
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "UPDATE_ROLLBACK_FAILED", stack.get("StackStatusReason")
@@ -17011,17 +17104,16 @@ def test_cfn_continue_update_rollback_recovers_the_stack(cfn, lam):
cfn.continue_update_rollback(StackName=stack_name, ResourcesToSkip=["Topic"])
assert "Topic" in exc.value.response["Error"]["Message"]
- # Once the resource can be deleted, the retry completes the rollback
- # without skipping anything.
+ # Once the resource can be sent back, the retry completes the
+ # rollback without skipping anything.
lam.update_function_code(FunctionName=fn, ZipFile=_cr_make_zip(_CR_HANDLER_SUCCESS))
cfn.continue_update_rollback(StackName=stack_name)
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
- events = cfn.describe_stack_events(StackName=stack_name)["StackEvents"]
- assert any(e["LogicalResourceId"] == "CR" and e["ResourceStatus"] == "DELETE_COMPLETE"
- for e in events)
+ resources = cfn.describe_stack_resources(StackName=stack_name)["StackResources"]
+ assert sorted(r["LogicalResourceId"] for r in resources) == ["CR", "Topic"]
- again = json.loads(json.dumps(base))
+ again = json.loads(base)
again["Resources"]["Topic"]["Properties"]["DisplayName"] = "after"
cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(again))
stack = _wait_stack(cfn, stack_name)
@@ -17046,18 +17138,13 @@ def test_cfn_continue_update_rollback_skips_the_named_resource(cfn, lam):
stack_name = f"cfn-continue-skip-{suffix}"
lam.create_function(
FunctionName=fn, Runtime="python3.12", Role=_CR_LAMBDA_ROLE, Handler="index.handler",
- Code={"ZipFile": _cr_make_zip(_CR_HANDLER_DELETE_FAILS)},
+ Code={"ZipFile": _cr_make_zip(_CR_HANDLER_REVERT_FAILS)},
)
- base = {"Resources": {"Topic": {"Type": "AWS::SNS::Topic",
- "Properties": {"TopicName": f"cfn-cur-skip-{suffix}"}}}}
- updated = json.loads(json.dumps(base))
- updated["Resources"]["CR"] = {"Type": "Custom::Tester", "Properties": {
- "ServiceToken": f"arn:aws:lambda:us-east-1:000000000000:function:{fn}"}}
- updated["Resources"]["Bad"] = {**_FAILING_RESOURCE, "DependsOn": "CR"}
+ base, updated = _cr_revert_fails_templates(fn, f"cfn-cur-skip-{suffix}")
try:
- cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(base))
+ cfn.create_stack(StackName=stack_name, TemplateBody=base)
assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
- cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(updated))
+ cfn.update_stack(StackName=stack_name, TemplateBody=updated)
assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_ROLLBACK_FAILED"
cfn.continue_update_rollback(StackName=stack_name, ResourcesToSkip=["CR"])
@@ -17065,6 +17152,7 @@ def test_cfn_continue_update_rollback_skips_the_named_resource(cfn, lam):
assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
events = cfn.describe_stack_events(StackName=stack_name)["StackEvents"]
assert any(e["LogicalResourceId"] == "CR" and e["ResourceStatus"] == "UPDATE_COMPLETE"
+ and e.get("ResourceStatusReason") == "Resource rollback skipped by user"
for e in events)
finally:
try:
@@ -17214,6 +17302,110 @@ def test_cfn_appsync_schema_stack_delete_removes_schema(cfn, appsync):
pass
+def _cfn_output(cfn, stack_name, key):
+ return next(o["OutputValue"]
+ for o in cfn.describe_stacks(StackName=stack_name)["Stacks"][0]["Outputs"]
+ if o["OutputKey"] == key)
+
+
+def _cfn_appsync_members_template(name, api_props, oidc):
+ return json.dumps({
+ "Resources": {
+ "Api": {"Type": "AWS::AppSync::GraphQLApi", "Properties": {
+ "Name": f"{name}_a", "AuthenticationType": "API_KEY", **api_props}},
+ "Oidc": {"Type": "AWS::AppSync::GraphQLApi", "Properties": {
+ "Name": f"{name}_b", "AuthenticationType": "OPENID_CONNECT",
+ "OpenIDConnectConfig": oidc}},
+ },
+ "Outputs": {"ApiId": {"Value": {"Fn::GetAtt": ["Api", "ApiId"]}},
+ "OidcId": {"Value": {"Fn::GetAtt": ["Oidc", "ApiId"]}}},
+ })
+
+
+def test_cfn_ecs_cluster_settings_read_back_in_the_api_shape(cfn, ecs):
+ """ClusterSettings, DefaultCapacityProviderStrategy and Configuration were
+ stored in the template's PascalCase while DescribeClusters serializes the
+ API's camelCase, so botocore dropped every member and answered a list of
+ empty objects, before and after any update. The cluster itself needs no
+ update handler: the create rebuilds the record from the template and
+ DescribeClusters recomputes the counters. Measured on AWS 2026-09-21 (with
+ include SETTINGS and CONFIGURATIONS): containerInsights enabled, FARGATE
+ weight 1 base 0, executeCommandConfiguration logging DEFAULT -> NONE."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-ecs-cl-{suffix}"
+ cluster = f"cfn-ecs-cl-{suffix}"
+
+ def template(setting, logging):
+ return json.dumps({
+ "Resources": {
+ "Cluster": {
+ "Type": "AWS::ECS::Cluster",
+ "Properties": {
+ "ClusterName": cluster,
+ "ClusterSettings": [
+ {"Name": "containerInsights", "Value": setting},
+ ],
+ "CapacityProviders": ["FARGATE"],
+ "DefaultCapacityProviderStrategy": [
+ {"CapacityProvider": "FARGATE", "Weight": 1, "Base": 0},
+ ],
+ "Configuration": {
+ "ExecuteCommandConfiguration": {"Logging": logging},
+ },
+ "Tags": [{"Key": "stage", "Value": setting}],
+ },
+ },
+ "TD": {
+ "Type": "AWS::ECS::TaskDefinition",
+ "Properties": {
+ "Family": f"cfn-ecs-td-{suffix}",
+ "ContainerDefinitions": [
+ {"Name": "app", "Image": "nginx", "Memory": 128},
+ ],
+ },
+ },
+ "Service": {
+ "Type": "AWS::ECS::Service",
+ "Properties": {
+ "Cluster": {"Ref": "Cluster"},
+ "ServiceName": f"cfn-ecs-svc-{suffix}",
+ "TaskDefinition": {"Ref": "TD"},
+ "DesiredCount": 1,
+ },
+ },
+ },
+ })
+
+ def described():
+ return ecs.describe_clusters(
+ clusters=[cluster], include=["SETTINGS", "CONFIGURATIONS"])["clusters"][0]
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("disabled", "DEFAULT"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ before = described()
+ assert before["settings"] == [{"name": "containerInsights", "value": "disabled"}]
+ assert before["defaultCapacityProviderStrategy"] == [
+ {"capacityProvider": "FARGATE", "weight": 1, "base": 0}]
+ assert before["configuration"] == {
+ "executeCommandConfiguration": {"logging": "DEFAULT"}}
+ assert before["activeServicesCount"] == 1
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("enabled", "NONE"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+
+ after = described()
+ assert after["settings"] == [
+ {"name": "containerInsights", "value": "enabled"}]
+ assert after["configuration"] == {
+ "executeCommandConfiguration": {"logging": "NONE"}}
+ assert after["activeServicesCount"] == 1
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
# ===========================================================================
# In-place update handlers — deploy, update a mutable property, assert the
# physical id survived and the new value is visible through the service API
@@ -21722,13 +21914,13 @@ def test_cfn_iam_instance_profile_path_change_under_generated_name_replaces_it(c
def test_cfn_update_rollback_keeps_the_resources_that_existed_before(cfn, sqs, ddb):
- """A failed update rolls back only what the update created. The queue
+ """A failed update deletes only what the update created. The queue
existed before the update and kept its physical id through an in-place
- change, so the rollback leaves it alone; the queue the update added is
- deleted; the table, whose attribute type change is refused under its
- custom name, is what fails the update. The in-place change itself is not
- reverted: the queue keeps the new VisibilityTimeout while the stack
- records the old template."""
+ change, so the rollback does not delete it: it updates it back to the
+ properties the restored stack records, with UPDATE_IN_PROGRESS and
+ UPDATE_COMPLETE events, as AWS does during UPDATE_ROLLBACK_IN_PROGRESS.
+ The queue the update added is deleted; the table, whose attribute type
+ change is refused under its custom name, is what fails the update."""
uid = _uuid_mod.uuid4().hex[:8]
stack_name = f"cfn-rb-keep-{uid}"
queue_name = f"cfn-rb-keep-{uid}"
@@ -21767,13 +21959,27 @@ def test_cfn_update_rollback_keeps_the_resources_that_existed_before(cfn, sqs, d
and e["ResourceStatus"].startswith("DELETE")]
assert [e for e in events if e["LogicalResourceId"] == "Added"
and e["ResourceStatus"] == "DELETE_COMPLETE"]
+ # The rollback as AWS records it (measured 2026-09-21 on this template):
+ # the queue updated back first, the refused table marked complete, and
+ # only then the added queue deleted in the cleanup phase.
+ rollback = next(i for i, e in enumerate(events)
+ if e["LogicalResourceId"] == stack_name
+ and e["ResourceStatus"] == "UPDATE_ROLLBACK_IN_PROGRESS")
+ assert [(e["LogicalResourceId"], e["ResourceStatus"])
+ for e in reversed(events[:rollback])
+ if e["LogicalResourceId"] != stack_name
+ and e["ResourceStatus"] != "DELETE_IN_PROGRESS"] == [
+ ("Queue", "UPDATE_IN_PROGRESS"), ("Queue", "UPDATE_COMPLETE"),
+ ("Table", "UPDATE_COMPLETE"), ("Added", "DELETE_COMPLETE")]
assert sqs.get_queue_url(QueueName=queue_name)["QueueUrl"] == queue_url
attributes = sqs.get_queue_attributes(
QueueUrl=queue_url, AttributeNames=["VisibilityTimeout", "ApproximateNumberOfMessages"]
)["Attributes"]
assert attributes["ApproximateNumberOfMessages"] == "1"
- assert attributes["VisibilityTimeout"] == "45" # the in-place change is not reverted
+ # Back to the value before the update: the rollback reverts an in-place
+ # change instead of leaving the queue at 45 under a stack that records 30.
+ assert attributes["VisibilityTimeout"] == "30"
with pytest.raises(ClientError):
sqs.get_queue_url(QueueName=added_name)
table = ddb.describe_table(TableName=table_name)["Table"]
@@ -21839,9 +22045,10 @@ def test_cfn_update_rollback_deletes_the_replacement_and_keeps_the_old_resource(
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
for logical_id, new_pid in (("Queue", new_url), ("Param", new_param)):
+ # DELETE_IN_PROGRESS then DELETE_COMPLETE, both for the replacement.
deleted = [pid for status, pid in _resource_events(cfn, stack_name, logical_id)
if status.startswith("DELETE")]
- assert deleted == [new_pid], (logical_id, deleted)
+ assert deleted == [new_pid, new_pid], (logical_id, deleted)
assert _queue_exists(sqs, old_name) and not _queue_exists(sqs, new_name)
assert param_exists(old_param) and not param_exists(new_param)
resources = {r["LogicalResourceId"]: r["PhysicalResourceId"]
diff --git a/tests/test_cfn_update_appconfig.py b/tests/test_cfn_update_appconfig.py
new file mode 100644
index 00000000..cad789dc
--- /dev/null
+++ b/tests/test_cfn_update_appconfig.py
@@ -0,0 +1,253 @@
+"""CloudFormation updates of AppConfig resources, in place and rolled back."""
+
+import json
+import uuid as _uuid_mod
+
+import pytest
+from botocore.exceptions import ClientError
+from test_cfn import (
+ _FAILING_RESOURCE,
+ _cfn_output,
+ _delete_cfn_test_stack,
+ _wait_stack,
+)
+
+
+def test_cfn_appconfig_application_updates_in_place(cfn, appconfig_client):
+ """Name, Description and Tags are No interruption on
+ AWS::AppConfig::Application, and the type has no replacing property: the
+ application id survives the update. Without the handler the create ran
+ again and minted a second application."""
+ # Unique per run, so a rerun or a parallel worker cannot collide.
+ suffix = _uuid_mod.uuid4().hex[:8]
+ name = f"cfn-ac-app-update-{suffix}"
+
+ def template(description):
+ return json.dumps({
+ "Resources": {
+ "App": {
+ "Type": "AWS::AppConfig::Application",
+ "Properties": {
+ "Name": name,
+ "Description": description,
+ "Tags": [{"Key": "stage", "Value": description}],
+ },
+ },
+ },
+ "Outputs": {"AppId": {"Value": {"Ref": "App"}}},
+ })
+
+ try:
+ cfn.create_stack(StackName=f"cfn-ac-app-{suffix}", TemplateBody=template("before"))
+ _wait_stack(cfn, f"cfn-ac-app-{suffix}")
+ app_id = _cfn_output(cfn, f"cfn-ac-app-{suffix}", "AppId")
+ assert appconfig_client.get_application(ApplicationId=app_id)["Name"] == name
+
+ cfn.update_stack(StackName=f"cfn-ac-app-{suffix}", TemplateBody=template("after"))
+ assert _wait_stack(cfn, f"cfn-ac-app-{suffix}")["StackStatus"] == "UPDATE_COMPLETE"
+
+ assert _cfn_output(cfn, f"cfn-ac-app-{suffix}", "AppId") == app_id, (
+ "the update minted a second application")
+ assert appconfig_client.get_application(ApplicationId=app_id)["Description"] == "after"
+
+ arn = f"arn:aws:appconfig:us-east-1:000000000000:application/{app_id}"
+ assert appconfig_client.list_tags_for_resource(
+ ResourceArn=arn)["Tags"]["stage"] == "after"
+ finally:
+ _delete_cfn_test_stack(cfn, f"cfn-ac-app-{suffix}")
+
+
+def test_cfn_appconfig_application_description_change_is_rolled_back(cfn, appconfig_client):
+ """A description change is applied in place, so a later failure in the
+ same update has to set it back. Measured on AWS 2026-09-21: the
+ application reads its old description after UPDATE_ROLLBACK_COMPLETE,
+ under the same id."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-ac-rb-{suffix}"
+
+ def template(description, with_bad):
+ resources = {"App": {"Type": "AWS::AppConfig::Application", "Properties": {
+ "Name": f"cfn-ac-rb-{suffix}", "Description": description}}}
+ if with_bad:
+ resources["Bad"] = {**_FAILING_RESOURCE, "DependsOn": "App"}
+ return json.dumps({"Resources": resources,
+ "Outputs": {"AppId": {"Value": {"Ref": "App"}}}})
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("before", False))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ app_id = next(o["OutputValue"] for o in
+ cfn.describe_stacks(StackName=stack_name)["Stacks"][0]["Outputs"]
+ if o["OutputKey"] == "AppId")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("after", True))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ assert appconfig_client.get_application(ApplicationId=app_id)["Description"] == "before"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_appconfig_environment_updates_in_place(cfn, appconfig_client):
+ """Description, Monitors and Name are No interruption on
+ AWS::AppConfig::Environment, so the environment id survives."""
+ # Unique per run, so a rerun or a parallel worker cannot collide.
+ suffix = _uuid_mod.uuid4().hex[:8]
+ def template(description):
+ return json.dumps({
+ "Resources": {
+ "App": {
+ "Type": "AWS::AppConfig::Application",
+ "Properties": {"Name": f"cfn-ac-env-app-{suffix}"},
+ },
+ "Env": {
+ "Type": "AWS::AppConfig::Environment",
+ "Properties": {
+ "ApplicationId": {"Ref": "App"},
+ "Name": f"cfn-ac-env-{suffix}",
+ "Description": description,
+ },
+ },
+ },
+ "Outputs": {"AppId": {"Value": {"Ref": "App"}},
+ "EnvId": {"Value": {"Ref": "Env"}}},
+ })
+
+ try:
+ cfn.create_stack(StackName=f"cfn-ac-env-{suffix}", TemplateBody=template("before"))
+ _wait_stack(cfn, f"cfn-ac-env-{suffix}")
+ app_id = _cfn_output(cfn, f"cfn-ac-env-{suffix}", "AppId")
+ env_id = _cfn_output(cfn, f"cfn-ac-env-{suffix}", "EnvId")
+
+ cfn.update_stack(StackName=f"cfn-ac-env-{suffix}", TemplateBody=template("after"))
+ assert _wait_stack(cfn, f"cfn-ac-env-{suffix}")["StackStatus"] == "UPDATE_COMPLETE"
+
+ envs = appconfig_client.list_environments(ApplicationId=app_id)["Items"]
+ assert len(envs) == 1, "the update minted a second environment"
+ assert envs[0]["Id"] == env_id
+ assert envs[0]["Description"] == "after"
+ finally:
+ _delete_cfn_test_stack(cfn, f"cfn-ac-env-{suffix}")
+
+
+def test_cfn_appconfig_profile_update_keeps_hosted_versions(cfn, appconfig_client):
+ """A Description change on AWS::AppConfig::ConfigurationProfile is No
+ interruption. Hosted configuration versions are keyed by application and
+ profile id, so the create-fallback's fresh profile id orphaned every
+ version the stack had written."""
+ # Unique per run, so a rerun or a parallel worker cannot collide.
+ suffix = _uuid_mod.uuid4().hex[:8]
+ def template(description):
+ return json.dumps({
+ "Resources": {
+ "App": {
+ "Type": "AWS::AppConfig::Application",
+ "Properties": {"Name": f"cfn-ac-prof-app-{suffix}"},
+ },
+ "Profile": {
+ "Type": "AWS::AppConfig::ConfigurationProfile",
+ "Properties": {
+ "ApplicationId": {"Ref": "App"},
+ "Name": f"cfn-ac-prof-{suffix}",
+ "LocationUri": "hosted",
+ "Description": description,
+ },
+ },
+ "HCV": {
+ "Type": "AWS::AppConfig::HostedConfigurationVersion",
+ "Properties": {
+ "ApplicationId": {"Ref": "App"},
+ "ConfigurationProfileId": {"Ref": "Profile"},
+ "ContentType": "application/json",
+ "Content": "{\"flag\": true}",
+ },
+ },
+ },
+ "Outputs": {"AppId": {"Value": {"Ref": "App"}},
+ "ProfileId": {"Value": {"Ref": "Profile"}}},
+ })
+
+ try:
+ cfn.create_stack(StackName=f"cfn-ac-prof-{suffix}", TemplateBody=template("before"))
+ _wait_stack(cfn, f"cfn-ac-prof-{suffix}")
+ app_id = _cfn_output(cfn, f"cfn-ac-prof-{suffix}", "AppId")
+ profile_id = _cfn_output(cfn, f"cfn-ac-prof-{suffix}", "ProfileId")
+ assert appconfig_client.list_hosted_configuration_versions(
+ ApplicationId=app_id, ConfigurationProfileId=profile_id)["Items"]
+
+ cfn.update_stack(StackName=f"cfn-ac-prof-{suffix}", TemplateBody=template("after"))
+ assert _wait_stack(cfn, f"cfn-ac-prof-{suffix}")["StackStatus"] == "UPDATE_COMPLETE"
+
+ profiles = appconfig_client.list_configuration_profiles(
+ ApplicationId=app_id)["Items"]
+ assert len(profiles) == 1, "the update minted a second profile"
+ assert profiles[0]["Id"] == profile_id
+ # Description is not a member of ConfigurationProfileSummary, so the
+ # read that shows the change is GetConfigurationProfile.
+ assert appconfig_client.get_configuration_profile(
+ ApplicationId=app_id,
+ ConfigurationProfileId=profile_id)["Description"] == "after"
+ assert appconfig_client.list_hosted_configuration_versions(
+ ApplicationId=app_id, ConfigurationProfileId=profile_id
+ )["Items"], "the hosted configuration version was orphaned"
+ finally:
+ _delete_cfn_test_stack(cfn, f"cfn-ac-prof-{suffix}")
+
+
+def test_cfn_appconfig_deployment_strategy_update_and_rename(cfn, appconfig_client):
+ """GrowthFactor is No interruption on AWS::AppConfig::DeploymentStrategy
+ and Name is Replacement. The name is not the physical id, so the rename is
+ a plain replacement: a new strategy id, and the predecessor removed."""
+ # Unique per run, so a rerun or a parallel worker cannot collide.
+ suffix = _uuid_mod.uuid4().hex[:8]
+ def template(name, growth):
+ return json.dumps({
+ "Resources": {
+ "Strategy": {
+ "Type": "AWS::AppConfig::DeploymentStrategy",
+ "Properties": {
+ "Name": name,
+ "DeploymentDurationInMinutes": 1,
+ "GrowthFactor": growth,
+ "ReplicateTo": "NONE",
+ },
+ },
+ },
+ "Outputs": {"StrategyId": {"Value": {"Ref": "Strategy"}}},
+ })
+
+ def strategy():
+ # Through the stack's Ref: the list action pages at 50 without a
+ # NextToken, so a name scan misses strategies on a busy server.
+ strategy_id = _cfn_output(cfn, f"cfn-ac-strat-{suffix}", "StrategyId")
+ return appconfig_client.get_deployment_strategy(DeploymentStrategyId=strategy_id)
+
+ try:
+ cfn.create_stack(StackName=f"cfn-ac-strat-{suffix}",
+ TemplateBody=template(f"cfn-ac-strat-a-{suffix}", 10))
+ _wait_stack(cfn, f"cfn-ac-strat-{suffix}")
+ created = strategy()
+ assert created["Name"] == f"cfn-ac-strat-a-{suffix}"
+ strategy_id = created["Id"]
+
+ # In place: the growth factor changes under the same id.
+ cfn.update_stack(StackName=f"cfn-ac-strat-{suffix}",
+ TemplateBody=template(f"cfn-ac-strat-a-{suffix}", 25))
+ assert _wait_stack(cfn, f"cfn-ac-strat-{suffix}")["StackStatus"] == "UPDATE_COMPLETE"
+ same = strategy()
+ assert same["Id"] == strategy_id
+ assert same["GrowthFactor"] == 25
+
+ # Replacement: a new id, and the old strategy gone.
+ cfn.update_stack(StackName=f"cfn-ac-strat-{suffix}",
+ TemplateBody=template(f"cfn-ac-strat-b-{suffix}", 25))
+ assert _wait_stack(cfn, f"cfn-ac-strat-{suffix}")["StackStatus"] == "UPDATE_COMPLETE"
+ renamed = strategy()
+ assert renamed["Name"] == f"cfn-ac-strat-b-{suffix}"
+ assert renamed["Id"] != strategy_id
+ with pytest.raises(ClientError) as exc:
+ appconfig_client.get_deployment_strategy(DeploymentStrategyId=strategy_id)
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException", (
+ "the predecessor survived")
+ finally:
+ _delete_cfn_test_stack(cfn, f"cfn-ac-strat-{suffix}")
diff --git a/tests/test_cfn_update_appsync.py b/tests/test_cfn_update_appsync.py
new file mode 100644
index 00000000..f7fff0c8
--- /dev/null
+++ b/tests/test_cfn_update_appsync.py
@@ -0,0 +1,344 @@
+"""CloudFormation updates of AppSync GraphQL APIs and API keys, in place and rolled back."""
+
+import json
+import time
+import uuid as _uuid_mod
+
+from test_cfn import (
+ _FAILING_RESOURCE,
+ _cfn_appsync_members_template,
+ _cfn_output,
+ _delete_cfn_test_stack,
+ _wait_stack,
+)
+
+
+def test_cfn_appsync_api_update_keeps_id_and_children(cfn, appsync):
+ """Every property of AWS::AppSync::GraphQLApi is No interruption, so the
+ API keeps its id. The create-fallback minted a new one and re-seeded the
+ api-key, data-source, resolver and type stores under it, so the renamed
+ API came back empty and the real one was orphaned."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-appsync-upd-{suffix}"
+
+ def template(name):
+ return json.dumps({
+ "Resources": {
+ "Api": {
+ "Type": "AWS::AppSync::GraphQLApi",
+ "Properties": {"Name": name, "AuthenticationType": "API_KEY"},
+ },
+ "DS": {
+ "Type": "AWS::AppSync::DataSource",
+ "Properties": {
+ "ApiId": {"Fn::GetAtt": ["Api", "ApiId"]},
+ "Name": "probe_source",
+ "Type": "NONE",
+ },
+ },
+ },
+ "Outputs": {"ApiId": {"Value": {"Fn::GetAtt": ["Api", "ApiId"]}}},
+ })
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(f"api_{suffix}_a"))
+ _wait_stack(cfn, stack_name)
+ api_id = next(
+ o["OutputValue"]
+ for o in cfn.describe_stacks(StackName=stack_name)["Stacks"][0]["Outputs"]
+ if o["OutputKey"] == "ApiId")
+ assert appsync.get_data_source(
+ apiId=api_id, name="probe_source")["dataSource"]["name"] == "probe_source"
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=template(f"api_{suffix}_b"))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+
+ api = appsync.get_graphql_api(apiId=api_id)["graphqlApi"]
+ assert api["name"] == f"api_{suffix}_b"
+ # The data source is the evidence the children survived: the create
+ # re-seeded _data_sources for the new api id.
+ assert appsync.get_data_source(
+ apiId=api_id, name="probe_source")["dataSource"]["name"] == "probe_source"
+ assert len([a for a in appsync.list_graphql_apis()["graphqlApis"]
+ if a["name"].startswith(f"api_{suffix}")]) == 1
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_appsync_api_key_updates_in_place(cfn, appsync):
+ """Description and Expires are No interruption on AWS::AppSync::ApiKey.
+ The create mints a fresh key id, so under the fallback every expiry change
+ handed out a new key and left the previous one valid on the API."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-appsync-key-{suffix}"
+ expiry = (int(time.time()) + 7 * 86400) // 3600 * 3600
+
+ def template(description, expires):
+ return json.dumps({
+ "Resources": {
+ "Api": {
+ "Type": "AWS::AppSync::GraphQLApi",
+ "Properties": {"Name": f"keyapi_{suffix}",
+ "AuthenticationType": "API_KEY"},
+ },
+ "Key": {
+ "Type": "AWS::AppSync::ApiKey",
+ "Properties": {
+ "ApiId": {"Fn::GetAtt": ["Api", "ApiId"]},
+ "Description": description,
+ "Expires": expires,
+ },
+ },
+ },
+ "Outputs": {
+ "ApiId": {"Value": {"Fn::GetAtt": ["Api", "ApiId"]}},
+ "KeyId": {"Value": {"Fn::GetAtt": ["Key", "ApiKeyId"]}},
+ },
+ })
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("before", expiry))
+ _wait_stack(cfn, stack_name)
+ outputs = {o["OutputKey"]: o["OutputValue"] for o in
+ cfn.describe_stacks(StackName=stack_name)["Stacks"][0]["Outputs"]}
+ api_id, key_id = outputs["ApiId"], outputs["KeyId"]
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=template("after", expiry + 3600))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+
+ keys = appsync.list_api_keys(apiId=api_id)["apiKeys"]
+ assert len(keys) == 1, "the update left the previous key on the API"
+ assert keys[0]["id"] == key_id
+ assert keys[0]["description"] == "after"
+ assert keys[0]["expires"] == expiry + 3600
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def _cfn_appsync_api_template(name, providers=None, with_bad=False):
+ props = {"Name": name, "AuthenticationType": "API_KEY"}
+ if providers is not None:
+ props["AdditionalAuthenticationProviders"] = providers
+ resources = {"Api": {"Type": "AWS::AppSync::GraphQLApi", "Properties": props}}
+ if with_bad:
+ resources["Bad"] = {**_FAILING_RESOURCE, "DependsOn": "Api"}
+ return json.dumps({
+ "Resources": resources,
+ "Outputs": {"ApiId": {"Value": {"Fn::GetAtt": ["Api", "ApiId"]}}},
+ })
+
+
+def test_cfn_appsync_additional_auth_provider_added_by_update_reads_back(cfn, appsync):
+ """AdditionalAuthenticationProviders is No interruption. AppSync is a
+ rest-json API, so the stored list has to carry the API's camelCase: kept
+ in the template's PascalCase, botocore read back [{}] and the API's auth
+ check never saw AWS_IAM. Measured on AWS 2026-09-21: the added provider
+ reads back as [{"authenticationType": "AWS_IAM"}]."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-appsync-auth-upd-{suffix}"
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_appsync_api_template(f"auth_{suffix}"))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ api_id = _cfn_output(cfn, stack_name, "ApiId")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_appsync_api_template(
+ f"auth_{suffix}", [{"AuthenticationType": "AWS_IAM"}]))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ api = appsync.get_graphql_api(apiId=api_id)["graphqlApi"]
+ assert api["additionalAuthenticationProviders"] == [
+ {"authenticationType": "AWS_IAM"}]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_appsync_additional_auth_providers_at_create_read_back(cfn, appsync):
+ """The create stores the list in the API's shape too, nested configuration
+ members included."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-appsync-auth-new-{suffix}"
+ providers = [
+ {"AuthenticationType": "AWS_IAM"},
+ {"AuthenticationType": "OPENID_CONNECT",
+ "OpenIDConnectConfig": {"Issuer": "https://issuer.example.com",
+ "ClientId": "client-1", "IatTTL": 60}},
+ ]
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_appsync_api_template(
+ f"auth_{suffix}", providers))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ api = appsync.get_graphql_api(
+ apiId=_cfn_output(cfn, stack_name, "ApiId"))["graphqlApi"]
+ assert api["additionalAuthenticationProviders"] == [
+ {"authenticationType": "AWS_IAM"},
+ {"authenticationType": "OPENID_CONNECT",
+ "openIDConnectConfig": {"issuer": "https://issuer.example.com",
+ "clientId": "client-1", "iatTTL": 60}},
+ ]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_appsync_api_rename_is_rolled_back(cfn, appsync):
+ """A rename is applied in place, so a later failure in the same update has
+ to rename the API back. Measured on AWS 2026-09-21: the API reads its old
+ name after UPDATE_ROLLBACK_COMPLETE, under the same id."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-appsync-rb-{suffix}"
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_appsync_api_template(f"rb_{suffix}_a"))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ api_id = _cfn_output(cfn, stack_name, "ApiId")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_appsync_api_template(
+ f"rb_{suffix}_b", with_bad=True))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ assert _cfn_output(cfn, stack_name, "ApiId") == api_id
+ assert appsync.get_graphql_api(apiId=api_id)["graphqlApi"]["name"] == f"rb_{suffix}_a"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_appsync_additional_auth_provider_removed_reads_absent(cfn, appsync):
+ """A template that stops declaring AdditionalAuthenticationProviders
+ leaves the API without the member: AWS answers it absent, not as an empty
+ list (measured 2026-09-21, same api id)."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-appsync-auth-rm-{suffix}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_appsync_api_template(
+ f"auth_{suffix}", [{"AuthenticationType": "AWS_IAM"}]))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=_cfn_appsync_api_template(f"auth_{suffix}"))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ api = appsync.get_graphql_api(
+ apiId=_cfn_output(cfn, stack_name, "ApiId"))["graphqlApi"]
+ assert "additionalAuthenticationProviders" not in api
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_appsync_api_members_apply_change_and_reset(cfn, appsync):
+ """The GraphQLApi members a template sets reach the API at create, change
+ in place on update and go back to AppSync's defaults when removed, as
+ measured on AWS 2026-09-21. The provisioner stored only the name, the
+ authentication type and the extra providers, so XrayEnabled,
+ QueryDepthLimit, ResolverCountLimit, IntrospectionConfig,
+ EnvironmentVariables, OwnerContact and OpenIDConnectConfig were accepted
+ and never readable; a ClientId or Issuer change is in place too."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-appsync-members-{suffix}"
+ name = f"members_{suffix}"
+ oidc = {"Issuer": "https://issuer.example.com", "ClientId": "c1"}
+
+ def members(api_id):
+ api = appsync.get_graphql_api(apiId=api_id)["graphqlApi"]
+ return {key: api.get(key) for key in (
+ "xrayEnabled", "queryDepthLimit", "resolverCountLimit",
+ "introspectionConfig", "ownerContact", "visibility", "apiType")}
+
+ def env(api_id):
+ return appsync.get_graphql_api_environment_variables(
+ apiId=api_id)["environmentVariables"]
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_appsync_members_template(name, {
+ "XrayEnabled": True, "QueryDepthLimit": 5, "ResolverCountLimit": 10,
+ "IntrospectionConfig": "DISABLED", "EnvironmentVariables": {"K1": "v1"},
+ "OwnerContact": "owner-a"}, oidc))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ api_id = _cfn_output(cfn, stack_name, "ApiId")
+ oidc_id = _cfn_output(cfn, stack_name, "OidcId")
+ assert members(api_id) == {
+ "xrayEnabled": True, "queryDepthLimit": 5, "resolverCountLimit": 10,
+ "introspectionConfig": "DISABLED", "ownerContact": "owner-a",
+ "visibility": "GLOBAL", "apiType": "GRAPHQL"}
+ assert env(api_id) == {"K1": "v1"}
+ assert appsync.get_graphql_api(apiId=oidc_id)["graphqlApi"]["openIDConnectConfig"] == {
+ "issuer": "https://issuer.example.com", "clientId": "c1", "authTTL": 0, "iatTTL": 0}
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_appsync_members_template(name, {
+ "XrayEnabled": False, "QueryDepthLimit": 6, "ResolverCountLimit": 11,
+ "IntrospectionConfig": "ENABLED", "EnvironmentVariables": {"K1": "v2", "K2": "x"},
+ "OwnerContact": "owner-b"}, {**oidc, "ClientId": "c2"}))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ assert _cfn_output(cfn, stack_name, "ApiId") == api_id
+ assert _cfn_output(cfn, stack_name, "OidcId") == oidc_id
+ assert members(api_id) == {
+ "xrayEnabled": False, "queryDepthLimit": 6, "resolverCountLimit": 11,
+ "introspectionConfig": "ENABLED", "ownerContact": "owner-b",
+ "visibility": "GLOBAL", "apiType": "GRAPHQL"}
+ assert env(api_id) == {"K1": "v2", "K2": "x"}
+ assert appsync.get_graphql_api(
+ apiId=oidc_id)["graphqlApi"]["openIDConnectConfig"]["clientId"] == "c2"
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_appsync_members_template(
+ name, {}, {**oidc, "ClientId": "c2"}))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ assert members(api_id) == {
+ "xrayEnabled": False, "queryDepthLimit": 0, "resolverCountLimit": 0,
+ "introspectionConfig": "ENABLED", "ownerContact": None,
+ "visibility": "GLOBAL", "apiType": "GRAPHQL"}
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_appsync_api_visibility_change_fails_the_update(cfn, appsync):
+ """Visibility can only be set when the API is created. AWS fails the
+ update with the handler's message and rolls it back (measured 2026-09-21),
+ where the provisioner used to accept the change and keep GLOBAL."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-appsync-vis-{suffix}"
+ oidc = {"Issuer": "https://issuer.example.com", "ClientId": "c1"}
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_appsync_members_template(
+ f"vis_{suffix}", {}, oidc))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ api_id = _cfn_output(cfn, stack_name, "ApiId")
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_appsync_members_template(
+ f"vis_{suffix}", {"Visibility": "PRIVATE"}, oidc))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ reasons = [e.get("ResourceStatusReason", "")
+ for e in cfn.describe_stack_events(StackName=stack_name)["StackEvents"]
+ if e["LogicalResourceId"] == "Api" and e["ResourceStatus"] == "UPDATE_FAILED"]
+ assert reasons and "Property Visibility can only be set when creating a GraphQL API" in reasons[0]
+ assert _cfn_output(cfn, stack_name, "ApiId") == api_id
+ assert appsync.get_graphql_api(apiId=api_id)["graphqlApi"]["visibility"] == "GLOBAL"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_appsync_api_tags_take_the_stack_tags(cfn, appsync):
+ """A GraphQL API carries its template Tags and the stack-level tags, and a
+ stack-tag change reaches it; AppSync lists no aws:cloudformation:* tag on
+ it (measured on AWS 2026-09-21). The provisioner stored no tag at all,
+ and its eight-character api id made an ARN botocore refuses as too short
+ for ListTagsForResource."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-appsync-tags-{suffix}"
+ template = json.dumps({
+ "Resources": {"Api": {"Type": "AWS::AppSync::GraphQLApi", "Properties": {
+ "Name": f"tags_{suffix}", "AuthenticationType": "API_KEY",
+ "Tags": [{"Key": "own", "Value": "a"}]}}},
+ "Outputs": {"Arn": {"Value": {"Fn::GetAtt": ["Api", "Arn"]}}},
+ })
+ cfn.create_stack(StackName=stack_name, TemplateBody=template,
+ Tags=[{"Key": "stage", "Value": "one"}])
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ arn = _cfn_output(cfn, stack_name, "Arn")
+ assert appsync.list_tags_for_resource(resourceArn=arn)["tags"] == {
+ "own": "a", "stage": "one"}
+ cfn.update_stack(StackName=stack_name, UsePreviousTemplate=True,
+ Tags=[{"Key": "stage", "Value": "two"}])
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ assert appsync.list_tags_for_resource(resourceArn=arn)["tags"] == {
+ "own": "a", "stage": "two"}
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
diff --git a/tests/test_cfn_update_autoscaling.py b/tests/test_cfn_update_autoscaling.py
new file mode 100644
index 00000000..1393f609
--- /dev/null
+++ b/tests/test_cfn_update_autoscaling.py
@@ -0,0 +1,733 @@
+"""CloudFormation updates of Auto Scaling groups, scaling policies and scheduled actions."""
+
+import json
+import uuid as _uuid_mod
+
+from test_cfn import (
+ _FAILING_RESOURCE,
+ _cfn_output,
+ _cfn_with_failing_resource,
+ _delete_cfn_test_stack,
+ _wait_stack,
+)
+
+
+def test_cfn_asg_update_keeps_arn_and_created_time(cfn, autoscaling):
+ """MinSize, MaxSize and DesiredCapacity are No interruption on
+ AWS::AutoScaling::AutoScalingGroup. The create mints a fresh ARN, resets
+ CreatedTime and empties the Instances list, so the fallback handed every
+ consumer of the ARN a new value and dropped the group's instances."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-asg-{suffix}"
+ group = f"cfn-asg-{suffix}"
+
+ def template(max_size):
+ return json.dumps({
+ "Resources": {
+ "LC": {
+ "Type": "AWS::AutoScaling::LaunchConfiguration",
+ "Properties": {"ImageId": "ami-12345678",
+ "InstanceType": "t3.micro"},
+ },
+ "ASG": {
+ "Type": "AWS::AutoScaling::AutoScalingGroup",
+ "Properties": {
+ "AutoScalingGroupName": group,
+ "LaunchConfigurationName": {"Ref": "LC"},
+ "MinSize": "1",
+ "MaxSize": str(max_size),
+ "AvailabilityZones": ["us-east-1a"],
+ },
+ },
+ },
+ })
+
+ def described():
+ return autoscaling.describe_auto_scaling_groups(
+ AutoScalingGroupNames=[group])["AutoScalingGroups"][0]
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(3))
+ _wait_stack(cfn, stack_name)
+ before = described()
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(5))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+
+ after = described()
+ assert after["MaxSize"] == 5
+ assert after["AutoScalingGroupARN"] == before["AutoScalingGroupARN"], \
+ "the group came back under a new ARN"
+ assert after["CreatedTime"] == before["CreatedTime"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_asg_scaling_policy_update_keeps_arn(cfn, autoscaling):
+ """Cooldown and ScalingAdjustment are No interruption on
+ AWS::AutoScaling::ScalingPolicy, and Ref answers the policy ARN, which the
+ create re-minted on every change."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-asg-pol-{suffix}"
+ group = f"cfn-asg-pol-{suffix}"
+
+ def template(cooldown):
+ return json.dumps({
+ "Resources": {
+ "LC": {
+ "Type": "AWS::AutoScaling::LaunchConfiguration",
+ "Properties": {"ImageId": "ami-12345678",
+ "InstanceType": "t3.micro"},
+ },
+ "ASG": {
+ "Type": "AWS::AutoScaling::AutoScalingGroup",
+ "Properties": {
+ "AutoScalingGroupName": group,
+ "LaunchConfigurationName": {"Ref": "LC"},
+ "MinSize": "1", "MaxSize": "3",
+ "AvailabilityZones": ["us-east-1a"],
+ },
+ },
+ "Policy": {
+ "Type": "AWS::AutoScaling::ScalingPolicy",
+ "Properties": {
+ # No PolicyName, so the name is generated.
+ "AutoScalingGroupName": {"Ref": "ASG"},
+ "AdjustmentType": "ChangeInCapacity",
+ "ScalingAdjustment": 1,
+ "Cooldown": str(cooldown),
+ },
+ },
+ },
+ "Outputs": {"PolicyArn": {"Value": {"Ref": "Policy"}}},
+ })
+
+ def policy_arn():
+ return next(
+ o["OutputValue"]
+ for o in cfn.describe_stacks(StackName=stack_name)["Stacks"][0]["Outputs"]
+ if o["OutputKey"] == "PolicyArn")
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(300))
+ _wait_stack(cfn, stack_name)
+ before = policy_arn()
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(600))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+
+ policies = autoscaling.describe_policies(
+ AutoScalingGroupName=group)["ScalingPolicies"]
+ assert len(policies) == 1
+ assert policies[0]["Cooldown"] == 600
+ assert policies[0]["PolicyARN"] == before, \
+ "the policy came back under a new ARN"
+ assert policies[0]["PolicyName"].startswith(f"{stack_name}-Policy-")
+ assert policy_arn() == before
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_asg_scheduled_action_update_keeps_arn(cfn, autoscaling):
+ """MinSize, MaxSize, DesiredCapacity and Recurrence are No interruption on
+ AWS::AutoScaling::ScheduledAction; the create re-minted the ARN Ref
+ answers."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-asg-sched-{suffix}"
+ group = f"cfn-asg-sched-{suffix}"
+
+ def template(max_size):
+ return json.dumps({
+ "Resources": {
+ "LC": {
+ "Type": "AWS::AutoScaling::LaunchConfiguration",
+ "Properties": {"ImageId": "ami-12345678",
+ "InstanceType": "t3.micro"},
+ },
+ "ASG": {
+ "Type": "AWS::AutoScaling::AutoScalingGroup",
+ "Properties": {
+ "AutoScalingGroupName": group,
+ "LaunchConfigurationName": {"Ref": "LC"},
+ "MinSize": "1", "MaxSize": "9",
+ "AvailabilityZones": ["us-east-1a"],
+ },
+ },
+ "Sched": {
+ "Type": "AWS::AutoScaling::ScheduledAction",
+ "Properties": {
+ "AutoScalingGroupName": {"Ref": "ASG"},
+ "Recurrence": "0 9 * * *",
+ "MinSize": 1,
+ "MaxSize": max_size,
+ },
+ },
+ },
+ "Outputs": {"Sched": {"Value": {"Ref": "Sched"}}},
+ })
+
+ def action():
+ actions = autoscaling.describe_scheduled_actions(
+ AutoScalingGroupName=group)["ScheduledUpdateGroupActions"]
+ assert len(actions) == 1
+ return actions[0]
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(4))
+ _wait_stack(cfn, stack_name)
+ before = action()["ScheduledActionARN"]
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(6))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+
+ after = action()
+ assert after["MaxSize"] == 6
+ assert after["ScheduledActionARN"] == before, \
+ "the scheduled action came back under a new ARN"
+ assert _cfn_output(cfn, stack_name, "Sched") == after["ScheduledActionName"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def _cfn_asg_policy_template(group, policies):
+ return json.dumps({
+ "Resources": {
+ "LC": {"Type": "AWS::AutoScaling::LaunchConfiguration",
+ "Properties": {"ImageId": "ami-12345678", "InstanceType": "t3.micro"}},
+ "ASG": {"Type": "AWS::AutoScaling::AutoScalingGroup", "Properties": {
+ "AutoScalingGroupName": group, "LaunchConfigurationName": {"Ref": "LC"},
+ "MinSize": "0", "MaxSize": "1", "DesiredCapacity": "0",
+ "AvailabilityZones": ["us-east-1a"]}},
+ **{name: {"Type": "AWS::AutoScaling::ScalingPolicy",
+ "Properties": {"AutoScalingGroupName": {"Ref": "ASG"}, **props}}
+ for name, props in policies.items()},
+ },
+ "Outputs": {name: {"Value": {"Ref": name}} for name in policies},
+ })
+
+
+def _cfn_asg_policies_by_arn(autoscaling, group):
+ return {p["PolicyARN"]: p for p in autoscaling.describe_policies(
+ AutoScalingGroupName=group)["ScalingPolicies"]}
+
+
+def test_cfn_asg_target_tracking_policy_reads_back_and_updates_in_place(cfn, autoscaling):
+ """TargetTrackingConfiguration is No interruption on
+ AWS::AutoScaling::ScalingPolicy, and it was dropped by the create, the
+ update and DescribePolicies alike, so the policy read back without the
+ one member it is for. The shape is AWS's (measured 2026-09-21):
+ TargetValue a double, DisableScaleIn false when unset, and no
+ AdjustmentType, ScalingAdjustment or Cooldown on a target-tracking
+ policy; round 51 measured TargetValue 40.0 -> 60.0 under an unchanged
+ ARN."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-asg-tt-{suffix}"
+ group = f"cfn-asg-tt-{suffix}"
+
+ def template(target):
+ return _cfn_asg_policy_template(group, {"Tt": {
+ "PolicyType": "TargetTrackingScaling",
+ "EstimatedInstanceWarmup": 120,
+ "TargetTrackingConfiguration": {
+ "PredefinedMetricSpecification": {
+ "PredefinedMetricType": "ASGAverageCPUUtilization"},
+ "TargetValue": target}}})
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(40))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ arn = _cfn_output(cfn, stack_name, "Tt")
+ policy = _cfn_asg_policies_by_arn(autoscaling, group)[arn]
+ assert policy["PolicyName"].startswith(f"{stack_name}-Tt-")
+ assert policy["TargetTrackingConfiguration"] == {
+ "PredefinedMetricSpecification": {
+ "PredefinedMetricType": "ASGAverageCPUUtilization"},
+ "TargetValue": 40.0,
+ "DisableScaleIn": False,
+ }
+ assert policy["EstimatedInstanceWarmup"] == 120
+ assert policy["Enabled"] is True
+ assert not {"AdjustmentType", "ScalingAdjustment", "Cooldown"} & set(policy)
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(60))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _cfn_output(cfn, stack_name, "Tt") == arn
+ policy = _cfn_asg_policies_by_arn(autoscaling, group)[arn]
+ assert policy["TargetTrackingConfiguration"]["TargetValue"] == 60.0
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_asg_scaling_policy_keeps_a_template_policy_name(cfn, autoscaling):
+ """The registry lists PolicyName as read-only on
+ AWS::AutoScaling::ScalingPolicy, but AWS applies one the template sets
+ (measured 2026-09-21: the policy carries exactly that name), so the
+ provisioner keeps honouring it. A guard, not a fix: main honours it too."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-asg-pname-{suffix}"
+ group = f"cfn-asg-pname-{suffix}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_asg_policy_template(group, {"Named": {
+ "PolicyName": f"named-{suffix}", "AdjustmentType": "ChangeInCapacity",
+ "ScalingAdjustment": 1}}))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ policies = autoscaling.describe_policies(AutoScalingGroupName=group)["ScalingPolicies"]
+ assert [p["PolicyName"] for p in policies] == [f"named-{suffix}"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_asg_scaling_policy_name_change_is_not_applied(cfn, autoscaling):
+ """PolicyName is honoured when the policy is created and never after:
+ AWS keeps the policy's name and ARN when the template changes the name or
+ drops it (measured 2026-09-21, UPDATE_COMPLETE both times). The handler
+ keyed a replacement on it, so the policy came back renamed under a new
+ ARN."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-asg-pren-{suffix}"
+ group = f"cfn-asg-pren-{suffix}"
+
+ def template(name):
+ props = {"AdjustmentType": "ChangeInCapacity", "ScalingAdjustment": 1}
+ if name:
+ props["PolicyName"] = name
+ return _cfn_asg_policy_template(group, {"Policy": props})
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(f"pa-{suffix}"))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ arn = _cfn_output(cfn, stack_name, "Policy")
+ for name in (f"pb-{suffix}", None):
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(name))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _cfn_output(cfn, stack_name, "Policy") == arn
+ policies = autoscaling.describe_policies(AutoScalingGroupName=group)["ScalingPolicies"]
+ assert [(p["PolicyName"], p["PolicyARN"]) for p in policies] == [(f"pa-{suffix}", arn)]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def _cfn_asg_scheduled_template(group, props):
+ return json.dumps({
+ "Resources": {
+ "LC": {"Type": "AWS::AutoScaling::LaunchConfiguration",
+ "Properties": {"ImageId": "ami-12345678", "InstanceType": "t3.micro"}},
+ "ASG": {"Type": "AWS::AutoScaling::AutoScalingGroup", "Properties": {
+ "AutoScalingGroupName": group, "LaunchConfigurationName": {"Ref": "LC"},
+ "MinSize": "0", "MaxSize": "1", "DesiredCapacity": "0",
+ "AvailabilityZones": ["us-east-1a"]}},
+ "Sched": {"Type": "AWS::AutoScaling::ScheduledAction", "Properties": {
+ "AutoScalingGroupName": {"Ref": "ASG"}, "MinSize": 0, "MaxSize": 1,
+ "DesiredCapacity": 0, "Recurrence": "0 9 * * *", **props}},
+ },
+ "Outputs": {"Sched": {"Value": {"Ref": "Sched"}},
+ "Name": {"Value": {"Fn::GetAtt": ["Sched", "ScheduledActionName"]}}},
+ })
+
+
+def test_cfn_asg_scheduled_action_is_named_by_cloudformation(cfn, autoscaling):
+ """CloudFormation names a scheduled action itself and Ref answers that
+ name: the registry lists ScheduledActionName as read-only, and AWS ignores
+ one the template sets, at create and on every update, with the ARN and
+ name unchanged (measured 2026-09-21). The provisioner used the template's
+ name, answered the ARN through Ref and replaced the action when the name
+ changed."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-asg-sname-{suffix}"
+ group = f"cfn-asg-sname-{suffix}"
+
+ def action():
+ actions = autoscaling.describe_scheduled_actions(
+ AutoScalingGroupName=group)["ScheduledUpdateGroupActions"]
+ assert len(actions) == 1
+ return actions[0]
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_asg_scheduled_template(
+ group, {"ScheduledActionName": f"sa-{suffix}"}))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ created = action()
+ assert created["ScheduledActionName"].startswith(f"{stack_name}-Sched-")
+ assert _cfn_output(cfn, stack_name, "Sched") == created["ScheduledActionName"]
+ assert _cfn_output(cfn, stack_name, "Name") == created["ScheduledActionName"]
+ for props in ({"ScheduledActionName": f"sb-{suffix}"}, {}):
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=_cfn_asg_scheduled_template(group, props))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert action() == created
+ assert _cfn_output(cfn, stack_name, "Sched") == created["ScheduledActionName"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ assert autoscaling.describe_scheduled_actions(
+ AutoScalingGroupName=group)["ScheduledUpdateGroupActions"] == []
+
+
+def test_cfn_asg_scheduled_action_times_read_back_and_update(cfn, autoscaling):
+ """StartTime, EndTime and TimeZone are No interruption on
+ AWS::AutoScaling::ScheduledAction. AWS answers all three (StartTime also
+ as Time), applies each change in place and drops EndTime when the
+ template removes it (measured 2026-09-21); the provisioner and
+ PutScheduledUpdateGroupAction stored none of them."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-asg-stimes-{suffix}"
+ group = f"cfn-asg-stimes-{suffix}"
+
+ def times():
+ action = autoscaling.describe_scheduled_actions(
+ AutoScalingGroupName=group)["ScheduledUpdateGroupActions"][0]
+ return {key: (value.isoformat() if hasattr(value, "isoformat") else value)
+ for key, value in action.items()
+ if key in ("StartTime", "Time", "EndTime", "TimeZone", "ScheduledActionARN")}
+
+ start = {"StartTime": "2027-01-04T09:00:00Z"}
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_asg_scheduled_template(group, {
+ **start, "EndTime": "2027-06-01T00:00:00Z", "TimeZone": "Europe/Berlin"}))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ before = times()
+ arn = before.pop("ScheduledActionARN")
+ assert before == {"StartTime": "2027-01-04T09:00:00+00:00",
+ "Time": "2027-01-04T09:00:00+00:00",
+ "EndTime": "2027-06-01T00:00:00+00:00",
+ "TimeZone": "Europe/Berlin"}
+ steps = [
+ ({**start, "EndTime": "2027-07-01T00:00:00Z", "TimeZone": "Europe/Berlin"},
+ {"EndTime": "2027-07-01T00:00:00+00:00"}),
+ ({**start, "EndTime": "2027-07-01T00:00:00Z", "TimeZone": "Etc/UTC"},
+ {"TimeZone": "Etc/UTC"}),
+ ({"StartTime": "2027-02-01T09:00:00Z", "EndTime": "2027-07-01T00:00:00Z",
+ "TimeZone": "Etc/UTC"},
+ {"StartTime": "2027-02-01T09:00:00+00:00", "Time": "2027-02-01T09:00:00+00:00"}),
+ ({"StartTime": "2027-02-01T09:00:00Z", "TimeZone": "Etc/UTC"}, {"EndTime": None}),
+ ]
+ for props, change in steps:
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=_cfn_asg_scheduled_template(group, props))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ before.update(change)
+ after = times()
+ assert after.pop("ScheduledActionARN") == arn
+ assert after == {k: v for k, v in before.items() if v is not None}
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_asg_predictive_scaling_policy_reads_back_and_updates_in_place(cfn, autoscaling):
+ """PredictiveScalingConfiguration is No interruption. AWS answers it with
+ MaxCapacityBreachBehavior defaulted to HonorMaxCapacity and TargetValue as
+ a double, and a TargetValue change keeps the ARN (measured 2026-09-21);
+ the configuration was dropped by the provisioner, PutScalingPolicy and
+ DescribePolicies alike."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-asg-pred-{suffix}"
+ group = f"cfn-asg-pred-{suffix}"
+
+ def template(target):
+ return _cfn_asg_policy_template(group, {"Pred": {
+ "PolicyType": "PredictiveScaling",
+ "PredictiveScalingConfiguration": {
+ "Mode": "ForecastOnly",
+ "MetricSpecifications": [{
+ "TargetValue": target,
+ "PredefinedMetricPairSpecification": {
+ "PredefinedMetricType": "ASGCPUUtilization"}}]}}})
+
+ def config(target):
+ return {"Mode": "ForecastOnly", "MaxCapacityBreachBehavior": "HonorMaxCapacity",
+ "MetricSpecifications": [{
+ "TargetValue": target,
+ "PredefinedMetricPairSpecification": {
+ "PredefinedMetricType": "ASGCPUUtilization"}}]}
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(40))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ arn = _cfn_output(cfn, stack_name, "Pred")
+ policy = _cfn_asg_policies_by_arn(autoscaling, group)[arn]
+ assert policy["PredictiveScalingConfiguration"] == config(40.0)
+ assert not {"AdjustmentType", "ScalingAdjustment", "Cooldown"} & set(policy)
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(50))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ assert _cfn_output(cfn, stack_name, "Pred") == arn
+ policy = _cfn_asg_policies_by_arn(autoscaling, group)[arn]
+ assert policy["PredictiveScalingConfiguration"] == config(50.0)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_asg_launch_template_reads_back_its_name_and_id(cfn, autoscaling):
+ """DescribeAutoScalingGroups answers the launch template's id and name
+ whichever of the two the group was given. A template references its
+ launch template through Ref, the id, and the provisioner copied only that:
+ LaunchTemplateName read "" where AWS answers the real name (measured
+ 2026-09-21)."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-asg-ltname-{suffix}"
+ lt_name = f"cfn-asg-ltname-{suffix}"
+
+ def group(logical_id, reference):
+ return {"Type": "AWS::AutoScaling::AutoScalingGroup", "Properties": {
+ "AutoScalingGroupName": f"{lt_name}-{logical_id.lower()}",
+ "LaunchTemplate": {**reference, "Version": {"Fn::GetAtt": ["LT", "LatestVersionNumber"]}},
+ "MinSize": "0", "MaxSize": "1", "DesiredCapacity": "0",
+ "AvailabilityZones": ["us-east-1a"]}}
+
+ template = json.dumps({"Resources": {
+ "LT": {"Type": "AWS::EC2::LaunchTemplate", "Properties": {
+ "LaunchTemplateName": lt_name,
+ "LaunchTemplateData": {"ImageId": "ami-12345678", "InstanceType": "t3.micro"}}},
+ "ById": group("ById", {"LaunchTemplateId": {"Ref": "LT"}}),
+ "ByName": group("ByName", {"LaunchTemplateName": lt_name}),
+ }, "Outputs": {"Lt": {"Value": {"Ref": "LT"}}}})
+ cfn.create_stack(StackName=stack_name, TemplateBody=template)
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ lt_id = _cfn_output(cfn, stack_name, "Lt")
+ groups = autoscaling.describe_auto_scaling_groups(AutoScalingGroupNames=[
+ f"{lt_name}-byid", f"{lt_name}-byname"])["AutoScalingGroups"]
+ assert [g["LaunchTemplate"] for g in groups] == [
+ {"LaunchTemplateId": lt_id, "LaunchTemplateName": lt_name, "Version": "1"}] * 2
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_asg_instance_id_change_replaces_the_group(cfn, autoscaling):
+ """InstanceId is create-only on AWS::AutoScaling::AutoScalingGroup (the
+ registry's createOnlyProperties), so a change replaces the group: a new
+ ARN under the generated name. The handler applied every other change in
+ place and ignored this one."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-asg-inst-{suffix}"
+
+ def template(instance_id):
+ return json.dumps({"Resources": {"ASG": {
+ "Type": "AWS::AutoScaling::AutoScalingGroup", "Properties": {
+ "InstanceId": instance_id, "MinSize": "0", "MaxSize": "1",
+ "DesiredCapacity": "0", "AvailabilityZones": ["us-east-1a"]}}},
+ "Outputs": {"Name": {"Value": {"Ref": "ASG"}}}})
+
+ def arn():
+ # The stack's Ref, read each time: the replacement is the group the
+ # stack names now, whatever name it was given.
+ name = _cfn_output(cfn, stack_name, "Name")
+ groups = autoscaling.describe_auto_scaling_groups(
+ AutoScalingGroupNames=[name])["AutoScalingGroups"]
+ assert len(groups) == 1, f"no group under the stack's Ref {name}"
+ return groups[0]["AutoScalingGroupARN"]
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("i-0123456789abcdef0"))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ before = arn()
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("i-0fedcba9876543210"))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ assert arn() != before
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_asg_step_and_customized_metric_policies_read_back(cfn, autoscaling):
+ """A step policy's StepAdjustments, MetricAggregationType,
+ MinAdjustmentMagnitude and EstimatedInstanceWarmup, and a customized
+ metric's Dimensions list, read back in the shape AWS answers (measured
+ 2026-09-21 on the same two policies): the bounds as doubles, an open
+ upper bound left out, and no ScalingAdjustment or Cooldown on a step
+ policy."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-asg-step-{suffix}"
+ group = f"cfn-asg-step-{suffix}"
+ body = _cfn_asg_policy_template(group, {
+ "Step": {
+ "PolicyType": "StepScaling",
+ "AdjustmentType": "PercentChangeInCapacity",
+ "MinAdjustmentMagnitude": 1,
+ "MetricAggregationType": "Average",
+ "EstimatedInstanceWarmup": 60,
+ "StepAdjustments": [
+ {"MetricIntervalLowerBound": 0, "MetricIntervalUpperBound": 10,
+ "ScalingAdjustment": 10},
+ {"MetricIntervalLowerBound": 10, "ScalingAdjustment": 20},
+ ]},
+ "Tc": {
+ "PolicyType": "TargetTrackingScaling",
+ "TargetTrackingConfiguration": {
+ "CustomizedMetricSpecification": {
+ "MetricName": "CPUUtilization", "Namespace": "AWS/EC2",
+ "Dimensions": [{"Name": "AutoScalingGroupName", "Value": group}],
+ "Statistic": "Average", "Unit": "Percent"},
+ "TargetValue": 50.5,
+ "DisableScaleIn": True}},
+ })
+ cfn.create_stack(StackName=stack_name, TemplateBody=body)
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ policies = _cfn_asg_policies_by_arn(autoscaling, group)
+ step = policies[_cfn_output(cfn, stack_name, "Step")]
+ assert step["AdjustmentType"] == "PercentChangeInCapacity"
+ assert step["MinAdjustmentMagnitude"] == 1
+ assert step["MetricAggregationType"] == "Average"
+ assert step["EstimatedInstanceWarmup"] == 60
+ assert step["StepAdjustments"] == [
+ {"MetricIntervalLowerBound": 0.0, "MetricIntervalUpperBound": 10.0,
+ "ScalingAdjustment": 10},
+ {"MetricIntervalLowerBound": 10.0, "ScalingAdjustment": 20},
+ ]
+ assert not {"ScalingAdjustment", "Cooldown"} & set(step)
+ tracking = policies[_cfn_output(cfn, stack_name, "Tc")]["TargetTrackingConfiguration"]
+ assert tracking == {
+ "CustomizedMetricSpecification": {
+ "MetricName": "CPUUtilization", "Namespace": "AWS/EC2",
+ "Dimensions": [{"Name": "AutoScalingGroupName", "Value": group}],
+ "Statistic": "Average", "Unit": "Percent"},
+ "TargetValue": 50.5,
+ "DisableScaleIn": True,
+ }
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def _cfn_asg_group_template(group, max_size="3", tags=None, with_bad=False):
+ props = {"AutoScalingGroupName": group, "LaunchConfigurationName": {"Ref": "LC"},
+ "MinSize": "0", "MaxSize": max_size, "DesiredCapacity": "0",
+ "AvailabilityZones": ["us-east-1a"]}
+ if tags is not None:
+ props["Tags"] = tags
+ resources = {
+ "LC": {"Type": "AWS::AutoScaling::LaunchConfiguration",
+ "Properties": {"ImageId": "ami-12345678", "InstanceType": "t3.micro"}},
+ "ASG": {"Type": "AWS::AutoScaling::AutoScalingGroup", "Properties": props},
+ }
+ if with_bad:
+ resources["Bad"] = {**_FAILING_RESOURCE, "DependsOn": "ASG"}
+ return json.dumps({"Resources": resources})
+
+
+def test_cfn_asg_tag_change_keeps_tags_added_through_the_api(cfn, autoscaling):
+ """Tags is No interruption on AWS::AutoScaling::AutoScalingGroup, and a
+ template tag change on AWS leaves a tag added through CreateOrUpdateTags
+ alone while the template's tags take their new values and
+ PropagateAtLaunch (measured 2026-09-21). The update overwrote the whole
+ tag list."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-asg-tags-{suffix}"
+ group = f"cfn-asg-tags-{suffix}"
+
+ def own_tags():
+ described = autoscaling.describe_auto_scaling_groups(
+ AutoScalingGroupNames=[group])["AutoScalingGroups"][0]
+ return sorted((t["Key"], t["Value"], t["PropagateAtLaunch"])
+ for t in described["Tags"] if not t["Key"].startswith("aws:"))
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_asg_group_template(
+ group, tags=[{"Key": "a", "Value": "1", "PropagateAtLaunch": False}]))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ autoscaling.create_or_update_tags(Tags=[{
+ "ResourceId": group, "ResourceType": "auto-scaling-group",
+ "Key": "api", "Value": "kept", "PropagateAtLaunch": False}])
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_asg_group_template(
+ group, tags=[{"Key": "a", "Value": "2", "PropagateAtLaunch": False},
+ {"Key": "b", "Value": "3", "PropagateAtLaunch": True}]))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert own_tags() == [("a", "2", False), ("api", "kept", False), ("b", "3", True)]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_asg_max_size_change_is_rolled_back(cfn, autoscaling):
+ """MaxSize is applied in place, so a later failure in the same update has
+ to set it back. Measured on AWS 2026-09-21: MaxSize reads 1 again after
+ UPDATE_ROLLBACK_COMPLETE, under the same group ARN."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-asg-rb-{suffix}"
+ group = f"cfn-asg-rb-{suffix}"
+
+ def described():
+ return autoscaling.describe_auto_scaling_groups(
+ AutoScalingGroupNames=[group])["AutoScalingGroups"][0]
+
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_asg_group_template(group, max_size="1"))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ arn = described()["AutoScalingGroupARN"]
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_asg_group_template(
+ group, max_size="2", with_bad=True))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ assert described()["MaxSize"] == 1
+ assert described()["AutoScalingGroupARN"] == arn
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_asg_policy_target_value_change_is_rolled_back(cfn, autoscaling):
+ """A TargetValue change is applied in place, so a later failure in the
+ same update has to set it back. Measured on AWS 2026-09-21: TargetValue
+ reads 40.0 again after UPDATE_ROLLBACK_COMPLETE, one policy under the same
+ ARN."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-asg-pol-rb-{suffix}"
+ group = f"cfn-asg-pol-rb-{suffix}"
+
+ def template(target):
+ return _cfn_asg_policy_template(group, {"Tt": {
+ "PolicyType": "TargetTrackingScaling",
+ "TargetTrackingConfiguration": {
+ "PredefinedMetricSpecification": {
+ "PredefinedMetricType": "ASGAverageCPUUtilization"},
+ "TargetValue": target}}})
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(40))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ arn = _cfn_output(cfn, stack_name, "Tt")
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=_cfn_with_failing_resource(template(60), "Tt"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ policies = _cfn_asg_policies_by_arn(autoscaling, group)
+ assert list(policies) == [arn]
+ assert policies[arn]["TargetTrackingConfiguration"]["TargetValue"] == 40.0
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_asg_scheduled_action_recurrence_change_is_rolled_back(cfn, autoscaling):
+ """A Recurrence change is applied in place, so a later failure in the same
+ update has to set it back. Measured on AWS 2026-09-21: the action reads
+ "0 9 * * *" again after UPDATE_ROLLBACK_COMPLETE, one action under the
+ same ARN."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-asg-sched-rb-{suffix}"
+ group = f"cfn-asg-sched-rb-{suffix}"
+
+ def actions():
+ return autoscaling.describe_scheduled_actions(
+ AutoScalingGroupName=group)["ScheduledUpdateGroupActions"]
+
+ try:
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_asg_scheduled_template(group, {}))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ [before] = actions()
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_with_failing_resource(
+ _cfn_asg_scheduled_template(group, {"Recurrence": "0 10 * * *"}), "Sched"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ [after] = actions()
+ assert after["Recurrence"] == "0 9 * * *"
+ assert after["ScheduledActionARN"] == before["ScheduledActionARN"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
diff --git a/tests/test_cfn_update_ec2.py b/tests/test_cfn_update_ec2.py
new file mode 100644
index 00000000..5a29e712
--- /dev/null
+++ b/tests/test_cfn_update_ec2.py
@@ -0,0 +1,1228 @@
+"""CloudFormation updates of EC2 networking: VPCs, subnets, security groups, launch templates, gateways, routes."""
+
+import json
+import uuid as _uuid_mod
+
+from botocore.exceptions import ClientError
+from test_cfn import (
+ _FAILING_RESOURCE,
+ _cfn_output,
+ _cfn_with_failing_resource,
+ _delete_cfn_test_stack,
+ _output,
+ _template_tags,
+ _wait_stack,
+)
+
+
+def test_cfn_ec2_vpc_update_keeps_id_and_leaves_no_default_children(cfn, ec2):
+ """EnableDnsHostnames is No interruption on AWS::EC2::VPC, so the VPC keeps
+ its id. The create mints a new one and also writes a default security
+ group, main route table and network ACL, none of which the CFN delete
+ removes, so every update leaked all three."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-vpc-upd-{suffix}"
+
+ def template(dns):
+ return json.dumps({
+ "Resources": {
+ "Vpc": {
+ "Type": "AWS::EC2::VPC",
+ "Properties": {
+ "CidrBlock": "10.42.0.0/16",
+ "EnableDnsHostnames": dns,
+ "Tags": [{"Key": "probe", "Value": str(dns)}],
+ },
+ },
+ },
+ "Outputs": {"VpcId": {"Value": {"Ref": "Vpc"}}},
+ })
+
+ def vpc_id():
+ return next(o["OutputValue"] for o in
+ cfn.describe_stacks(StackName=stack_name)["Stacks"][0]["Outputs"]
+ if o["OutputKey"] == "VpcId")
+
+ def children_of(vid):
+ sgs = [g for g in ec2.describe_security_groups()["SecurityGroups"]
+ if g.get("VpcId") == vid]
+ rtbs = [r for r in ec2.describe_route_tables()["RouteTables"]
+ if r.get("VpcId") == vid]
+ acls = [a for a in ec2.describe_network_acls()["NetworkAcls"]
+ if a.get("VpcId") == vid]
+ return sgs, rtbs, acls
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(False))
+ _wait_stack(cfn, stack_name)
+ before = vpc_id()
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(True))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+
+ assert vpc_id() == before, "the VPC came back under a new id"
+ sgs, rtbs, acls = children_of(before)
+ assert len(sgs) == 1 and len(rtbs) == 1 and len(acls) == 1, (
+ "the update left a second set of default children behind: "
+ f"{len(sgs)} security groups, {len(rtbs)} route tables, {len(acls)} ACLs")
+ assert ec2.describe_vpc_attribute(
+ VpcId=before, Attribute="enableDnsHostnames"
+ )["EnableDnsHostnames"]["Value"] is True
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def _cfn_vpc_children(ec2, vpc_id):
+ return (
+ [g["GroupId"] for g in ec2.describe_security_groups()["SecurityGroups"]
+ if g.get("VpcId") == vpc_id],
+ [r["RouteTableId"] for r in ec2.describe_route_tables()["RouteTables"]
+ if r.get("VpcId") == vpc_id],
+ [a["NetworkAclId"] for a in ec2.describe_network_acls()["NetworkAcls"]
+ if a.get("VpcId") == vpc_id],
+ )
+
+
+def test_cfn_ec2_vpc_stack_delete_removes_its_default_children(cfn, ec2):
+ """DeleteVpc removes the default security group, main route table and
+ default network ACL with the VPC, so a stack delete leaves none of the
+ three behind. The CFN delete popped only the VPC, which left all three
+ pointing at a VPC id that no longer existed."""
+ stack_name = f"cfn-vpc-del-{_uuid_mod.uuid4().hex[:8]}"
+ template = json.dumps({
+ "Resources": {"Vpc": {"Type": "AWS::EC2::VPC",
+ "Properties": {"CidrBlock": "10.47.0.0/16"}}},
+ "Outputs": {"VpcId": {"Value": {"Ref": "Vpc"}}},
+ })
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template)
+ vpc_id = _output(_wait_stack(cfn, stack_name), "VpcId")
+ sgs, rtbs, acls = _cfn_vpc_children(ec2, vpc_id)
+ assert len(sgs) == 1 and len(rtbs) == 1 and len(acls) == 1
+
+ cfn.delete_stack(StackName=stack_name)
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"
+
+ assert _cfn_vpc_children(ec2, vpc_id) == ([], [], []), (
+ "the stack delete left the VPC's default children behind")
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_vpc_stack_delete_keeps_a_security_group_made_outside_it(cfn, ec2):
+ """AWS refuses DeleteVpc with DependencyViolation while a non-default
+ security group lives in the VPC, so a stack whose VPC holds a group made
+ outside the stack ends DELETE_FAILED and the group survives. The CFN
+ delete popped every security group with the VPC's id, the foreign one
+ included."""
+ stack_name = f"cfn-vpc-dep-{_uuid_mod.uuid4().hex[:8]}"
+ template = json.dumps({
+ "Resources": {"Vpc": {"Type": "AWS::EC2::VPC",
+ "Properties": {"CidrBlock": "10.48.0.0/16"}}},
+ "Outputs": {"VpcId": {"Value": {"Ref": "Vpc"}}},
+ })
+ group_id = None
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template)
+ vpc_id = _output(_wait_stack(cfn, stack_name), "VpcId")
+ group_id = ec2.create_security_group(
+ GroupName=f"foreign-{stack_name}", Description="outside the stack",
+ VpcId=vpc_id,
+ )["GroupId"]
+
+ cfn.delete_stack(StackName=stack_name)
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_FAILED"
+
+ groups = ec2.describe_security_groups(GroupIds=[group_id])["SecurityGroups"]
+ assert [g["GroupId"] for g in groups] == [group_id]
+ assert ec2.describe_vpcs(VpcIds=[vpc_id])["Vpcs"]
+ finally:
+ if group_id:
+ try:
+ ec2.delete_security_group(GroupId=group_id)
+ except ClientError:
+ pass
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def _cfn_vpc_attribute(ec2, vpc_id, attribute):
+ key = attribute[0].upper() + attribute[1:]
+ return ec2.describe_vpc_attribute(VpcId=vpc_id, Attribute=attribute)[key]["Value"]
+
+
+def test_cfn_ec2_vpc_dns_property_removed_returns_to_its_default(cfn, ec2):
+ """A DNS property the template stops setting goes back to the VPC's
+ default, which is what AWS does (measured 2026-09-21): a removed
+ EnableDnsHostnames reads false, a removed EnableDnsSupport true. The
+ update only wrote a property that was present, so a removed one kept the
+ value the template had set."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-vpc-dns-{suffix}"
+
+ def template(both, off):
+ return json.dumps({
+ "Resources": {
+ "Both": {"Type": "AWS::EC2::VPC", "Properties": {
+ "CidrBlock": "10.45.0.0/16", **both}},
+ "Off": {"Type": "AWS::EC2::VPC", "Properties": {
+ "CidrBlock": "10.46.0.0/16", **off}},
+ },
+ "Outputs": {"Both": {"Value": {"Ref": "Both"}}, "Off": {"Value": {"Ref": "Off"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(
+ {"EnableDnsSupport": True, "EnableDnsHostnames": True}, {"EnableDnsSupport": False}))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ both, off = _cfn_output(cfn, stack_name, "Both"), _cfn_output(cfn, stack_name, "Off")
+ assert _cfn_vpc_attribute(ec2, both, "enableDnsHostnames") is True
+ assert _cfn_vpc_attribute(ec2, off, "enableDnsSupport") is False
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(
+ {"EnableDnsSupport": True}, {}))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _cfn_output(cfn, stack_name, "Both") == both
+ assert _cfn_output(cfn, stack_name, "Off") == off
+ assert _cfn_vpc_attribute(ec2, both, "enableDnsHostnames") is False
+ assert _cfn_vpc_attribute(ec2, both, "enableDnsSupport") is True
+ assert _cfn_vpc_attribute(ec2, off, "enableDnsSupport") is True
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_vpc_tag_change_keeps_tags_added_through_the_api(cfn, ec2):
+ """Tags is No interruption on AWS::EC2::VPC, and on AWS a template tag
+ change leaves a tag added through CreateTags alone (measured 2026-09-21:
+ a=1 -> a=2 plus b=3, api=kept stays). The update overwrote the whole tag
+ list."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-vpc-tags-{suffix}"
+
+ def template(tags):
+ return json.dumps({
+ "Resources": {"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {
+ "CidrBlock": "10.47.0.0/16", "Tags": tags}}},
+ "Outputs": {"VpcId": {"Value": {"Ref": "Vpc"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template([{"Key": "a", "Value": "1"}]))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ vpc_id = _cfn_output(cfn, stack_name, "VpcId")
+ ec2.create_tags(Resources=[vpc_id], Tags=[{"Key": "api", "Value": "kept"}])
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(
+ [{"Key": "a", "Value": "2"}, {"Key": "b", "Value": "3"}]))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ tags = ec2.describe_vpcs(VpcIds=[vpc_id])["Vpcs"][0].get("Tags", [])
+ assert sorted((t["Key"], t["Value"]) for t in tags
+ if not t["Key"].startswith("aws:")) == [
+ ("a", "2"), ("api", "kept"), ("b", "3")]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_vpc_dns_hostnames_change_is_rolled_back(cfn, ec2):
+ """EnableDnsHostnames is applied in place, so a later failure in the same
+ update has to set it back. Measured on AWS 2026-09-21: the VPC reads
+ enableDnsHostnames false again after UPDATE_ROLLBACK_COMPLETE."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-vpc-rb-{suffix}"
+
+ def template(hostnames, with_bad):
+ resources = {"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {
+ "CidrBlock": "10.48.0.0/16", "EnableDnsSupport": True,
+ "EnableDnsHostnames": hostnames}}}
+ if with_bad:
+ resources["Bad"] = {**_FAILING_RESOURCE, "DependsOn": "Vpc"}
+ return json.dumps({"Resources": resources,
+ "Outputs": {"VpcId": {"Value": {"Ref": "Vpc"}}}})
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(False, False))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ vpc_id = _cfn_output(cfn, stack_name, "VpcId")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(True, True))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ assert _cfn_output(cfn, stack_name, "VpcId") == vpc_id
+ assert _cfn_vpc_attribute(ec2, vpc_id, "enableDnsHostnames") is False
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_vpc_create_only_ipam_members_replace_the_vpc(cfn, ec2):
+ """Ipv4IpamPoolId, Ipv4NetmaskLength and VpcEncryptionControl are
+ create-only on AWS::EC2::VPC (the registry's createOnlyProperties), so a
+ change replaces the VPC. The handler keyed its replacement on CidrBlock
+ and tenancy alone and applied such a change as an in-place no-op."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-vpc-ipam-{suffix}"
+
+ def template(netmask):
+ return json.dumps({
+ "Resources": {"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {
+ "Ipv4IpamPoolId": "ipam-pool-0123456789abcdef0",
+ "Ipv4NetmaskLength": netmask}}},
+ "Outputs": {"VpcId": {"Value": {"Ref": "Vpc"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(24))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ before = _cfn_output(cfn, stack_name, "VpcId")
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(28))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ after = _cfn_output(cfn, stack_name, "VpcId")
+ assert after != before
+ assert not ec2.describe_vpcs(Filters=[{"Name": "vpc-id", "Values": [before]}])["Vpcs"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_subnet_update_keeps_id(cfn, ec2):
+ """MapPublicIpOnLaunch is No interruption on AWS::EC2::Subnet, so the
+ subnet keeps its id; anything holding it (instances, ENIs, load balancer
+ subnet lists) would otherwise dangle."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-subnet-upd-{suffix}"
+
+ def template(public):
+ return json.dumps({
+ "Resources": {
+ "Vpc": {"Type": "AWS::EC2::VPC",
+ "Properties": {"CidrBlock": "10.43.0.0/16"}},
+ "Subnet": {
+ "Type": "AWS::EC2::Subnet",
+ "Properties": {
+ "VpcId": {"Ref": "Vpc"},
+ "CidrBlock": "10.43.1.0/24",
+ "MapPublicIpOnLaunch": public,
+ },
+ },
+ },
+ "Outputs": {"SubnetId": {"Value": {"Ref": "Subnet"}}},
+ })
+
+ def subnet_id():
+ return next(o["OutputValue"] for o in
+ cfn.describe_stacks(StackName=stack_name)["Stacks"][0]["Outputs"]
+ if o["OutputKey"] == "SubnetId")
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(False))
+ _wait_stack(cfn, stack_name)
+ before = subnet_id()
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(True))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+
+ assert subnet_id() == before, "the subnet came back under a new id"
+ described = ec2.describe_subnets(SubnetIds=[before])["Subnets"][0]
+ assert described["MapPublicIpOnLaunch"] is True
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_subnet_keeps_map_public_ip_when_the_property_is_removed(cfn, ec2):
+ """A template that stops setting MapPublicIpOnLaunch leaves the subnet's
+ attribute as it is: measured on AWS 2026-09-21, true stays true after the
+ property is removed. The update wrote the default false instead."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-subnet-map-{suffix}"
+
+ def template(extra):
+ return json.dumps({
+ "Resources": {
+ "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.49.0.0/16"}},
+ "Subnet": {"Type": "AWS::EC2::Subnet", "Properties": {
+ "VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.49.1.0/24", **extra}},
+ },
+ "Outputs": {"SubnetId": {"Value": {"Ref": "Subnet"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template({"MapPublicIpOnLaunch": True}))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ subnet_id = _cfn_output(cfn, stack_name, "SubnetId")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template({}))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _cfn_output(cfn, stack_name, "SubnetId") == subnet_id
+ described = ec2.describe_subnets(SubnetIds=[subnet_id])["Subnets"][0]
+ assert described["MapPublicIpOnLaunch"] is True
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_subnet_create_only_members_replace_the_subnet(cfn, ec2):
+ """AvailabilityZoneId, the IPAM members, Ipv6Native and OutpostArn are
+ create-only on AWS::EC2::Subnet (the registry's createOnlyProperties).
+ The handler keyed its replacement on VpcId, CidrBlock and
+ AvailabilityZone alone, so a zone given by id was ignored at create and
+ its change applied as an in-place no-op."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-subnet-azid-{suffix}"
+
+ def template(zone_id):
+ return json.dumps({
+ "Resources": {
+ "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.53.0.0/16"}},
+ "Subnet": {"Type": "AWS::EC2::Subnet", "Properties": {
+ "VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.53.1.0/24",
+ "AvailabilityZoneId": zone_id}},
+ },
+ "Outputs": {"SubnetId": {"Value": {"Ref": "Subnet"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("use1-az2"))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ before = _cfn_output(cfn, stack_name, "SubnetId")
+ subnet = ec2.describe_subnets(SubnetIds=[before])["Subnets"][0]
+ assert (subnet["AvailabilityZoneId"], subnet["AvailabilityZone"]) == ("use1-az2", "us-east-1b")
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("use1-az3"))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ after = _cfn_output(cfn, stack_name, "SubnetId")
+ assert after != before
+ assert ec2.describe_subnets(SubnetIds=[after])["Subnets"][0]["AvailabilityZoneId"] == "use1-az3"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_subnet_dns_name_options_update_in_place(cfn, ec2):
+ """PrivateDnsNameOptionsOnLaunch is No interruption on AWS::EC2::Subnet.
+ AWS answers it (and EnableDns64, Ipv6Native, AssignIpv6AddressOnCreation,
+ false by default) in DescribeSubnets, applies a change in place, keeps
+ the value when the template removes the property, and fails EnableDns64
+ on a subnet without an IPv6 block (measured 2026-09-21). None of the
+ four was stored or answered."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-subnet-dns-{suffix}"
+
+ def template(extra):
+ return json.dumps({
+ "Resources": {
+ "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.55.0.0/16"}},
+ "Subnet": {"Type": "AWS::EC2::Subnet", "Properties": {
+ "VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.55.1.0/24", **extra}},
+ },
+ "Outputs": {"SubnetId": {"Value": {"Ref": "Subnet"}}},
+ })
+
+ def attributes(subnet_id):
+ subnet = ec2.describe_subnets(SubnetIds=[subnet_id])["Subnets"][0]
+ return {key: subnet.get(key) for key in (
+ "PrivateDnsNameOptionsOnLaunch", "EnableDns64", "Ipv6Native",
+ "AssignIpv6AddressOnCreation")}
+
+ def options(hostname_type, a_record):
+ return {"HostnameType": hostname_type, "EnableResourceNameDnsARecord": a_record,
+ "EnableResourceNameDnsAAAARecord": False}
+
+ resource_name = {"HostnameType": "resource-name", "EnableResourceNameDnsARecord": True}
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(
+ {"PrivateDnsNameOptionsOnLaunch": resource_name}))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ subnet_id = _cfn_output(cfn, stack_name, "SubnetId")
+ defaults = {"EnableDns64": False, "Ipv6Native": False, "AssignIpv6AddressOnCreation": False}
+ assert attributes(subnet_id) == {
+ "PrivateDnsNameOptionsOnLaunch": options("resource-name", True), **defaults}
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template({
+ "PrivateDnsNameOptionsOnLaunch": {
+ "HostnameType": "ip-name", "EnableResourceNameDnsARecord": False}}))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ assert _cfn_output(cfn, stack_name, "SubnetId") == subnet_id
+ assert attributes(subnet_id)["PrivateDnsNameOptionsOnLaunch"] == options("ip-name", False)
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(
+ {"PrivateDnsNameOptionsOnLaunch": resource_name}))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ cfn.update_stack(StackName=stack_name, TemplateBody=template({}))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ assert attributes(subnet_id)["PrivateDnsNameOptionsOnLaunch"] == options("resource-name", True)
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template({"EnableDns64": True}))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ reasons = [e.get("ResourceStatusReason", "")
+ for e in cfn.describe_stack_events(StackName=stack_name)["StackEvents"]
+ if e["LogicalResourceId"] == "Subnet" and e["ResourceStatus"] == "UPDATE_FAILED"]
+ assert reasons and "Property Ipv6CidrBlock or Ipv6IpamPoolId cannot be empty." in reasons[0]
+ assert attributes(subnet_id)["EnableDns64"] is False
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_security_group_update_keeps_id_and_rules(cfn, ec2):
+ """SecurityGroupIngress is "Some interruptions" on
+ AWS::EC2::SecurityGroup, which is an in-place update, and Tags is No
+ interruption. The create mints a new group id, so every rule added through
+ AuthorizeSecurityGroupIngress went with the old group."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-sg-upd-{suffix}"
+
+ def template(port):
+ return json.dumps({
+ "Resources": {
+ "Vpc": {"Type": "AWS::EC2::VPC",
+ "Properties": {"CidrBlock": "10.44.0.0/16"}},
+ "Sg": {
+ "Type": "AWS::EC2::SecurityGroup",
+ "Properties": {
+ "GroupDescription": "probe",
+ "VpcId": {"Ref": "Vpc"},
+ "SecurityGroupIngress": [
+ {"IpProtocol": "tcp", "FromPort": port,
+ "ToPort": port, "CidrIp": "10.0.0.0/8"},
+ ],
+ },
+ },
+ },
+ "Outputs": {"SgId": {"Value": {"Fn::GetAtt": ["Sg", "GroupId"]}}},
+ })
+
+ def sg_id():
+ return next(o["OutputValue"] for o in
+ cfn.describe_stacks(StackName=stack_name)["Stacks"][0]["Outputs"]
+ if o["OutputKey"] == "SgId")
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(80))
+ _wait_stack(cfn, stack_name)
+ before = sg_id()
+ # A rule added out of band is what the replacement destroys.
+ ec2.authorize_security_group_ingress(
+ GroupId=before,
+ IpPermissions=[{"IpProtocol": "tcp", "FromPort": 8443, "ToPort": 8443,
+ "IpRanges": [{"CidrIp": "192.0.2.0/24"}]}])
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(443))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+
+ assert sg_id() == before, "the security group came back under a new id"
+ perms = ec2.describe_security_groups(
+ GroupIds=[before])["SecurityGroups"][0]["IpPermissions"]
+ ports = sorted(p["FromPort"] for p in perms if "FromPort" in p)
+ assert 443 in ports, "the template's new ingress rule was not applied"
+ assert 8443 in ports, "the out-of-band rule was destroyed"
+ assert 80 not in ports, "the template's old ingress rule survived"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_security_group_rule_members_update_in_place(cfn, ec2):
+ """A rule's Description, a SourcePrefixListId source and a source group's
+ name and owner are members of SecurityGroupIngress and
+ SecurityGroupEgress. AWS applies a rule with a prefix-list source and
+ changes a description in place (measured 2026-09-21); the provisioner
+ dropped all of them, so a prefix-list rule was lost outright and two
+ rules differing only in their prefix list compared equal."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-sg-members-{suffix}"
+ prefix_list = ec2.create_managed_prefix_list(
+ PrefixListName=f"cfn-sg-members-{suffix}", MaxEntries=1, AddressFamily="IPv4",
+ Entries=[{"Cidr": "198.51.100.0/24"}])["PrefixList"]["PrefixListId"]
+
+ def template(ingress_description, egress_description, with_list):
+ ingress = [{"IpProtocol": "tcp", "FromPort": 22, "ToPort": 22,
+ "CidrIp": "10.0.0.0/8", "Description": ingress_description},
+ {"IpProtocol": "tcp", "FromPort": 8080, "ToPort": 8080,
+ "SourceSecurityGroupId": {"Fn::GetAtt": ["Vpc", "DefaultSecurityGroup"]},
+ "Description": "from the default group"}]
+ if with_list:
+ ingress.append({"IpProtocol": "tcp", "FromPort": 443, "ToPort": 443,
+ "SourcePrefixListId": prefix_list, "Description": "from the list"})
+ return json.dumps({
+ "Resources": {
+ "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.57.0.0/16"}},
+ "Sg": {"Type": "AWS::EC2::SecurityGroup", "Properties": {
+ "GroupDescription": "members", "VpcId": {"Ref": "Vpc"},
+ "SecurityGroupIngress": ingress,
+ "SecurityGroupEgress": [{"IpProtocol": "-1", "CidrIp": "0.0.0.0/0",
+ "Description": egress_description}]}},
+ },
+ "Outputs": {"Sg": {"Value": {"Fn::GetAtt": ["Sg", "GroupId"]}}},
+ })
+
+ def rules(group_id, member):
+ group = ec2.describe_security_groups(GroupIds=[group_id])["SecurityGroups"][0]
+ flat = []
+ for perm in group[member]:
+ for entry in perm.get("IpRanges", []):
+ flat.append((perm.get("FromPort"), entry["CidrIp"], entry.get("Description")))
+ for entry in perm.get("PrefixListIds", []):
+ flat.append((perm.get("FromPort"), entry["PrefixListId"], entry.get("Description")))
+ for entry in perm.get("UserIdGroupPairs", []):
+ flat.append((perm.get("FromPort"), "group", entry.get("Description")))
+ return sorted(flat, key=str)
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("a", "e1", True))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ group_id = _cfn_output(cfn, stack_name, "Sg")
+ listed = (443, prefix_list, "from the list")
+ by_group = (8080, "group", "from the default group")
+ assert rules(group_id, "IpPermissions") == sorted(
+ [(22, "10.0.0.0/8", "a"), listed, by_group], key=str)
+ assert rules(group_id, "IpPermissionsEgress") == [(None, "0.0.0.0/0", "e1")]
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("b", "e1", True))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ assert _cfn_output(cfn, stack_name, "Sg") == group_id
+ assert rules(group_id, "IpPermissions") == sorted(
+ [(22, "10.0.0.0/8", "b"), listed, by_group], key=str)
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("b", "e2", True))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ assert rules(group_id, "IpPermissionsEgress") == [(None, "0.0.0.0/0", "e2")]
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("b", "e2", False))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ assert rules(group_id, "IpPermissions") == sorted(
+ [(22, "10.0.0.0/8", "b"), by_group], key=str)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ ec2.delete_managed_prefix_list(PrefixListId=prefix_list)
+
+
+def test_cfn_ec2_security_group_egress_update_matches_the_create(cfn, ec2):
+ """A group whose template declares no egress gets the allow-all egress
+ rule, and one that declares egress gets only those rules. Measured on AWS
+ 2026-09-21: declaring egress in an update takes the allow-all rule away,
+ and dropping the declaration again leaves the group with no egress rule
+ from the template; allow-all does not come back. A rule authorized
+ outside the template stays either way."""
+ stack_name = f"cfn-sg-egress-{_uuid_mod.uuid4().hex[:8]}"
+
+ def template(egress):
+ props = {"GroupDescription": "egress", "VpcId": {"Ref": "Vpc"}}
+ if egress:
+ props["SecurityGroupEgress"] = [
+ {"IpProtocol": "tcp", "FromPort": 443, "ToPort": 443,
+ "CidrIp": "10.0.0.0/8"}]
+ return json.dumps({
+ "Resources": {
+ "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.58.0.0/16"}},
+ "Sg": {"Type": "AWS::EC2::SecurityGroup", "Properties": props},
+ },
+ "Outputs": {"Sg": {"Value": {"Fn::GetAtt": ["Sg", "GroupId"]}}},
+ })
+
+ def egress(group_id):
+ group = ec2.describe_security_groups(GroupIds=[group_id])["SecurityGroups"][0]
+ return sorted(
+ (perm["IpProtocol"], perm.get("FromPort"), entry["CidrIp"])
+ for perm in group["IpPermissionsEgress"]
+ for entry in perm.get("IpRanges", [])
+ )
+
+ allow_all = ("-1", None, "0.0.0.0/0")
+ declared = ("tcp", 443, "10.0.0.0/8")
+ foreign = ("tcp", 25, "192.0.2.0/24")
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(False))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ group_id = _cfn_output(cfn, stack_name, "Sg")
+ ec2.authorize_security_group_egress(
+ GroupId=group_id,
+ IpPermissions=[{"IpProtocol": "tcp", "FromPort": 25, "ToPort": 25,
+ "IpRanges": [{"CidrIp": "192.0.2.0/24"}]}])
+ assert egress(group_id) == sorted([allow_all, foreign])
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(True))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ assert egress(group_id) == sorted([declared, foreign]), (
+ "declaring egress kept the allow-all rule the create would not add")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(False))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ assert egress(group_id) == sorted([foreign]), (
+ "dropping the egress declaration brought the allow-all rule back")
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_security_group_ingress_change_is_rolled_back(cfn, ec2):
+ """An ingress rule change is applied in place, so a later failure in the
+ same update has to take the new rule away again. Measured on AWS
+ 2026-09-21: the group's ingress ports read [22] again after
+ UPDATE_ROLLBACK_COMPLETE, under the same group id."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-sg-rb-{suffix}"
+
+ def template(ports, with_bad):
+ resources = {
+ "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.50.0.0/16"}},
+ "Sg": {"Type": "AWS::EC2::SecurityGroup", "Properties": {
+ "GroupDescription": "probe", "VpcId": {"Ref": "Vpc"},
+ "SecurityGroupIngress": [
+ {"IpProtocol": "tcp", "FromPort": port, "ToPort": port,
+ "CidrIp": "10.0.0.0/8"} for port in ports]}},
+ }
+ if with_bad:
+ resources["Bad"] = {**_FAILING_RESOURCE, "DependsOn": "Sg"}
+ return json.dumps({"Resources": resources,
+ "Outputs": {"SgId": {"Value": {"Fn::GetAtt": ["Sg", "GroupId"]}}}})
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template([22], False))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ sg_id = _cfn_output(cfn, stack_name, "SgId")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template([22, 443], True))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ assert _cfn_output(cfn, stack_name, "SgId") == sg_id
+ perms = ec2.describe_security_groups(GroupIds=[sg_id])["SecurityGroups"][0]["IpPermissions"]
+ assert sorted(p["FromPort"] for p in perms if "FromPort" in p) == [22]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_launch_template_update_adds_a_version(cfn, ec2):
+ """LaunchTemplateData is No interruption on AWS::EC2::LaunchTemplate: AWS
+ adds version N+1 under the same template. The create minted a new lt- id
+ and reset Versions and LatestVersionNumber to 1, which is exactly what an
+ Auto Scaling group reads through Fn::GetAtt LatestVersionNumber."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-lt-upd-{suffix}"
+ name = f"cfn-lt-upd-{suffix}"
+
+ def template(instance_type):
+ return json.dumps({
+ "Resources": {
+ "LT": {
+ "Type": "AWS::EC2::LaunchTemplate",
+ "Properties": {
+ "LaunchTemplateName": name,
+ "LaunchTemplateData": {
+ "ImageId": "ami-cfn7777",
+ "InstanceType": instance_type,
+ },
+ },
+ },
+ },
+ "Outputs": {
+ "LtId": {"Value": {"Ref": "LT"}},
+ "Latest": {"Value": {"Fn::GetAtt": ["LT", "LatestVersionNumber"]}},
+ "Default": {"Value": {"Fn::GetAtt": ["LT", "DefaultVersionNumber"]}},
+ },
+ })
+
+ def outputs():
+ return {o["OutputKey"]: o["OutputValue"] for o in
+ cfn.describe_stacks(StackName=stack_name)["Stacks"][0]["Outputs"]}
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("t3.micro"))
+ _wait_stack(cfn, stack_name)
+ before = outputs()
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("t3.large"))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+
+ after = outputs()
+ assert after["LtId"] == before["LtId"], \
+ "the launch template came back under a new id"
+ assert after["Latest"] == "2", \
+ f"the data change did not add a version (latest {after['Latest']})"
+ versions = ec2.describe_launch_template_versions(
+ LaunchTemplateId=before["LtId"])["LaunchTemplateVersions"]
+ assert sorted(v["VersionNumber"] for v in versions) == [1, 2]
+ latest = next(v for v in versions if v["VersionNumber"] == 2)
+ assert latest["LaunchTemplateData"]["InstanceType"] == "t3.large"
+ # The default version stays where it was: measured on AWS 2026-09-21,
+ # a data change answers latest 2 and default 1.
+ assert after["Default"] == "1"
+ assert latest["DefaultVersion"] is False
+ described = ec2.describe_launch_templates(
+ LaunchTemplateIds=[before["LtId"]])["LaunchTemplates"][0]
+ assert (described["LatestVersionNumber"], described["DefaultVersionNumber"]) == (2, 1)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_launch_template_tags_come_from_tag_specifications(cfn, ec2):
+ """AWS::EC2::LaunchTemplate has no Tags property: the template's own tags
+ are the TagSpecifications entry for "launch-template", which the create
+ ignored. Measured on AWS 2026-09-21: they are applied at creation only, so
+ a TagSpecifications change adds a version and leaves the template's tags,
+ and a tag added through CreateTags, as they were."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-lt-tags-{suffix}"
+
+ def template(value):
+ return json.dumps({
+ "Resources": {"LT": {"Type": "AWS::EC2::LaunchTemplate", "Properties": {
+ "LaunchTemplateData": {"ImageId": "ami-cfn7777", "InstanceType": "t3.micro"},
+ "TagSpecifications": [
+ {"ResourceType": "launch-template",
+ "Tags": [{"Key": "v", "Value": value}]},
+ {"ResourceType": "instance",
+ "Tags": [{"Key": "launched", "Value": "yes"}]},
+ ]}}},
+ "Outputs": {"LtId": {"Value": {"Ref": "LT"}}},
+ })
+
+ def tags(lt_id):
+ described = ec2.describe_launch_templates(LaunchTemplateIds=[lt_id])["LaunchTemplates"][0]
+ return sorted((t["Key"], t["Value"]) for t in described.get("Tags", []))
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("one"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ lt_id = _cfn_output(cfn, stack_name, "LtId")
+ assert tags(lt_id) == [("v", "one")]
+ ec2.create_tags(Resources=[lt_id], Tags=[{"Key": "api", "Value": "kept"}])
+ assert tags(lt_id) == [("api", "kept"), ("v", "one")]
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("two"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _cfn_output(cfn, stack_name, "LtId") == lt_id
+ assert tags(lt_id) == [("api", "kept"), ("v", "one")]
+ described = ec2.describe_launch_templates(LaunchTemplateIds=[lt_id])["LaunchTemplates"][0]
+ assert (described["LatestVersionNumber"], described["DefaultVersionNumber"]) == (2, 1)
+
+ # The stack delete takes the template's tags with it.
+ cfn.delete_stack(StackName=stack_name)
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"
+ assert ec2.describe_tags(
+ Filters=[{"Name": "resource-id", "Values": [lt_id]}])["Tags"] == []
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_launch_template_data_change_is_rolled_back(cfn, ec2):
+ """A LaunchTemplateData change adds a version, so a later failure in the
+ same update rolls it back the way AWS does (measured 2026-09-21): by
+ adding one more version with the old data. The template keeps its id,
+ the latest version is 3 (t3.micro, t3.large, t3.micro), the default stays
+ 1, and the stack's GetAtt outputs read what they read before the update."""
+ stack_name = f"cfn-lt-rb-{_uuid_mod.uuid4().hex[:8]}"
+
+ def template(instance_type):
+ return json.dumps({
+ "Resources": {"Lt": {"Type": "AWS::EC2::LaunchTemplate", "Properties": {
+ "LaunchTemplateData": {"ImageId": "ami-cfn7777",
+ "InstanceType": instance_type}}}},
+ "Outputs": {
+ "LtId": {"Value": {"Ref": "Lt"}},
+ "Latest": {"Value": {"Fn::GetAtt": ["Lt", "LatestVersionNumber"]}},
+ "Default": {"Value": {"Fn::GetAtt": ["Lt", "DefaultVersionNumber"]}},
+ },
+ })
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("t3.micro"))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ lt_id = _cfn_output(cfn, stack_name, "LtId")
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=_cfn_with_failing_resource(template("t3.large"), "Lt"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ assert _cfn_output(cfn, stack_name, "LtId") == lt_id
+ assert (_cfn_output(cfn, stack_name, "Latest"),
+ _cfn_output(cfn, stack_name, "Default")) == ("1", "1")
+ described = ec2.describe_launch_templates(LaunchTemplateIds=[lt_id])["LaunchTemplates"][0]
+ assert (described["LatestVersionNumber"], described["DefaultVersionNumber"]) == (3, 1)
+ versions = ec2.describe_launch_template_versions(
+ LaunchTemplateId=lt_id)["LaunchTemplateVersions"]
+ assert sorted((v["VersionNumber"], v["LaunchTemplateData"]["InstanceType"],
+ v["DefaultVersion"]) for v in versions) == [
+ (1, "t3.micro", True), (2, "t3.large", False), (3, "t3.micro", False)]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_internet_gateway_tag_update_keeps_id_and_attachment(cfn, ec2):
+ """Tags is the only property AWS::EC2::InternetGateway has, and it is No
+ interruption. The create ignored props entirely, so a tag change minted a
+ new igw- id, reset Attachments to empty and still applied no tags."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-igw-upd-{suffix}"
+
+ def template(stage):
+ return json.dumps({
+ "Resources": {
+ "Vpc": {"Type": "AWS::EC2::VPC",
+ "Properties": {"CidrBlock": "10.45.0.0/16"}},
+ "Igw": {
+ "Type": "AWS::EC2::InternetGateway",
+ "Properties": {"Tags": [{"Key": "stage", "Value": stage}]},
+ },
+ "Attach": {
+ "Type": "AWS::EC2::VPCGatewayAttachment",
+ "Properties": {"VpcId": {"Ref": "Vpc"},
+ "InternetGatewayId": {"Ref": "Igw"}},
+ },
+ },
+ "Outputs": {"IgwId": {"Value": {"Ref": "Igw"}}},
+ })
+
+ def igw_id():
+ return next(o["OutputValue"] for o in
+ cfn.describe_stacks(StackName=stack_name)["Stacks"][0]["Outputs"]
+ if o["OutputKey"] == "IgwId")
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("before"))
+ _wait_stack(cfn, stack_name)
+ before = igw_id()
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("after"))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+
+ assert igw_id() == before, "the gateway came back under a new id"
+ described = ec2.describe_internet_gateways(
+ InternetGatewayIds=[before])["InternetGateways"][0]
+ assert described["Attachments"], "the VPC attachment was dropped"
+ assert _template_tags(described.get("Tags", [])) == \
+ [{"Key": "stage", "Value": "after"}]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_internet_gateway_tag_change_is_rolled_back(cfn, ec2):
+ """A tag change on an internet gateway is applied in place, so a later
+ failure in the same update has to set it back. Measured on AWS
+ 2026-09-21: the gateway reads stage=before again after
+ UPDATE_ROLLBACK_COMPLETE, under the same id and still attached."""
+ stack_name = f"cfn-igw-rb-{_uuid_mod.uuid4().hex[:8]}"
+
+ def template(stage):
+ return json.dumps({
+ "Resources": {
+ "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.52.0.0/16"}},
+ "Igw": {"Type": "AWS::EC2::InternetGateway",
+ "Properties": {"Tags": [{"Key": "stage", "Value": stage}]}},
+ "Attach": {"Type": "AWS::EC2::VPCGatewayAttachment", "Properties": {
+ "VpcId": {"Ref": "Vpc"}, "InternetGatewayId": {"Ref": "Igw"}}},
+ },
+ "Outputs": {"IgwId": {"Value": {"Ref": "Igw"}}},
+ })
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("before"))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ igw_id = _cfn_output(cfn, stack_name, "IgwId")
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=_cfn_with_failing_resource(template("after"), "Igw"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ assert _cfn_output(cfn, stack_name, "IgwId") == igw_id
+ described = ec2.describe_internet_gateways(
+ InternetGatewayIds=[igw_id])["InternetGateways"][0]
+ assert described["Attachments"], "the VPC attachment was dropped"
+ assert _template_tags(described.get("Tags", [])) == [{"Key": "stage", "Value": "before"}]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_route_table_tag_update_keeps_id_and_routes(cfn, ec2):
+ """Tags is the only property AWS::EC2::RouteTable has. The create minted a
+ new rtb- id and reset Routes to the local route and Associations to empty,
+ so anything added through CreateRoute or AssociateRouteTable was lost."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-rtb-upd-{suffix}"
+
+ def template(stage):
+ return json.dumps({
+ "Resources": {
+ "Vpc": {"Type": "AWS::EC2::VPC",
+ "Properties": {"CidrBlock": "10.46.0.0/16"}},
+ "Rtb": {
+ "Type": "AWS::EC2::RouteTable",
+ "Properties": {"VpcId": {"Ref": "Vpc"},
+ "Tags": [{"Key": "stage", "Value": stage}]},
+ },
+ },
+ "Outputs": {"RtbId": {"Value": {"Ref": "Rtb"}}},
+ })
+
+ def rtb_id():
+ return next(o["OutputValue"] for o in
+ cfn.describe_stacks(StackName=stack_name)["Stacks"][0]["Outputs"]
+ if o["OutputKey"] == "RtbId")
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("before"))
+ _wait_stack(cfn, stack_name)
+ before = rtb_id()
+ # A route added out of band is what the replacement destroys.
+ ec2.create_route(RouteTableId=before, DestinationCidrBlock="198.51.100.0/24",
+ GatewayId="local")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("after"))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+
+ assert rtb_id() == before, "the route table came back under a new id"
+ table = ec2.describe_route_tables(RouteTableIds=[before])["RouteTables"][0]
+ dests = [r.get("DestinationCidrBlock") for r in table["Routes"]]
+ assert "198.51.100.0/24" in dests, "the out-of-band route was destroyed"
+ assert _template_tags(table.get("Tags", [])) == \
+ [{"Key": "stage", "Value": "after"}]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_route_table_tag_change_is_rolled_back(cfn, ec2):
+ """A tag change on a route table is applied in place, so a later failure
+ in the same update has to set it back. Measured on AWS 2026-09-21: the
+ table reads stage=before again after UPDATE_ROLLBACK_COMPLETE, under the
+ same id."""
+ stack_name = f"cfn-rtb-rb-{_uuid_mod.uuid4().hex[:8]}"
+
+ def template(stage):
+ return json.dumps({
+ "Resources": {
+ "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.53.0.0/16"}},
+ "Rtb": {"Type": "AWS::EC2::RouteTable", "Properties": {
+ "VpcId": {"Ref": "Vpc"}, "Tags": [{"Key": "stage", "Value": stage}]}},
+ },
+ "Outputs": {"RtbId": {"Value": {"Ref": "Rtb"}}},
+ })
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("before"))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ rtb_id = _cfn_output(cfn, stack_name, "RtbId")
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=_cfn_with_failing_resource(template("after"), "Rtb"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ assert _cfn_output(cfn, stack_name, "RtbId") == rtb_id
+ table = ec2.describe_route_tables(RouteTableIds=[rtb_id])["RouteTables"][0]
+ assert _template_tags(table.get("Tags", [])) == [{"Key": "stage", "Value": "before"}]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_network_tag_change_keeps_tags_added_through_the_api(cfn, ec2):
+ """The subnet, security group, internet gateway and route table apply a
+ template tag change the way the VPC does: the template's tags take their
+ new values and a tag added through CreateTags survives, as on AWS
+ (measured 2026-09-21 on a VPC). The updates overwrote the whole tag
+ list."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-net-tags-{suffix}"
+
+ def template(value):
+ tags = [{"Key": "a", "Value": value}]
+ return json.dumps({
+ "Resources": {
+ "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.51.0.0/16"}},
+ "Subnet": {"Type": "AWS::EC2::Subnet", "Properties": {
+ "VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.51.1.0/24", "Tags": tags}},
+ "Sg": {"Type": "AWS::EC2::SecurityGroup", "Properties": {
+ "GroupDescription": "probe", "VpcId": {"Ref": "Vpc"}, "Tags": tags}},
+ "Igw": {"Type": "AWS::EC2::InternetGateway", "Properties": {"Tags": tags}},
+ "Rtb": {"Type": "AWS::EC2::RouteTable", "Properties": {
+ "VpcId": {"Ref": "Vpc"}, "Tags": tags}},
+ },
+ "Outputs": {
+ "Subnet": {"Value": {"Ref": "Subnet"}},
+ "Sg": {"Value": {"Fn::GetAtt": ["Sg", "GroupId"]}},
+ "Igw": {"Value": {"Ref": "Igw"}},
+ "Rtb": {"Value": {"Ref": "Rtb"}},
+ },
+ })
+
+ def tags_of(resource_id):
+ found = ec2.describe_tags(
+ Filters=[{"Name": "resource-id", "Values": [resource_id]}])["Tags"]
+ return sorted((t["Key"], t["Value"]) for t in found if not t["Key"].startswith("aws:"))
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("1"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ ids = {key: _cfn_output(cfn, stack_name, key) for key in ("Subnet", "Sg", "Igw", "Rtb")}
+ ec2.create_tags(Resources=list(ids.values()), Tags=[{"Key": "api", "Value": "kept"}])
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("2"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ for key, resource_id in ids.items():
+ assert _cfn_output(cfn, stack_name, key) == resource_id, key
+ assert tags_of(resource_id) == [("a", "2"), ("api", "kept")], key
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_networking_resources_carry_the_stack_tags(cfn, ec2):
+ """A VPC, subnet, security group, internet gateway and route table carry
+ the three aws:cloudformation:* tags and the stack-level tags beside their
+ own, and a stack-tag change reaches them (measured on AWS 2026-09-21).
+ The five types were missing from the stack-tag table, so they carried the
+ template's tags only."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-net-stack-tags-{suffix}"
+ own = [{"Key": "own", "Value": "a"}]
+ template = json.dumps({
+ "Resources": {
+ "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.63.0.0/16", "Tags": own}},
+ "Subnet": {"Type": "AWS::EC2::Subnet", "Properties": {
+ "VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.63.1.0/24", "Tags": own}},
+ "Sg": {"Type": "AWS::EC2::SecurityGroup", "Properties": {
+ "GroupDescription": "stack tags", "VpcId": {"Ref": "Vpc"}, "Tags": own}},
+ "Igw": {"Type": "AWS::EC2::InternetGateway", "Properties": {"Tags": own}},
+ "Rtb": {"Type": "AWS::EC2::RouteTable", "Properties": {"VpcId": {"Ref": "Vpc"}, "Tags": own}},
+ },
+ "Outputs": {
+ "Vpc": {"Value": {"Ref": "Vpc"}}, "Subnet": {"Value": {"Ref": "Subnet"}},
+ "Sg": {"Value": {"Fn::GetAtt": ["Sg", "GroupId"]}},
+ "Igw": {"Value": {"Ref": "Igw"}}, "Rtb": {"Value": {"Ref": "Rtb"}},
+ },
+ })
+
+ def tags_of(resource_id):
+ return {t["Key"]: t["Value"] for t in ec2.describe_tags(
+ Filters=[{"Name": "resource-id", "Values": [resource_id]}])["Tags"]}
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template,
+ Tags=[{"Key": "stage", "Value": "one"}])
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ ids = {key: _cfn_output(cfn, stack_name, key) for key in ("Vpc", "Subnet", "Sg", "Igw", "Rtb")}
+ for logical_id, resource_id in ids.items():
+ assert tags_of(resource_id) == {
+ "own": "a", "stage": "one",
+ "aws:cloudformation:stack-name": stack_name,
+ "aws:cloudformation:stack-id": stack["StackId"],
+ "aws:cloudformation:logical-id": logical_id,
+ }, logical_id
+ cfn.update_stack(StackName=stack_name, UsePreviousTemplate=True,
+ Tags=[{"Key": "stage", "Value": "two"}])
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ for logical_id, resource_id in ids.items():
+ assert tags_of(resource_id)["stage"] == "two", logical_id
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_route_target_change_does_not_duplicate(cfn, ec2):
+ """The physical id of AWS::EC2::Route is "{table}|{destination}", so a
+ changed target leaves it unmoved and the engine declares no replacement.
+ The create then appended a second entry, leaving the table holding two
+ routes for one destination."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-route-upd-{suffix}"
+
+ def template(target):
+ return json.dumps({
+ "Resources": {
+ "Vpc": {"Type": "AWS::EC2::VPC",
+ "Properties": {"CidrBlock": "10.47.0.0/16"}},
+ "Rtb": {"Type": "AWS::EC2::RouteTable",
+ "Properties": {"VpcId": {"Ref": "Vpc"}}},
+ "Igw": {"Type": "AWS::EC2::InternetGateway"},
+ "Attach": {
+ "Type": "AWS::EC2::VPCGatewayAttachment",
+ "Properties": {"VpcId": {"Ref": "Vpc"},
+ "InternetGatewayId": {"Ref": "Igw"}},
+ },
+ "Route": {
+ "Type": "AWS::EC2::Route",
+ "DependsOn": "Attach",
+ "Properties": {
+ "RouteTableId": {"Ref": "Rtb"},
+ "DestinationCidrBlock": "0.0.0.0/0",
+ "GatewayId": target,
+ },
+ },
+ },
+ "Outputs": {"RtbId": {"Value": {"Ref": "Rtb"}}},
+ })
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("igw-aaaaaaaa"))
+ _wait_stack(cfn, stack_name)
+ rtb = next(o["OutputValue"] for o in
+ cfn.describe_stacks(StackName=stack_name)["Stacks"][0]["Outputs"]
+ if o["OutputKey"] == "RtbId")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("igw-bbbbbbbb"))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+
+ table = ec2.describe_route_tables(RouteTableIds=[rtb])["RouteTables"][0]
+ default = [r for r in table["Routes"]
+ if r.get("DestinationCidrBlock") == "0.0.0.0/0"]
+ assert len(default) == 1, \
+ f"the target change left {len(default)} routes for one destination"
+ assert default[0].get("GatewayId") == "igw-bbbbbbbb"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ec2_route_destinations_are_separate_routes(cfn, ec2):
+ """DestinationCidrBlock, DestinationIpv6CidrBlock and
+ DestinationPrefixListId are three create-only properties of
+ AWS::EC2::Route, each naming its own route: on AWS a prefix-list route
+ and an IPv6 default route sit beside the IPv4 default route, and removing
+ one leaves the others (measured 2026-09-21). The provisioner read only
+ DestinationCidrBlock and defaulted it to 0.0.0.0/0, so a prefix-list or
+ IPv6 route took the IPv4 default route's place."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-route-dest-{suffix}"
+ prefix_list = ec2.create_managed_prefix_list(
+ PrefixListName=f"cfn-route-dest-{suffix}", MaxEntries=1, AddressFamily="IPv4",
+ Entries=[{"Cidr": "198.51.100.0/24"}])["PrefixList"]["PrefixListId"]
+
+ def template(with_v4):
+ routes = {
+ "RoutePl": {"DestinationPrefixListId": prefix_list},
+ "Route6": {"DestinationIpv6CidrBlock": "::/0"},
+ }
+ if with_v4:
+ routes["Route4"] = {"DestinationCidrBlock": "0.0.0.0/0"}
+ return json.dumps({
+ "Resources": {
+ "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.59.0.0/16"}},
+ "Rtb": {"Type": "AWS::EC2::RouteTable", "Properties": {"VpcId": {"Ref": "Vpc"}}},
+ "Igw": {"Type": "AWS::EC2::InternetGateway"},
+ "Attach": {"Type": "AWS::EC2::VPCGatewayAttachment", "Properties": {
+ "VpcId": {"Ref": "Vpc"}, "InternetGatewayId": {"Ref": "Igw"}}},
+ **{logical_id: {"Type": "AWS::EC2::Route", "DependsOn": "Attach", "Properties": {
+ "RouteTableId": {"Ref": "Rtb"}, "GatewayId": {"Ref": "Igw"}, **destination}}
+ for logical_id, destination in routes.items()},
+ },
+ "Outputs": {"Rtb": {"Value": {"Ref": "Rtb"}}, "RoutePl": {"Value": {"Ref": "RoutePl"}}},
+ })
+
+ def destinations(rtb):
+ table = ec2.describe_route_tables(RouteTableIds=[rtb])["RouteTables"][0]
+ return sorted(
+ r.get("DestinationCidrBlock") or r.get("DestinationIpv6CidrBlock")
+ or r.get("DestinationPrefixListId") for r in table["Routes"])
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(True))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ rtb = _cfn_output(cfn, stack_name, "Rtb")
+ assert _cfn_output(cfn, stack_name, "RoutePl") == f"{rtb}|{prefix_list}"
+ assert destinations(rtb) == sorted(["0.0.0.0/0", "10.59.0.0/16", "::/0", prefix_list])
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(False))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ assert destinations(rtb) == sorted(["10.59.0.0/16", "::/0", prefix_list])
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ ec2.delete_managed_prefix_list(PrefixListId=prefix_list)
diff --git a/tests/test_cfn_update_rollback.py b/tests/test_cfn_update_rollback.py
new file mode 100644
index 00000000..f2472851
--- /dev/null
+++ b/tests/test_cfn_update_rollback.py
@@ -0,0 +1,339 @@
+"""A failed CloudFormation update rolls back its in-place changes and its parameters."""
+
+import json
+import time
+import uuid as _uuid_mod
+
+from botocore.exceptions import ClientError
+from test_cfn import (
+ _CR_LAMBDA_ROLE,
+ _FAILING_RESOURCE,
+ _cfn_appsync_members_template,
+ _cr_make_zip,
+ _delete_cfn_test_stack,
+ _wait_stack,
+)
+
+
+def test_cfn_update_rollback_records_the_cleanup_phase(cfn):
+ """The events of an update rollback as AWS records them (measured
+ 2026-09-21): the stack's UPDATE_ROLLBACK_IN_PROGRESS names the resource
+ that failed, "failed to update" for one that existed before the update and
+ "failed to create" for one the update added; what the update created is
+ deleted in UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS, each resource with
+ DELETE_IN_PROGRESS then DELETE_COMPLETE; the final UPDATE_ROLLBACK_COMPLETE
+ carries no reason."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-rb-events-{uid}"
+ table_name = f"cfn-rb-events-{uid}"
+
+ def template(key_type, extra=None):
+ resources = {
+ "Table": {"Type": "AWS::DynamoDB::Table", "Properties": {
+ "TableName": table_name,
+ "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": key_type}],
+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
+ "BillingMode": "PAY_PER_REQUEST",
+ }},
+ }
+ if extra == "wait":
+ resources["Handle"] = {"Type": "AWS::CloudFormation::WaitConditionHandle"}
+ resources["Wait"] = {"Type": "AWS::CloudFormation::WaitCondition",
+ "Properties": {"Handle": {"Ref": "Handle"}, "Timeout": "1"}}
+ elif extra == "added":
+ resources["Added"] = {"Type": "AWS::SQS::Queue", "Properties": {}}
+ resources["Table"]["DependsOn"] = "Added"
+ return json.dumps({"Resources": resources})
+
+ def rollback_events():
+ events = list(reversed(cfn.describe_stack_events(StackName=stack_name)["StackEvents"]))
+ start = max(i for i, e in enumerate(events)
+ if e["LogicalResourceId"] == stack_name
+ and e["ResourceStatus"] == "UPDATE_IN_PROGRESS")
+ return events[start:]
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("S"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+
+ # An existing resource fails: the table's key type change is refused,
+ # after the update created a queue.
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("N", "added"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ events = rollback_events()
+ stack_events = [(e["ResourceStatus"], e.get("ResourceStatusReason", ""))
+ for e in events if e["LogicalResourceId"] == stack_name]
+ assert stack_events[1:] == [
+ ("UPDATE_ROLLBACK_IN_PROGRESS", "The following resource(s) failed to update: [Table]. "),
+ ("UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS", ""),
+ ("UPDATE_ROLLBACK_COMPLETE", ""),
+ ]
+ cleanup = next(i for i, e in enumerate(events)
+ if e["ResourceStatus"] == "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS")
+ assert [(e["LogicalResourceId"], e["ResourceStatus"]) for e in events[cleanup + 1:]] == [
+ ("Added", "DELETE_IN_PROGRESS"), ("Added", "DELETE_COMPLETE"),
+ (stack_name, "UPDATE_ROLLBACK_COMPLETE")]
+
+ # A resource the update adds fails: the wait condition times out.
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("S", "wait"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ reasons = [e.get("ResourceStatusReason", "") for e in rollback_events()
+ if e["LogicalResourceId"] == stack_name
+ and e["ResourceStatus"] == "UPDATE_ROLLBACK_IN_PROGRESS"]
+ assert reasons == ["The following resource(s) failed to create: [Wait]. "]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_change_set_rollback_restores_the_parameters(cfn, sqs):
+ """An executed change set that rolls back leaves the stack reporting the
+ parameters it had before, as UpdateStack's rollback does (measured on AWS
+ 2026-09-21: DescribeStacks answers P=30 after a change set set it to 45
+ and failed). The execute path kept no copy of them, so the stack reported
+ the values of the update it had just undone."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cs-rb-params-{uid}"
+ queue_name = f"cfn-cs-rb-params-{uid}"
+ template = json.dumps({
+ "Parameters": {"P": {"Type": "String", "Default": "30"},
+ "K": {"Type": "String", "Default": "S"}},
+ "Resources": {
+ "Queue": {"Type": "AWS::SQS::Queue", "Properties": {
+ "QueueName": queue_name, "VisibilityTimeout": {"Ref": "P"}}},
+ "Table": {"Type": "AWS::DynamoDB::Table", "DependsOn": "Queue", "Properties": {
+ "TableName": f"cfn-cs-rb-params-{uid}",
+ "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": {"Ref": "K"}}],
+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
+ "BillingMode": "PAY_PER_REQUEST",
+ }},
+ },
+ })
+ cfn.create_stack(StackName=stack_name, TemplateBody=template)
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ cfn.create_change_set(
+ StackName=stack_name, ChangeSetName="raise", UsePreviousTemplate=True,
+ Parameters=[{"ParameterKey": "P", "ParameterValue": "45"},
+ {"ParameterKey": "K", "ParameterValue": "N"}])
+ for _ in range(60):
+ change_set = cfn.describe_change_set(StackName=stack_name, ChangeSetName="raise")
+ if not change_set["Status"].endswith(("_PENDING", "_IN_PROGRESS")):
+ break
+ time.sleep(0.5)
+ assert change_set["Status"] == "CREATE_COMPLETE", change_set.get("StatusReason")
+ cfn.execute_change_set(StackName=stack_name, ChangeSetName="raise")
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ assert sorted((p["ParameterKey"], p["ParameterValue"])
+ for p in stack["Parameters"]) == [("K", "S"), ("P", "30")]
+ queue_url = sqs.get_queue_url(QueueName=queue_name)["QueueUrl"]
+ assert sqs.get_queue_attributes(
+ QueueUrl=queue_url, AttributeNames=["VisibilityTimeout"]
+ )["Attributes"]["VisibilityTimeout"] == "30"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def _cr_mode_handler(fail_mode):
+ """A custom-resource handler that refuses an Update whose target Mode is
+ ``fail_mode`` and accepts every other request, keeping its physical id."""
+ return f"""\
+import json, urllib.request
+
+FAIL_MODE = {fail_mode!r}
+
+def handler(event, context):
+ mode = event.get("ResourceProperties", {{}}).get("Mode")
+ failed = event["RequestType"] == "Update" and mode == FAIL_MODE
+ payload = json.dumps({{
+ "Status": "FAILED" if failed else "SUCCESS",
+ "Reason": "update to %s refused for testing" % mode,
+ "RequestId": event["RequestId"],
+ "StackId": event["StackId"],
+ "LogicalResourceId": event["LogicalResourceId"],
+ "PhysicalResourceId": event.get("PhysicalResourceId") or "mode-cr",
+ "Data": {{"Mode": str(mode)}},
+ }}).encode()
+ req = urllib.request.Request(
+ event["ResponseURL"], data=payload, method="PUT",
+ headers={{"content-type": "", "content-length": str(len(payload))}},
+ )
+ urllib.request.urlopen(req, timeout=10)
+"""
+
+
+def _cfn_mode_cr_function(lam, fn, fail_mode):
+ lam.create_function(
+ FunctionName=fn, Runtime="python3.12", Role=_CR_LAMBDA_ROLE, Handler="index.handler",
+ Code={"ZipFile": _cr_make_zip(_cr_mode_handler(fail_mode))},
+ )
+
+
+def _cfn_mode_cr_accept_all(lam, fn):
+ lam.update_function_code(FunctionName=fn, ZipFile=_cr_make_zip(_cr_mode_handler(None)))
+
+
+def _cfn_events_since_rollback(cfn, stack_name, logical_id):
+ """The statuses one resource recorded after the stack's latest
+ UPDATE_ROLLBACK_IN_PROGRESS, oldest first."""
+ events = cfn.describe_stack_events(StackName=stack_name)["StackEvents"]
+ rollback = next(i for i, e in enumerate(events)
+ if e["LogicalResourceId"] == stack_name
+ and e["ResourceStatus"] == "UPDATE_ROLLBACK_IN_PROGRESS")
+ return [e["ResourceStatus"] for e in reversed(events[:rollback])
+ if e["LogicalResourceId"] == logical_id]
+
+
+def test_cfn_update_rollback_failed_revert_is_retried_by_continue_update_rollback(cfn, lam):
+ """A revert the rollback cannot apply lands the stack in
+ UPDATE_ROLLBACK_FAILED with the resource named as failed to update, and
+ ContinueUpdateRollback retries that update (not a delete) until it
+ succeeds. The custom resource takes the forward update to "new" and
+ refuses the update back to "old"."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ fn = f"cr-revert-fails-{suffix}"
+ stack_name = f"cfn-revert-fails-{suffix}"
+ _cfn_mode_cr_function(lam, fn, fail_mode="old")
+ token = f"arn:aws:lambda:us-east-1:000000000000:function:{fn}"
+
+ def template(mode, with_bad):
+ resources = {"CR": {"Type": "Custom::Tester",
+ "Properties": {"ServiceToken": token, "Mode": mode}}}
+ if with_bad:
+ resources["Bad"] = {**_FAILING_RESOURCE, "DependsOn": "CR"}
+ return json.dumps({"Resources": resources})
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("old", False))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("new", True))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_FAILED", stack.get("StackStatusReason")
+ assert stack["StackStatusReason"] == (
+ "The following resource(s) failed to update: [CR].")
+ statuses = _cfn_events_since_rollback(cfn, stack_name, "CR")
+ assert statuses[:2] == ["UPDATE_IN_PROGRESS", "UPDATE_FAILED"], statuses
+
+ # Still refused: the retry fails the same way.
+ cfn.continue_update_rollback(StackName=stack_name)
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_FAILED", stack.get("StackStatusReason")
+ assert "failed to update: [CR]" in stack["StackStatusReason"]
+
+ # Accepted now: the retry is an update, so the resource is not deleted.
+ _cfn_mode_cr_accept_all(lam, fn)
+ cfn.continue_update_rollback(StackName=stack_name)
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ statuses = _cfn_events_since_rollback(cfn, stack_name, "CR")
+ assert statuses == ["UPDATE_IN_PROGRESS", "UPDATE_COMPLETE"], statuses
+ resources = cfn.describe_stack_resources(StackName=stack_name)["StackResources"]
+ assert [r["LogicalResourceId"] for r in resources] == ["CR"]
+ finally:
+ try:
+ _cfn_mode_cr_accept_all(lam, fn)
+ except ClientError:
+ pass
+ _delete_cfn_test_stack(cfn, stack_name)
+ try:
+ lam.delete_function(FunctionName=fn)
+ except ClientError:
+ pass
+
+
+def test_cfn_update_rollback_failed_revert_can_be_skipped(cfn, lam):
+ """ResourcesToSkip accepts a resource whose revert failed: it keeps the
+ state the update left (an UPDATE_COMPLETE event, no delete) and the stack
+ reaches UPDATE_ROLLBACK_COMPLETE."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ fn = f"cr-revert-skip-{suffix}"
+ stack_name = f"cfn-revert-skip-{suffix}"
+ _cfn_mode_cr_function(lam, fn, fail_mode="old")
+ token = f"arn:aws:lambda:us-east-1:000000000000:function:{fn}"
+ base = {"Resources": {"CR": {"Type": "Custom::Tester",
+ "Properties": {"ServiceToken": token, "Mode": "old"}}}}
+ updated = json.loads(json.dumps(base))
+ updated["Resources"]["CR"]["Properties"]["Mode"] = "new"
+ updated["Resources"]["Bad"] = {**_FAILING_RESOURCE, "DependsOn": "CR"}
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(base))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(updated))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_ROLLBACK_FAILED"
+
+ cfn.continue_update_rollback(StackName=stack_name, ResourcesToSkip=["CR"])
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ assert _cfn_events_since_rollback(cfn, stack_name, "CR") == ["UPDATE_COMPLETE"]
+ finally:
+ try:
+ _cfn_mode_cr_accept_all(lam, fn)
+ except ClientError:
+ pass
+ _delete_cfn_test_stack(cfn, stack_name)
+ try:
+ lam.delete_function(FunctionName=fn)
+ except ClientError:
+ pass
+
+
+def test_cfn_update_rollback_reverts_the_resource_whose_update_failed(cfn, lam):
+ """The resource whose update fails the stack may have changed state before
+ it failed, so the rollback sends it the update back to its previous
+ properties too. The custom resource refuses the update to "new"; the
+ rollback's update back to "old" is accepted."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ fn = f"cr-fwd-fails-{suffix}"
+ stack_name = f"cfn-fwd-fails-{suffix}"
+ _cfn_mode_cr_function(lam, fn, fail_mode="new")
+ token = f"arn:aws:lambda:us-east-1:000000000000:function:{fn}"
+
+ def template(mode):
+ return json.dumps({"Resources": {"CR": {
+ "Type": "Custom::Tester", "Properties": {"ServiceToken": token, "Mode": mode}}}})
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("old"))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("new"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ assert _cfn_events_since_rollback(cfn, stack_name, "CR") == [
+ "UPDATE_IN_PROGRESS", "UPDATE_COMPLETE"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ try:
+ lam.delete_function(FunctionName=fn)
+ except ClientError:
+ pass
+
+
+def test_cfn_update_rollback_does_not_resend_a_refused_resource_update(cfn):
+ """A resource type's own handler that refused the update changed nothing,
+ so the rollback records it complete without calling it again. Measured on
+ AWS 2026-09-21: a GraphQL API whose Visibility change the handler refuses
+ ("can only be set when creating a GraphQL API") gets a lone
+ UPDATE_COMPLETE in the rollback, and so did a scaling policy refused with
+ AlreadyExists. Calling the handler again would only be refused the other
+ way round and fail the rollback."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-rb-refused-{uid}"
+ oidc = {"Issuer": "https://issuer.example.com", "ClientId": "c1"}
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_appsync_members_template(
+ f"refused_{uid}", {}, oidc))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_appsync_members_template(
+ f"refused_{uid}", {"Visibility": "PRIVATE"}, oidc))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ assert _cfn_events_since_rollback(cfn, stack_name, "Api") == ["UPDATE_COMPLETE"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
diff --git a/tests/test_ec2.py b/tests/test_ec2.py
index 83793083..f8422dac 100644
--- a/tests/test_ec2.py
+++ b/tests/test_ec2.py
@@ -1379,6 +1379,42 @@ def test_ec2_modify_vpc_attribute(ec2):
ec2.modify_vpc_attribute(VpcId=vpc_id, EnableDnsHostnames={"Value": True})
ec2.delete_vpc(VpcId=vpc_id)
+
+def test_ec2_subnet_dns_and_ipv6_attributes_read_back(ec2):
+ """DescribeSubnets answers PrivateDnsNameOptionsOnLaunch, EnableDns64,
+ Ipv6Native and AssignIpv6AddressOnCreation on AWS (false and "ip-name"
+ for a subnet created without them), and ModifySubnetAttribute changes the
+ DNS name options one member at a time. None of the four was answered or
+ stored."""
+ vpc_id = subnet_id = None
+ try:
+ vpc_id = ec2.create_vpc(CidrBlock="10.61.0.0/16")["Vpc"]["VpcId"]
+ subnet_id = ec2.create_subnet(VpcId=vpc_id, CidrBlock="10.61.1.0/24")["Subnet"]["SubnetId"]
+
+ def attributes():
+ subnet = ec2.describe_subnets(SubnetIds=[subnet_id])["Subnets"][0]
+ return {key: subnet.get(key) for key in (
+ "PrivateDnsNameOptionsOnLaunch", "EnableDns64", "Ipv6Native",
+ "AssignIpv6AddressOnCreation")}
+
+ assert attributes() == {
+ "PrivateDnsNameOptionsOnLaunch": {
+ "HostnameType": "ip-name", "EnableResourceNameDnsARecord": False,
+ "EnableResourceNameDnsAAAARecord": False},
+ "EnableDns64": False, "Ipv6Native": False, "AssignIpv6AddressOnCreation": False}
+ ec2.modify_subnet_attribute(SubnetId=subnet_id, PrivateDnsHostnameTypeOnLaunch="resource-name")
+ ec2.modify_subnet_attribute(SubnetId=subnet_id,
+ EnableResourceNameDnsARecordOnLaunch={"Value": True})
+ assert attributes()["PrivateDnsNameOptionsOnLaunch"] == {
+ "HostnameType": "resource-name", "EnableResourceNameDnsARecord": True,
+ "EnableResourceNameDnsAAAARecord": False}
+ finally:
+ if subnet_id:
+ ec2.delete_subnet(SubnetId=subnet_id)
+ if vpc_id:
+ ec2.delete_vpc(VpcId=vpc_id)
+
+
def test_ec2_modify_subnet_attribute(ec2):
vpc_id = ec2.create_vpc(CidrBlock="10.11.0.0/16")["Vpc"]["VpcId"]
subnet_id = ec2.create_subnet(VpcId=vpc_id, CidrBlock="10.11.1.0/24")["Subnet"]["SubnetId"]
@@ -2596,6 +2632,48 @@ def test_ec2_launch_template_crud(ec2):
assert len(desc3["LaunchTemplates"]) == 0
+def test_ec2_launch_template_versions_newest_first(ec2):
+ """DescribeLaunchTemplateVersions lists a template's versions newest
+ first on AWS (measured 2026-09-21: 4, 3, 2, 1 after three new versions);
+ the emulator answered them oldest first."""
+ name = f"qa-lt-order-{_uuid_mod.uuid4().hex[:8]}"
+ lt_id = ec2.create_launch_template(
+ LaunchTemplateName=name, LaunchTemplateData={"InstanceType": "t3.micro"},
+ )["LaunchTemplate"]["LaunchTemplateId"]
+ try:
+ for instance_type in ("t3.small", "t3.medium"):
+ ec2.create_launch_template_version(
+ LaunchTemplateId=lt_id, LaunchTemplateData={"InstanceType": instance_type})
+ versions = ec2.describe_launch_template_versions(
+ LaunchTemplateId=lt_id)["LaunchTemplateVersions"]
+ assert [v["VersionNumber"] for v in versions] == [3, 2, 1]
+ finally:
+ ec2.delete_launch_template(LaunchTemplateId=lt_id)
+
+
+def test_ec2_launch_template_tags_read_back(ec2):
+ """A launch template's tags are the TagSpecifications entry for
+ "launch-template". CreateLaunchTemplate and DescribeLaunchTemplates
+ rendered them under <tags>, where the EC2 model reads <tagSet>, so botocore
+ dropped them and no launch template ever read back a tag."""
+ name = f"qa-lt-tags-{_uuid_mod.uuid4().hex[:8]}"
+ resp = ec2.create_launch_template(
+ LaunchTemplateName=name,
+ LaunchTemplateData={"InstanceType": "t3.micro", "ImageId": "ami-12345678"},
+ TagSpecifications=[{"ResourceType": "launch-template",
+ "Tags": [{"Key": "team", "Value": "qa"}]}],
+ )
+ lt_id = resp["LaunchTemplate"]["LaunchTemplateId"]
+ try:
+ assert resp["LaunchTemplate"]["Tags"] == [{"Key": "team", "Value": "qa"}]
+ ec2.create_tags(Resources=[lt_id], Tags=[{"Key": "added", "Value": "later"}])
+ described = ec2.describe_launch_templates(LaunchTemplateIds=[lt_id])["LaunchTemplates"][0]
+ assert sorted((t["Key"], t["Value"]) for t in described["Tags"]) == [
+ ("added", "later"), ("team", "qa")]
+ finally:
+ ec2.delete_launch_template(LaunchTemplateId=lt_id)
+
+
def test_ec2_launch_template_duplicate_name(ec2):
"""Creating a template with a duplicate name should fail."""
ec2.create_launch_template(