Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
Prerelease/fixes (#1823)
Nahuel Nucera6f942173db32
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 69b6bbc0..83fb8cec 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,11 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]-### Fixed--- **Lambda — `ReservedConcurrentExecutions=0` disables the function** — a zero reservation was treated as unset, so the function ran unbounded instead of throttling every invoke with `TooManyRequestsException`. Zero now throttles across all executors, the Docker pool, and SQS event source mappings.### Added+- **CloudFront — public keys and key groups** — `CreatePublicKey`, `GetPublicKey`, `GetPublicKeyConfig`, `UpdatePublicKey`, `DeletePublicKey`, `ListPublicKeys`, `CreateKeyGroup`, `GetKeyGroup`, `GetKeyGroupConfig`, `UpdateKeyGroup`, `DeleteKeyGroup`, `ListKeyGroups`, so `aws_cloudfront_public_key` / `aws_cloudfront_key_group` (and Upbound's Terraform-based `provider-aws-cloudfront`) apply instead of hitting `NoSuchResource` on every create. Key groups validate their `Items` against real public keys, `DeletePublicKey` refuses a key still referenced by a key group, and `DeleteKeyGroup` refuses a group still referenced by a distribution's trusted key groups — both ETag/`If-Match` optimistic concurrency like the other CloudFront policy families. Contributed by @fabio-andre-rodrigues.- **Step Functions — execution history pagination** — `GetExecutionHistory` accepts `nextToken` and returns successive pages in forward or reverse order, with a token only while more events remain. `includeExecutionData=false` omits input and output payloads from returned history events.- **CloudFront — public keys and key groups** — `CreatePublicKey`, `GetPublicKey`, `GetPublicKeyConfig`, `UpdatePublicKey`, `DeletePublicKey`, `ListPublicKeys`, `CreateKeyGroup`, `GetKeyGroup`, `GetKeyGroupConfig`, `UpdateKeyGroup`, `DeleteKeyGroup`, `ListKeyGroups`, so `aws_cloudfront_public_key` / `aws_cloudfront_key_group` (and Upbound's Terraform-based `provider-aws-cloudfront`) apply instead of hitting `NoSuchResource` on every create. Key groups validate their `Items` against real public keys, `DeletePublicKey` refuses a key still referenced by a key group, and `DeleteKeyGroup` refuses a group still referenced by a distribution's trusted key groups — both ETag/`If-Match` optimistic concurrency like the other CloudFront policy families.- **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.@@ -27,6 +25,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Fixed+- **Lambda — `ReservedConcurrentExecutions=0` disables the function** — a zero reservation was treated as unset, so the function ran unbounded instead of throttling every invoke with `TooManyRequestsException`. Zero now throttles across all executors, the Docker pool, and SQS event source mappings. Contributed by @AdrianAcala.- **Step Functions — Secrets Manager binary values** — `aws-sdk:secretsmanager:getSecretValue`, `createSecret`, and `putSecretValue` now pass literal UTF-8 text in `SecretBinary`, matching the AWS SDK integration rather than exposing the HTTP API's base64 representation. Direct Secrets Manager API/SDK calls keep their existing binary encoding.- **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.@@ -40,7 +39,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Added-- **Organizations — member accounts, service control policies and attachments** — `CreateAccount`, `DescribeCreateAccountStatus`, `MoveAccount`, `CloseAccount`, `CreatePolicy`, `DescribePolicy`, `UpdatePolicy`, `DeletePolicy`, `ListPolicies`, `AttachPolicy`, `DetachPolicy`, `ListPoliciesForTarget`, `ListTargetsForPolicy`, `EnablePolicyType` and `DisablePolicyType`, so `aws_organizations_account`, `aws_organizations_policy` and `aws_organizations_policy_attachment` apply. `CreateAccount` answers with a `CreateAccountStatus` whose id the provider reads back through `DescribeCreateAccountStatus`, as on AWS. A root carries `SERVICE_CONTROL_POLICY` enabled and the AWS-managed `p-FullAWSAccess`, attaching a policy whose type the root has disabled is `PolicyTypeNotEnabledException`, and deleting an attached policy is `PolicyInUseException`. Requested by @rv0lt.+- **Organizations — member accounts, service control policies and attachments** — `CreateAccount`, `DescribeCreateAccountStatus`, `MoveAccount`, `CloseAccount`, `CreatePolicy`, `DescribePolicy`, `UpdatePolicy`, `DeletePolicy`, `ListPolicies`, `AttachPolicy`, `DetachPolicy`, `ListPoliciesForTarget`, `ListTargetsForPolicy`, `EnablePolicyType` and `DisablePolicyType`, so `aws_organizations_account`, `aws_organizations_policy` and `aws_organizations_policy_attachment` apply. `CreateAccount` answers with a `CreateAccountStatus` whose id the provider reads back through `DescribeCreateAccountStatus`, as on AWS. A root carries `SERVICE_CONTROL_POLICY` enabled and the AWS-managed `p-FullAWSAccess`, attaching a policy whose type the root has disabled is `PolicyTypeNotEnabledException`, and deleting an attached policy is `PolicyInUseException`. Reported by @rv0lt.- **SNS — direct-to-phone publishes can be read back** — a `Publish` with a `PhoneNumber` and no `TopicArn` is recorded and served at `GET /_ministack/sns/sms-messages`, filterable by `account`, `region` and `phoneNumber`. Contributed by @himangshuj.- **Lambda MicroVMs — image lifecycle** — `ListMicrovmImages`, `GetMicrovmImage`, `GetMicrovmImageVersion` and `UpdateMicrovmImage`. Contributed by @edersonbrilhante.diff --git a/ministack/services/autoscaling.py b/ministack/services/autoscaling.pyindex 11abe80a..9715f13c 100644--- a/ministack/services/autoscaling.py+++ b/ministack/services/autoscaling.py@@ -516,16 +516,12 @@ 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).+# Typed per the autoscaling service-2.json shapes; every other leaf is a string._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")@@ -546,9 +542,7 @@ def _policy_typed(value, key=None):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": ...}]}``."""+ """The query members under ``prefix`` as nested dicts, ``.member.N`` levels as lists."""tree = {}for key in params:if not key.startswith(prefix + "."):@@ -579,12 +573,7 @@ def _parse_nested(params, prefix):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."""+ """A policy record with only the members its type has, from API members or template properties."""policy_type = fields.get("PolicyType") or "SimpleScaling"record = {"PolicyARN": arn,@@ -607,8 +596,7 @@ def _policy_record(asg_name, policy_name, arn, fields):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).+ # "Defaults to HonorMaxCapacity if not specified" (service-2.json).predictive.setdefault("MaxCapacityBreachBehavior", "HonorMaxCapacity")return record@@ -630,8 +618,6 @@ def _put_scaling_policy(p):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] = recordreturn _xml(200, "PutScalingPolicyResponse",@@ -639,8 +625,7 @@ def _put_scaling_policy(p):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."""+ """A stored member as query-protocol XML."""if isinstance(value, dict):return "".join(f"<{k}>{_member_xml(v)}</{k}>" for k, v in value.items())if isinstance(value, list):@@ -656,10 +641,6 @@ def _describe_policies(p):for key, pol in _policies.items():if asg_name and pol["AutoScalingGroupName"] != asg_name:continue- # 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", [])@@ -736,11 +717,7 @@ def _record_lifecycle_heartbeat(p):# ---------------------------------------------------------------------------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."""+ """A scheduled action record; an omitted capacity is -1 and left out of the response."""def capacity(member):value = fields.get(member)return -1 if value in (None, "") else int(value)@@ -778,11 +755,6 @@ 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>"@@ -792,8 +764,7 @@ def _describe_scheduled_actions(p):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).+ # StartTime is also answered as the deprecated Time.if sa.get("StartTime"):members += (f"<StartTime>{escape(sa['StartTime'])}</StartTime>"f"<Time>{escape(sa['StartTime'])}</Time>")diff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.pyindex 588a43fe..c0b17aa2 100644--- a/ministack/services/cloudformation/changesets.py+++ b/ministack/services/cloudformation/changesets.py@@ -729,8 +729,6 @@ 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.pyindex 76a8b744..5bea6a9e 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -890,6 +890,11 @@ def _update_resource(resource_type: str, physical_id: str, old_props: dict,# Tags# ---------------------------------------------------------------------------+def _cfn_bool(value) -> bool:+ """A template boolean, which YAML can carry as the string "false"."""+ return str(value).lower() == "true"++def _tag_map(tags) -> dict:"""The ``{Key: Value}`` view of a CloudFormation ``Tags`` property; a map(the shape SSM and API Gateway v2 use) passes through."""@@ -2475,11 +2480,7 @@ def _iam_policy_update(physical_id, old_props, new_props, stack_name, logical_idold_name = old_props.get("PolicyName") or physical_idnew_name = new_props.get("PolicyName") or physical_id- # Every name the new template lists is resolved before anything comes off,- # and the new document is validated here too: an in place change is not- # undone by the rollback of an update, so a put that failed after the- # drops below (on a missing entity or a malformed document alike) would- # leave the entity holding nothing.+ # Validated before anything comes off: the rollback does not resend a failed update._iam_policy_require_entities(new_props)_iam_policy_require_valid_document(new_props)@@ -2664,9 +2665,7 @@ 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."""+ """Reconcile the per-ARN tag map; tags from TagResource stay."""if not old_props.get("Tags") and not new_props.get("Tags"):return_reconcile_tag_map(_appconfig._tags.setdefault(arn, {}), old_props, new_props)@@ -2691,14 +2690,7 @@ def _appconfig_application_create(logical_id, props, stack_name):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)."""+ """Every property is No interruption (aws-resource-appconfig-application)."""app = _appconfig._applications.get(physical_id)if app is None:return _appconfig_application_create(@@ -2717,6 +2709,14 @@ def _appconfig_application_delete(physical_id, props):# --- AppConfig Environment ---+def _appconfig_environment_fields(props):+ return {+ "Description": props.get("Description", ""),+ "Monitors": props.get("Monitors", []),+ "DeletionProtectionCheck": props.get("DeletionProtectionCheck", "ACCOUNT_DEFAULT"),+ }++def _appconfig_environment_create(logical_id, props, stack_name):app_id = props.get("ApplicationId")if not app_id:@@ -2727,10 +2727,8 @@ def _appconfig_environment_create(logical_id, props, stack_name):"ApplicationId": app_id,"Id": env_id,"Name": name,- "Description": props.get("Description", ""),"State": "READY_FOR_DEPLOYMENT",- "Monitors": props.get("Monitors", []),- "DeletionProtectionCheck": props.get("DeletionProtectionCheck", "ACCOUNT_DEFAULT"),+ **_appconfig_environment_fields(props),}cfn_tags = props.get("Tags") or []if cfn_tags:@@ -2744,17 +2742,9 @@ def _appconfig_environment_create(logical_id, props, stack_name):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."""+ """ApplicationId replaces; the rest is in place (aws-resource-appconfig-environment)."""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.+ # Looked up under the old ApplicationId, so a move still deletes the predecessor.env = _appconfig._environments.get(f"{old_props.get('ApplicationId', '')}/{physical_id}")replaced = _rename_replacement(@@ -2766,10 +2756,7 @@ def _appconfig_environment_update(physical_id, old_props, new_props, stack_name,return replacedif 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")+ env.update(_appconfig_environment_fields(new_props))_appconfig_reconcile_tags(_appconfig._env_arn(app_id, physical_id), old_props, new_props)return physical_id, {"EnvironmentId": physical_id}@@ -2783,6 +2770,16 @@ def _appconfig_environment_delete(physical_id, props):# --- AppConfig ConfigurationProfile ---+def _appconfig_configuration_profile_fields(props):+ return {+ "Description": props.get("Description", ""),+ "RetrievalRoleArn": props.get("RetrievalRoleArn", ""),+ "Validators": props.get("Validators", []),+ "KmsKeyIdentifier": props.get("KmsKeyIdentifier", ""),+ "DeletionProtectionCheck": props.get("DeletionProtectionCheck", "ACCOUNT_DEFAULT"),+ }++def _appconfig_configuration_profile_create(logical_id, props, stack_name):app_id = props.get("ApplicationId")if not app_id:@@ -2793,13 +2790,9 @@ def _appconfig_configuration_profile_create(logical_id, props, stack_name):"ApplicationId": app_id,"Id": profile_id,"Name": name,- "Description": props.get("Description", ""),"LocationUri": props.get("LocationUri", "hosted"),- "RetrievalRoleArn": props.get("RetrievalRoleArn", ""),- "Validators": props.get("Validators", []),"Type": props.get("Type", "AWS.Freeform"),- "KmsKeyIdentifier": props.get("KmsKeyIdentifier", ""),- "DeletionProtectionCheck": props.get("DeletionProtectionCheck", "ACCOUNT_DEFAULT"),+ **_appconfig_configuration_profile_fields(props),}cfn_tags = props.get("Tags") or []if cfn_tags:@@ -2818,16 +2811,9 @@ 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)."""+ """ApplicationId, LocationUri and Type replace; the rest is in place (aws-resource-appconfig-configurationprofile)."""app_id = new_props.get("ApplicationId", "")- # The old key, for the same reason the environment handler uses it.+ # Looked up under the old ApplicationId, so a move still deletes the predecessor.profile = _appconfig._config_profiles.get(f"{old_props.get('ApplicationId', '')}/{physical_id}")replaced = _rename_replacement(@@ -2844,12 +2830,7 @@ def _appconfig_configuration_profile_update(physical_id, old_props, new_props,return replacedif 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")+ profile.update(_appconfig_configuration_profile_fields(new_props))_appconfig_reconcile_tags(_appconfig._profile_arn(app_id, physical_id), old_props, new_props)return physical_id, {@@ -2915,17 +2896,23 @@ def _appconfig_hosted_version_delete(physical_id, props):# --- AppConfig DeploymentStrategy ---+def _appconfig_deployment_strategy_fields(props):+ return {+ "Description": props.get("Description", ""),+ "DeploymentDurationInMinutes": props.get("DeploymentDurationInMinutes", 0),+ "GrowthType": props.get("GrowthType", "LINEAR"),+ "GrowthFactor": props.get("GrowthFactor", 100.0),+ "FinalBakeTimeInMinutes": props.get("FinalBakeTimeInMinutes", 0),+ }++def _appconfig_deployment_strategy_create(logical_id, props, stack_name):name = props.get("Name") or _physical_name(stack_name, logical_id, max_len=64)strategy_id = _appconfig._gen_id()_appconfig._deployment_strategies[strategy_id] = {"Id": strategy_id,"Name": name,- "Description": props.get("Description", ""),- "DeploymentDurationInMinutes": props.get("DeploymentDurationInMinutes", 0),- "GrowthType": props.get("GrowthType", "LINEAR"),- "GrowthFactor": props.get("GrowthFactor", 100.0),- "FinalBakeTimeInMinutes": props.get("FinalBakeTimeInMinutes", 0),+ **_appconfig_deployment_strategy_fields(props),"ReplicateTo": props.get("ReplicateTo", "NONE"),}cfn_tags = props.get("Tags") or []@@ -2940,13 +2927,7 @@ def _appconfig_deployment_strategy_create(logical_id, props, stack_name):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."""+ """Name and ReplicateTo replace; the rest is in place (aws-resource-appconfig-deploymentstrategy)."""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)@@ -2959,12 +2940,7 @@ def _appconfig_deployment_strategy_update(physical_id, old_props, new_props,)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)+ strategy.update(_appconfig_deployment_strategy_fields(new_props))_appconfig_reconcile_tags(_appconfig._strategy_arn(physical_id), old_props, new_props)return physical_id, {"Id": physical_id}@@ -5612,8 +5588,7 @@ 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.+# Absent from the API unless the template sets them._APPSYNC_API_OPTIONAL = ("AdditionalAuthenticationProviders", "EnhancedMetricsConfig","LambdaAuthorizerConfig", "LogConfig", "MergedApiExecutionRoleArn",@@ -5622,16 +5597,10 @@ _APPSYNC_API_OPTIONAL = (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- [{}]."""+ """The template's properties as the API's camelCase members, scalars defaulted."""members = {"authenticationType": props.get("AuthenticationType", "API_KEY"),- "xrayEnabled": str(props.get("XrayEnabled", False)).lower() == "true",+ "xrayEnabled": _cfn_bool(props.get("XrayEnabled", False)),"apiType": props.get("ApiType", "GRAPHQL"),"visibility": props.get("Visibility", "GLOBAL"),"introspectionConfig": props.get("IntrospectionConfig", "ENABLED"),@@ -5643,19 +5612,16 @@ def _appsync_api_members(props):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.+ # The caller's own keys, not converted.if props.get("EnvironmentVariables"):members["environmentVariables"] = dict(props["EnvironmentVariables"])return membersdef _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)."""+ """The template and stack tags, without the aws: ones AppSync does not list."""return {"Tags": [t for t in (props.get("Tags") or [])if isinstance(t, dict) and not str(t.get("Key", "")).startswith("aws:")]}@@ -5663,8 +5629,7 @@ def _appsync_api_tags(props):def _appsync_api_create(logical_id, props, stack_name):import time as _timename = props.get("Name") or _physical_name(stack_name, logical_id)- # The id shape CreateGraphqlApi mints; eight characters made an ARN that- # botocore refuses as too short for ListTagsForResource.+ # CreateGraphqlApi's 26-character id shape.api_id = new_uuid().replace("-", "")[:26]arn = f"arn:aws:appsync:{get_region()}:{get_account_id()}:apis/{api_id}"now = _time.time()@@ -5689,32 +5654,19 @@ def _appsync_api_create(logical_id, props, stack_name):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+ """Every property is No interruption (aws-resource-appsync-graphqlapi)."""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)+ # visibility "cannot be changed once the API has been created" (appsync service-2.json).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.+ # UpdateGraphqlApi has no apiType member.members.pop("apiType")for prop in (*_APPSYNC_API_OPTIONAL, "EnvironmentVariables"):api.pop(prop[:1].lower() + prop[1:], None)@@ -5723,7 +5675,7 @@ def _appsync_api_update(physical_id, old_props, new_props, stack_name, logical_i_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()+ api["lastUpdatedAt"] = time.time()return physical_id, {"ApiId": physical_id,"Arn": api["arn"],@@ -5856,9 +5808,6 @@ def _appsync_apikey_create(logical_id, props, stack_name):import timekey = {"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()),@@ -5870,14 +5819,7 @@ def _appsync_apikey_create(logical_id, props, stack_name):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+ """ApiId replaces; Description and Expires are in place (aws-resource-appsync-apikey)."""api_id = new_props.get("ApiId", "")old_api_id = old_props.get("ApiId", "")key = _appsync._api_keys.get(old_api_id, {}).get(physical_id)@@ -6934,14 +6876,7 @@ 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)."""+ """The template's tags into the EC2 tag store; tags from CreateTags stay."""tags = list(_ec2._tags.get(physical_id) or [])_reconcile_tag_list(tags, old_props or {}, props)if tags:@@ -6951,18 +6886,10 @@ def _ec2_apply_tags(physical_id, props, old_props=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)."""+ """The DNS attributes onto the record; on update a removed one goes back to its default."""for prop in ("EnableDnsSupport", "EnableDnsHostnames"):if prop in props:- value = props[prop]- vpc[prop] = value if isinstance(value, bool) else str(value).lower() == "true"+ vpc[prop] = _cfn_bool(props[prop])elif reset_absent:vpc.pop(prop, None)@@ -7011,32 +6938,19 @@ def _ec2_vpc_create(logical_id, props, stack_name):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.+# Replacement beside CidrBlock (aws-resource-ec2-vpc); not on the record._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.- """+ """Update a VPC in place (aws-resource-ec2-vpc)."""vpc = _ec2._vpcs.get(physical_id)tenancy = new_props.get("InstanceTenancy", "default")+ # "Updating InstanceTenancy from default to dedicated requires replacement."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,@@ -7058,10 +6972,7 @@ def _ec2_vpc_update(physical_id, old_props, new_props, stack_name, logical_id=Nodef _ec2_vpc_delete(physical_id, props):- # 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.+ # DeleteVpc takes the default children and refuses with DependencyViolation.children = [child_idfor store in (_ec2._security_groups, _ec2._route_tables, _ec2._network_acls)@@ -7145,8 +7056,7 @@ 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.+# Replacement beside VpcId, CidrBlock and the zone (aws-resource-ec2-subnet); not on the record._EC2_SUBNET_CREATE_ONLY = ("Ipv4IpamPoolId", "Ipv4NetmaskLength", "Ipv6IpamPoolId", "Ipv6Native","Ipv6NetmaskLength", "OutpostArn",@@ -7154,8 +7064,7 @@ _EC2_SUBNET_CREATE_ONLY = (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."""+ """The zone name from AvailabilityZone or AvailabilityZoneId."""if props.get("AvailabilityZone"):return props["AvailabilityZone"]if props.get("AvailabilityZoneId"):@@ -7166,17 +7075,13 @@ def _ec2_subnet_zone(props):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 (+ """The DNS attributes the template sets onto the record; a removed one stays."""+ if _cfn_bool(props.get("EnableDns64", False)) 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"+ subnet["EnableDns64"] = _cfn_bool(props["EnableDns64"])options = props.get("PrivateDnsNameOptionsOnLaunch")if isinstance(options, dict):current = dict(_ec2._subnet_dns_name_options(subnet))@@ -7184,7 +7089,7 @@ def _ec2_subnet_attributes(subnet, props):current["HostnameType"] = options["HostnameType"]for member in ("EnableResourceNameDnsARecord", "EnableResourceNameDnsAAAARecord"):if member in options:- current[member] = str(options[member]).lower() == "true"+ current[member] = _cfn_bool(options[member])subnet["PrivateDnsNameOptionsOnLaunch"] = current@@ -7202,7 +7107,7 @@ def _ec2_subnet_create(logical_id, props, stack_name):"State": "available","AvailableIpAddressCount": 251,"DefaultForAz": False,- "MapPublicIpOnLaunch": _ec2_subnet_public_ip(props),+ "MapPublicIpOnLaunch": _cfn_bool(props.get("MapPublicIpOnLaunch", False)),"OwnerId": get_account_id(),}try:@@ -7215,17 +7120,7 @@ def _ec2_subnet_create(logical_id, props, stack_name):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."""+ """Update a subnet in place (aws-resource-ec2-subnet)."""subnet = _ec2._subnets.get(physical_id)key = (new_props.get("VpcId", ""),new_props.get("CidrBlock", "10.0.1.0/24"),@@ -7241,27 +7136,14 @@ def _ec2_subnet_update(physical_id, old_props, new_props, stack_name, logical_id)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)+ subnet["MapPublicIpOnLaunch"] = _cfn_bool(new_props["MapPublicIpOnLaunch"])_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)@@ -7288,11 +7170,7 @@ def _ec2_sg_create(logical_id, props, stack_name):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."""+ """A template's ingress or egress rules in the EC2 store's shape."""permissions = []for rule in (rules or []):if not isinstance(rule, dict):@@ -7330,57 +7208,27 @@ def _ec2_sg_permissions(rules):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)."""+ """The template's egress rules, or allow-all when it declares none."""return _ec2_sg_permissions(rules) or [{"IpProtocol": "-1", "IpRanges": [{"CidrIp": "0.0.0.0/0"}],"Ipv6Ranges": [], "PrefixListIds": [], "UserIdGroupPairs": []},]-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."""+ """Swap the template's old rules for its new ones; rules authorized outside it stay."""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 key(perm):+ return json.dumps(_ec2._strip_descriptions(perm), sort_keys=True)++ keys = {key(p) for p in old_perms} | {key(p) for p in new_perms}+ store[:] = [p for p in store if key(p) not in keys] + new_permsdef _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."""+ """Update a security group in place (aws-resource-ec2-securitygroup)."""_ec2._ensure_defaults_initialized()group = _ec2._security_groups.get(physical_id)name = new_props.get("GroupName", f"{stack_name}-{logical_id or physical_id}")@@ -7399,9 +7247,7 @@ def _ec2_sg_update(physical_id, old_props, new_props, stack_name, logical_id=Non_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.+ # A dropped egress declaration does not bring allow-all back._ec2_sg_reconcile(group.setdefault("IpPermissionsEgress", []),_ec2_sg_egress_permissions(old_props.get("SecurityGroupEgress")),_ec2_sg_permissions(new_props.get("SecurityGroupEgress")))@@ -7427,14 +7273,7 @@ def _ec2_igw_create(logical_id, props, stack_name):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."""+ """Tags, the type's only property, is No interruption (aws-resource-ec2-internetgateway)."""gateway = _ec2._internet_gateways.get(physical_id)if gateway is None:return _ec2_igw_create(logical_id or physical_id, new_props, stack_name)@@ -7486,13 +7325,7 @@ def _ec2_rtb_create(logical_id, props, stack_name):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."""+ """Update a route table in place (aws-resource-ec2-routetable)."""table = _ec2._route_tables.get(physical_id)replaced = _rename_replacement(physical_id, old_props, new_props, stack_name, logical_id,@@ -7511,18 +7344,14 @@ def _ec2_rtb_delete(physical_id, props):_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.+# No interruption (aws-resource-ec2-route)._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.+# Replacement, each naming its own route (aws-resource-ec2-route)._EC2_ROUTE_DESTINATIONS = ("DestinationCidrBlock", "DestinationIpv6CidrBlock", "DestinationPrefixListId",)@@ -7547,8 +7376,7 @@ def _ec2_route_record(props, dest):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."""+ """Put the route for ``dest``, replacing any route already at that destination."""prop, value = destrtb["Routes"] = [r for r in rtb["Routes"] if r.get(prop) != value@@ -7560,26 +7388,13 @@ def _ec2_route_create(logical_id, props, stack_name):dest = _ec2_route_destination(props)rtb = _ec2._route_tables.get(rtb_id)if rtb:- # 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."""+ """A target change is in place; a table or destination change replaces (aws-resource-ec2-route)."""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@@ -7639,9 +7454,6 @@ def _ecs_cluster_create(logical_id, props, stack_name):"runningTasksCount": 0,"pendingTasksCount": 0,"activeServicesCount": 0,- # 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": _pascal_to_camel(@@ -7649,7 +7461,6 @@ def _ecs_cluster_create(logical_id, props, stack_name):"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}@@ -7802,33 +7613,31 @@ def _ecs_service_delete(physical_id, props):# --- EC2 Launch Template provisioners ----def _ec2_launch_template_create(logical_id, props, stack_name):- name = props.get("LaunchTemplateName", _physical_name(stack_name, logical_id))- lt_data = props.get("LaunchTemplateData", {})- lt_id = _ec2._new_lt_id()- now = __import__("time").strftime("%Y-%m-%dT%H:%M:%SZ", __import__("time").gmtime())- version = {+def _ec2_launch_template_version(lt_id, name, number, props, default):+ return {"LaunchTemplateId": lt_id,"LaunchTemplateName": name,- "VersionNumber": 1,+ "VersionNumber": number,"VersionDescription": props.get("VersionDescription", ""),- "DefaultVersion": True,- "CreateTime": now,- "LaunchTemplateData": lt_data,+ "DefaultVersion": default,+ "CreateTime": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),+ "LaunchTemplateData": props.get("LaunchTemplateData", {}),}+++def _ec2_launch_template_create(logical_id, props, stack_name):+ name = props.get("LaunchTemplateName", _physical_name(stack_name, logical_id))+ lt_id = _ec2._new_lt_id()+ version = _ec2_launch_template_version(lt_id, name, 1, props, True)lt = {"LaunchTemplateId": lt_id,"LaunchTemplateName": name,- "CreateTime": now,+ "CreateTime": version["CreateTime"],"DefaultVersionNumber": 1,"LatestVersionNumber": 1,"Versions": [version],}- # 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.+ # The type has no Tags property; its own tags are the "launch-template" TagSpecifications entry.tags = [{"Key": str(t.get("Key", "")), "Value": str(t.get("Value", ""))}for spec in (props.get("TagSpecifications") or [])@@ -7849,22 +7658,7 @@ 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+ """A change adds a version and leaves the default (aws-resource-ec2-launchtemplate)."""template = _ec2._launch_templates.get(physical_id)name = new_props.get("LaunchTemplateName", _physical_name(stack_name, logical_id or physical_id))@@ -7876,15 +7670,8 @@ def _ec2_launch_template_update(physical_id, old_props, new_props, stack_name,if replaced is not None:return replacedversion_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.setdefault("Versions", []).append(_ec2_launch_template_version(+ physical_id, template["LaunchTemplateName"], version_number, new_props, False))template["LatestVersionNumber"] = version_numberreturn physical_id, {"LaunchTemplateId": physical_id,@@ -9196,7 +8983,7 @@ def _apigw_v2_api_props(props, stack_name, logical_id):return {"name": props.get("Name") or _physical_name(stack_name, logical_id, max_len=128),"routeSelectionExpression": props.get("RouteSelectionExpression", default_rse),- "apiKeySelectionExpression": props.get("ApiKeySelectionExpression", "$request.header.x-api-key"), # sadscan:disable np.twitter.1 - API route expression, not a credential.+ "apiKeySelectionExpression": props.get("ApiKeySelectionExpression", "$request.header.x-api-key"),"disableSchemaValidation": props.get("DisableSchemaValidation", False),"disableExecuteApiEndpoint": props.get("DisableExecuteApiEndpoint", False),"version": props.get("Version", ""),@@ -10121,24 +9908,12 @@ def _asg_create(logical_id, props, stack_name):asg = {"AutoScalingGroupName": name,"AutoScalingGroupARN": arn,- "LaunchConfigurationName": props.get("LaunchConfigurationName", ""),- "LaunchTemplate": {},- "MinSize": int(props.get("MinSize", 0)),- "MaxSize": int(props.get("MaxSize", 0)),- "DesiredCapacity": int(props.get("DesiredCapacity", props.get("MinSize", 0))),- "DefaultCooldown": int(props.get("Cooldown", 300)),- "AvailabilityZones": props.get("AvailabilityZones", [f"{get_region()}a"]),- "HealthCheckType": props.get("HealthCheckType", "EC2"),- "HealthCheckGracePeriod": int(props.get("HealthCheckGracePeriod", 300)),+ **_asg_fields(props),"Instances": [],"CreatedTime": now_iso(),- "VPCZoneIdentifier": ",".join(props.get("VPCZoneIdentifier", [])) if isinstance(props.get("VPCZoneIdentifier"), list) else props.get("VPCZoneIdentifier", ""),- "TerminationPolicies": props.get("TerminationPolicies", ["Default"]),- "NewInstancesProtectedFromScaleIn": props.get("NewInstancesProtectedFromScaleIn", False),"Tags": [],"Status": "",}- asg["LaunchTemplate"] = _asg_launch_template(props.get("LaunchTemplate"))tags = []for t in props.get("Tags", []):tags.append({@@ -10146,7 +9921,7 @@ def _asg_create(logical_id, props, stack_name):"Value": t.get("Value", ""),"ResourceId": name,"ResourceType": "auto-scaling-group",- "PropagateAtLaunch": _asg_propagate_at_launch(t),+ "PropagateAtLaunch": _cfn_bool(t.get("PropagateAtLaunch", False)),})asg["Tags"] = tags_asg._asgs[name] = asg@@ -10154,12 +9929,27 @@ def _asg_create(logical_id, props, stack_name):return name, {"AutoScalingGroupARN": arn, "Arn": arn}+def _asg_fields(props):+ """The group members a template sets, for create and update alike."""+ zone_id = props.get("VPCZoneIdentifier", "")+ return {+ "LaunchConfigurationName": props.get("LaunchConfigurationName", ""),+ "LaunchTemplate": _asg_launch_template(props.get("LaunchTemplate")),+ "MinSize": int(props.get("MinSize", 0)),+ "MaxSize": int(props.get("MaxSize", 0)),+ "DesiredCapacity": int(props.get("DesiredCapacity", props.get("MinSize", 0))),+ "DefaultCooldown": int(props.get("Cooldown", 300)),+ "AvailabilityZones": props.get("AvailabilityZones", [f"{get_region()}a"]),+ "HealthCheckType": props.get("HealthCheckType", "EC2"),+ "HealthCheckGracePeriod": int(props.get("HealthCheckGracePeriod", 300)),+ "VPCZoneIdentifier": ",".join(zone_id) if isinstance(zone_id, list) else zone_id,+ "TerminationPolicies": props.get("TerminationPolicies", ["Default"]),+ "NewInstancesProtectedFromScaleIn": props.get("NewInstancesProtectedFromScaleIn", False),+ }++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)."""+ """The launch template's id and name, whichever of the two the group was given."""if not spec:return {}lt_id = spec.get("LaunchTemplateId", "")@@ -10177,16 +9967,7 @@ def _asg_launch_template(spec):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."""+ """AutoScalingGroupName and InstanceId replace; the rest is in place (aws-resource-autoscaling-autoscalinggroup)."""name = new_props.get("AutoScalingGroupName") or _physical_name(stack_name, logical_id or physical_id, max_len=255)asg = _asg._asgs.get(physical_id)@@ -10198,25 +9979,8 @@ def _asg_update(physical_id, old_props, new_props, stack_name, logical_id=None):)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.+ asg.update(_asg_fields(new_props))+ # Tags from CreateOrUpdateTags stay.tags = _asg._tags.get(physical_id)if tags is None:tags = list(asg.get("Tags") or [])@@ -10230,20 +9994,13 @@ def _asg_update(physical_id, old_props, new_props, stack_name, logical_id=None):if spec is not None:tag["ResourceId"] = physical_idtag["ResourceType"] = "auto-scaling-group"- tag["PropagateAtLaunch"] = _asg_propagate_at_launch(spec)+ tag["PropagateAtLaunch"] = _cfn_bool(spec.get("PropagateAtLaunch", False))asg["Tags"] = tags_asg._tags[physical_id] = tagsarn = 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)@@ -10269,40 +10026,17 @@ 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 = _asg_policy_name(props, stack_name, logical_id)+ policy_name = props.get("PolicyName") or _physical_name(stack_name, logical_id, max_len=255)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}"- # 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."""+ """AutoScalingGroupName replaces; the rest is in place (aws-resource-autoscaling-scalingpolicy)."""asg_name = new_props.get("AutoScalingGroupName", "")current = next((p for p in _asg._policies.values() if p.get("PolicyARN") == physical_id), None)@@ -10313,8 +10047,6 @@ def _asg_policy_update(physical_id, old_props, new_props, stack_name, logical_id)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)@@ -10351,24 +10083,17 @@ 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)."""+ """Ref returns the generated name (aws-resource-autoscaling-scheduledaction)."""asg_name = props.get("AutoScalingGroupName", "")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}"- # 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."""+ """The store key and record, by name in the group or by ARN (the older physical id)."""asg_name = props.get("AutoScalingGroupName", "")for key, action in _asg._scheduled_actions.items():if (action.get("ScheduledActionARN") == physical_id@@ -10380,20 +10105,10 @@ def _asg_scheduled_find(physical_id, props):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."""+ """AutoScalingGroupName replaces; the rest is in place (aws-resource-autoscaling-scheduledaction)."""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.+ # The replacement keeps the generated name, so the predecessor goes explicitly.replaced = _rename_replacement(physical_id, old_props, new_props, stack_name, logical_id,asg_name, current["AutoScalingGroupName"] if current else None,diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.pyindex ec37d8a2..ad060462 100644--- a/ministack/services/cloudformation/stacks.py+++ b/ministack/services/cloudformation/stacks.py@@ -189,9 +189,7 @@ def _resolve_stack_outputs(outputs_defs, conditions, resources, param_values,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."""+ """The reason of a rollback that could not finish: failed reverts, then failed deletes."""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 = []@@ -203,23 +201,15 @@ def _rollback_failure_reason(failed_records: dict) -> str: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."""+ """Whether the resource whose own update failed is sent back too: a provider+ or a child stack may have changed state before failing; a type's handler did not."""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."""+ """The restored record of a resource the rollback updated reports UPDATE_COMPLETE."""if record is not None:record["ResourceStatus"] = "UPDATE_COMPLETE"record["Timestamp"] = now_iso()@@ -227,15 +217,8 @@ def _mark_rolled_back(record):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."""+ """Send an in-place update back to the previous properties through the+ type's update handler; ``record`` takes the attributes it answers."""_add_event(stack_id, stack_name, logical_id, rtype, "UPDATE_IN_PROGRESS",physical_id=physical_id)try:@@ -254,8 +237,6 @@ async def _revert_update(stack_id, stack_name, logical_id, rtype, physical_id,raiseif 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@@ -268,11 +249,8 @@ async def _revert_update(stack_id, stack_name, logical_id, rtype, physical_id,async def _continue_update_rollback_async(stack_name: str, stack_id: str,resources_to_skip):- """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."""+ """ContinueUpdateRollback: retry the failed reverts and deletes; a skipped+ resource is set to UPDATE_COMPLETE and left as it is."""from ministack.services.cloudformation import _stacksstack = _stacks.get(stack_name)if not stack:@@ -378,14 +356,8 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,fail_reason = ""cancelled = Falsereplaced_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.+ # (logical id, type, pid, applied, previous, attrs) of a pre-existing resource that failed.failed_update = None- # The logical id of the resource whose create or update failed, which the- # rollback's reason names.failed_logical_id = Nonestack.pop("_cancel_requested", None)@@ -471,10 +443,9 @@ 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)+ # A custom-named refusal never reaches the handler: nothing to send back.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):@@ -610,7 +581,14 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,old_resources = previous_stack.get("_resources", {})old_template = previous_stack.get("_template", {}) or {}old_defs = old_template.get("Resources", {}) or {}- for logical_id in to_remove:+ # Dependents first, as the stack delete orders it.+ try:+ removal_order = [lid for lid in _topological_sort(+ old_defs, previous_stack.get("_conditions", conditions)) if lid in to_remove]+ except ValueError:+ removal_order = []+ removal_order += [lid for lid in to_remove if lid not in removal_order]+ for logical_id in reversed(removal_order):old_res = old_resources.get(logical_id, {})rtype = old_res.get("ResourceType", "")pid = old_res.get("PhysicalResourceId", "")@@ -669,8 +647,6 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,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}]. ")@@ -688,8 +664,7 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,replaced_ids = {entry[0] for entry in replaced_resources}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.+ # A failed revert is kept for ContinueUpdateRollback.try:await _revert_update(stack_id, stack_name, logical_id, rtype,pid, applied, previous, attrs,@@ -701,11 +676,7 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,"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.+ # In-place changes go back first; what the update created is deleted in cleanup.to_delete = []for logical_id in created_in_this_run:res = provisioned_resources.get(logical_id, {})@@ -715,12 +686,7 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,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.+ # Pre-existing and same identity: sent back with the tags each side was called with.rtype = res.get("ResourceType", "")applied = _with_stack_tags(rtype, res.get("Properties", {}), stack_tags,stack_name, stack_id, logical_id)@@ -736,18 +702,11 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,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.+ # "rolled back to its previous working state ... still deleting any new+ # resources" (view-stack-events): a cleanup delete failure does not fail it.cleanup_phase = bool(is_update and previous_stackand not rollback_failed_records)if cleanup_phase:@@ -832,8 +791,6 @@ 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"],"" if is_update and previous_stack else "Rollback complete",diff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.pyindex 80fd0fa6..8345128b 100644--- a/ministack/services/cloudfront.py+++ b/ministack/services/cloudfront.py@@ -1640,11 +1640,7 @@ _RHP_SPEC = {# ----------------------------------------------------------------------------# PublicKey — used by signed URLs/cookies and as KeyGroup members. Not built-# on the generic policy CRUD helpers above: PublicKey has no Name-uniqueness-# constraint worth enforcing (real AWS dedupes by CallerReference, which-# nothing here reads back), tracks CreatedTime rather than LastModifiedTime,-# and its "in use" check is against KeyGroups, not distributions.+# Public keys# ---------------------------------------------------------------------------@@ -1735,8 +1731,9 @@ def _update_public_key(pk_id, headers, body):cfg, err = _parse_public_key_config(el)if err is not None:return err- if cfg["EncodedKey"] != pk["Config"]["EncodedKey"]:- return _error("CannotChangeImmutablePublicKeyFields", "The encoded key cannot be changed.", 400)+ # Only the comment can change.+ if any(cfg[k] != pk["Config"][k] for k in ("CallerReference", "Name", "EncodedKey")):+ return _error("CannotChangeImmutablePublicKeyFields", "Only the comment can be changed.", 400)new_etag = new_uuid()pk["Config"] = cfgpk["ETag"] = new_etag@@ -1787,12 +1784,7 @@ def _list_public_keys(query_params):# ----------------------------------------------------------------------------# KeyGroup — a named list of PublicKey ids, referenced by a distribution's-# trusted key groups (signed URLs/cookies) and by cache behaviors' OAC-signed-# origin access. Bespoke rather than the generic policy CRUD helpers above:-# KeyGroupConfig's own Items list has no analogue there, and AWS's error-# codes for this family (NoSuchResource / ResourceInUse) differ from the-# Cache/OriginRequest/ResponseHeaders policy families' Name-specific ones.+# Key groups# ---------------------------------------------------------------------------@@ -1831,8 +1823,19 @@ def _build_key_group_xml(parent, kg):_build_key_group_config_xml(cfg_el, kg["Config"])+def _trusted_key_group_ids(dist):+ try:+ root = fromstring(dist.get("config_xml") or "")+ except Exception:+ return set()+ return {+ el.text for tkg in root.iter() if tkg.tag.split("}")[-1] == "TrustedKeyGroups"+ for el in tkg.iter() if el.tag.split("}")[-1] == "KeyGroup" and el.text+ }++def _key_groups_using(kg_id):- return [d.get("Id", "") for d in _distributions.values() if _value_contains(d, kg_id)]+ return [d.get("Id", "") for d in _distributions.values() if kg_id in _trusted_key_group_ids(d)]def _create_key_group(body):@@ -2227,9 +2230,7 @@ async def handle_request(method, path, headers, body, query_params):if method == "GET":return _policy_list_distributions(_response_headers_policies, _RHP_SPEC, m.group(1))- # Public key routes. Unlike every other CloudFront policy family, real- # AWS puts UpdatePublicKey on the .../config path (PUT), not the bare- # .../{Id} path -- verified against botocore's service-2.json.+ # UpdatePublicKey is PUT .../config, unlike the other families.m = _PUBLIC_KEY_CFG_RE.match(path)if m:pk_id = m.group(1)diff --git a/ministack/services/ec2.py b/ministack/services/ec2.pyindex 97df8d3d..37386e1c 100644--- a/ministack/services/ec2.py+++ b/ministack/services/ec2.py@@ -3129,9 +3129,7 @@ def _describe_vpc_classic_link_dns_support(p):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."""+ """A subnet's PrivateDnsNameOptionsOnLaunch, defaulted when never set."""return subnet.get("PrivateDnsNameOptionsOnLaunch") or {"HostnameType": "ip-name","EnableResourceNameDnsARecord": False,@@ -3148,7 +3146,6 @@ def _modify_subnet_attribute(p):val = _p(p, "MapPublicIpOnLaunch.Value")if val: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:@@ -4344,8 +4341,7 @@ 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.+ # No IPv6 block is modelled, so the two IPv6 members are always false.dns_options = _subnet_dns_name_options(subnet)return f"""<{tag}><subnetId>{subnet['SubnetId']}</subnetId>@@ -4392,8 +4388,7 @@ 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.+# The Route shape has no vpcEndpointId member; an endpoint target is a gatewayId._ROUTE_MEMBERS = (("DestinationIpv6CidrBlock", "destinationIpv6CidrBlock"),("DestinationPrefixListId", "destinationPrefixListId"),@@ -4414,9 +4409,6 @@ _ROUTE_MEMBERS = (def _rtb_fields_xml(rtb, tag="item"):def _route_xml(r):- # 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))@@ -6813,7 +6805,6 @@ def _describe_launch_template_versions(p):"The specified launch template does not exist", 400)# Filter by version numbersreq_versions = _parse_member_list(p, "LaunchTemplateVersion")- # 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 = []diff --git a/ministack/services/lambda_microvms.py b/ministack/services/lambda_microvms.pyindex ce4ca915..030a0fa8 100644--- a/ministack/services/lambda_microvms.py+++ b/ministack/services/lambda_microvms.py@@ -8,6 +8,8 @@ There is no real VM behind a MicroVM here — a RunMicrovm goes straight toRUNNING and an image build straight to CREATED, which is what a client pollingGetMicrovm / GetMicrovmImage needs to proceed.+With Docker, images are built from the codeArtifact Dockerfile like AWS.+Shapes verified against the AWS Lambda MicroVM API reference (2025-09-09):RunMicrovm, GetMicrovm, ListMicrovms, SuspendMicrovm, ResumeMicrovm,TerminateMicrovm, ListMicrovmImages, CreateMicrovmImage, CreateMicrovmAuthToken,@@ -16,22 +18,39 @@ UpdateMicrovmImage."""import copy+import ioimport jsonimport logging+import os+import pathlibimport secrets+import stat+import tempfile+import threadingimport time-from urllib.parse import unquote+import urllib.error+import urllib.request+import zipfile+from urllib.parse import unquote, urlparse+from ministack.core import container_reaperfrom ministack.core.responses import (AccountRegionScopedDict,+ apply_image_prefix,error_response_json,get_account_id,get_region,json_response,+ request_scope,)logger = logging.getLogger("lambda_microvms")+DOCKER_NETWORK = os.environ.get("DOCKER_NETWORK", "")+_DOCKER_TIMEOUT = float(os.environ.get("MINISTACK_DOCKER_TIMEOUT", "10"))+_docker = None+_docker_in_use = False+# MicroVM lifecycle states (AWS enum)._MICROVM_STATES = ("PENDING", "RUNNING", "SUSPENDING", "SUSPENDED","TERMINATING", "TERMINATED")@@ -63,10 +82,20 @@ def _restore_state(data):_microvms.update(data.get("microvms", {}))_images.update(data.get("images", {}))-+ # Workloads do not survive a restart.+ for record in _microvms.values():+ if record.get("backend") == "docker" and record.get("state") not in (+ "TERMINATED", "TERMINATING"+ ):+ record["state"] = "TERMINATED"+ record["terminatedAt"] = record.get("terminatedAt") or _now()+ record.pop("_container_id", None)+ record.pop("_container_name", None)+ record.pop("_container_ip", None)def reset():+ _sweep_containers()_microvms.clear()_images.clear()@@ -125,6 +154,447 @@ def _resolve_image_arn(image_identifier: str) -> str:return _image_arn(image_identifier)+# ---------------------------------------------------------------------------+# Optional Docker-backed workload+# ---------------------------------------------------------------------------++def _docker_enabled() -> bool:+ return _get_docker() is not None+++def _get_docker():+ """Return a lazily-created Docker client, or None when unavailable."""+ global _docker+ if _docker is None:+ try:+ import docker++ _docker = docker.from_env(timeout=_DOCKER_TIMEOUT)+ except Exception as exc:+ logger.debug("MicroVM: no Docker client available: %s", exc)+ return _docker+++def _get_ministack_network(client):+ """Use the configured MiniStack network when one is available."""+ if DOCKER_NETWORK:+ return DOCKER_NETWORK+ try:+ hostname = os.environ.get("HOSTNAME", "")+ if not hostname:+ return None+ own_container = client.containers.get(hostname)+ networks = own_container.attrs.get("NetworkSettings", {}).get("Networks", {})+ return next(iter(networks), None)+ except Exception:+ return None+++def _valid_container_image(value) -> bool:+ """Reject values that cannot be a Docker image reference."""+ return (+ isinstance(value, str)+ and 1 <= len(value) <= 512+ and not any(ord(char) < 32 or ord(char) == 127 for char in value)+ and not any(char.isspace() for char in value)+ )+++def _hook_config(record):+ return record.get("hooks") or {}+++def _hook_enabled(record, group, name):+ return (_hook_config(record).get(group) or {}).get(name) == "ENABLED"+++def _hook_port(record):+ try:+ port = int(_hook_config(record).get("port"))+ except (TypeError, ValueError):+ return None+ return port if 1 <= port <= 65535 else None+++def _hook_timeout(record, group, name, default=30):+ raw = (_hook_config(record).get(group) or {}).get(f"{name}TimeoutInSeconds")+ try:+ return max(1, min(3600, int(raw)))+ except (TypeError, ValueError):+ return default+++def _s3_artifact_bytes(uri):+ """Read a code-artifact ZIP from MiniStack's account-scoped S3 service."""+ if not isinstance(uri, str) or not uri.startswith("s3://"):+ raise ValueError("codeArtifact.uri must be an s3:// URI")+ parsed = urlparse(uri)+ bucket = parsed.netloc+ key = parsed.path.lstrip("/")+ if not bucket or not key:+ raise ValueError("codeArtifact.uri must include an S3 bucket and key")+ from ministack.services import s3++ data = s3._get_object_data(bucket, key)+ if data is None:+ raise FileNotFoundError(f"code artifact not found: {uri}")+ return data+++def _safe_extract_artifact(data, destination):+ """Extract an artifact without allowing ZIP path traversal or symlinks."""+ root = pathlib.Path(destination).resolve()+ with zipfile.ZipFile(io.BytesIO(data)) as archive:+ for member in archive.infolist():+ relative = pathlib.PurePosixPath(member.filename)+ if relative.is_absolute() or ".." in relative.parts:+ raise ValueError(f"unsafe path in code artifact: {member.filename}")+ mode = (member.external_attr >> 16) & 0o170000+ if mode == stat.S_IFLNK:+ raise ValueError(f"symlinks are not allowed in code artifacts: {member.filename}")+ target = (root / pathlib.Path(*relative.parts)).resolve()+ if root != target and root not in target.parents:+ raise ValueError(f"unsafe path in code artifact: {member.filename}")+ if member.is_dir():+ target.mkdir(parents=True, exist_ok=True)+ continue+ target.parent.mkdir(parents=True, exist_ok=True)+ with archive.open(member, "r") as source, target.open("wb") as output:+ output.write(source.read())+++def _container_ip(container, network):+ container.reload()+ networks = container.attrs.get("NetworkSettings", {}).get("Networks", {})+ if network and network in networks:+ ip = networks[network].get("IPAddress")+ else:+ ip = next(iter(networks.values()), {}).get("IPAddress")+ if not ip:+ raise RuntimeError("Docker workload has no reachable network address")+ return ip+++def _hook_path(name):+ return f"/aws/lambda-microvms/runtime/v1/{name}"+++def _hooks_missing_port(hooks):+ hooks = hooks or {}+ configured = any(+ value == "ENABLED"+ for group in ("microvmHooks", "microvmImageHooks")+ for value in (hooks.get(group) or {}).values()+ )+ return configured and not _hook_port({"hooks": hooks})+++def _workload_kwargs(record):+ kwargs = {}+ env = record.get("environmentVariables")+ if isinstance(env, dict) and env:+ kwargs["environment"] = {str(k): str(v) for k, v in env.items()}+ if record.get("additionalOsCapabilities") == ["ALL"]:+ kwargs["cap_add"] = ["ALL"]+ port = _hook_port(record)+ client = _get_docker()+ if port and client is not None and not _get_ministack_network(client):+ kwargs["ports"] = {f"{port}/tcp": ("127.0.0.1", None)}+ return kwargs+++def _call_hook(record, container, name, *, image_phase=False, payload=None, retry=False):+ """POST one MicroVM hook and require a 2xx response."""+ port = _hook_port(record)+ if not port:+ raise RuntimeError("MicroVM hook port is not configured")+ client = _get_docker()+ network = _get_ministack_network(client) if client else None+ if network:+ host = _container_ip(container, network)+ else:+ # Host-run MiniStack reaches the hook via the loopback-published port.+ container.reload()+ bindings = (container.attrs.get("NetworkSettings", {}).get("Ports") or {}).get(f"{port}/tcp")+ if not bindings:+ raise RuntimeError("MicroVM hook port is not published")+ host, port = "127.0.0.1", int(bindings[0]["HostPort"])+ group = "microvmImageHooks" if image_phase else "microvmHooks"+ timeout = _hook_timeout(record, group, name)+ deadline = time.monotonic() + timeout if retry else None+ body = json.dumps(payload or {}).encode("utf-8")+ url = f"http://{host}:{port}{_hook_path(name)}"++ while True:+ request = urllib.request.Request(+ url,+ data=body,+ headers={"Content-Type": "application/json"},+ method="POST",+ )+ try:+ with urllib.request.urlopen(request, timeout=timeout) as response:+ status = response.status+ if 200 <= status < 300:+ return+ error = RuntimeError(f"MicroVM hook {name} returned HTTP {status}")+ except urllib.error.HTTPError as exc:+ error = RuntimeError(f"MicroVM hook {name} returned HTTP {exc.code}")+ status = exc.code+ except (urllib.error.URLError, TimeoutError, OSError) as exc:+ error = RuntimeError(f"MicroVM hook {name} was unreachable: {exc}")+ status = None+ if not retry or time.monotonic() >= deadline or status not in (None, 503):+ raise error+ time.sleep(0.1)+++def _image_has_entrypoint(client, image_ref):+ """Pull the image if needed and inspect whether it has a start command."""+ try:+ image = client.images.get(image_ref)+ except Exception:+ image = client.images.pull(image_ref)+ if isinstance(image, list):+ image = image[0]+ config = image.attrs.get("Config") or {}+ return bool(config.get("Entrypoint") or config.get("Cmd"))+++def _build_docker_image(record):+ """Build the image from the code-artifact ZIP\'s root Dockerfile."""+ client = _get_docker()+ if client is None:+ raise RuntimeError("no Docker daemon available")+ artifact = (record.get("codeArtifact") or {}).get("uri")+ data = _s3_artifact_bytes(artifact)+ image_ref = f"ministack-microvm:{secrets.token_hex(12)}"++ with tempfile.TemporaryDirectory(prefix="ministack-microvm-build-") as context:+ _safe_extract_artifact(data, context)+ if not os.path.isfile(os.path.join(context, "Dockerfile")):+ raise ValueError("code artifact must contain a Dockerfile at its root")+ client.images.build(path=context, tag=image_ref, rm=True, forcerm=True)++ network = _get_ministack_network(client)+ global _docker_in_use+ _docker_in_use = True+ build_kwargs = {+ "detach": True,+ "init": True,+ "labels": container_reaper.own_labels("lambda-microvm-build"),+ **_workload_kwargs(record),+ }+ if network:+ build_kwargs["network"] = network+ # Snapshot is disk-only: Docker cannot checkpoint memory without CRIU.+ def _drop(container, what):+ try:+ container.remove(force=True)+ except Exception as exc:+ logger.warning("MicroVM: could not remove image %s container: %s", what, exc)++ build_container = client.containers.run(image_ref, **build_kwargs)+ try:+ if _hook_enabled(record, "microvmImageHooks", "ready"):+ _call_hook(record, build_container, "ready", image_phase=True, retry=True)+ snapshot = f"ministack-microvm:{secrets.token_hex(12)}"+ repository, tag = snapshot.split(":", 1)+ build_container.commit(repository=repository, tag=tag)+ finally:+ _drop(build_container, "build")+ if _hook_enabled(record, "microvmImageHooks", "validate"):+ validate_container = client.containers.run(snapshot, **build_kwargs)+ try:+ _call_hook(record, validate_container, "validate", image_phase=True, retry=True)+ finally:+ _drop(validate_container, "validate")+ return snapshot+++def _build_in_background(record, success_state, failed_state, version):+ account_id, region = get_account_id(), get_region()++ def _run():+ with request_scope(account_id, region):+ try:+ image_ref = _build_docker_image(record)+ except Exception as exc:+ logger.warning("MicroVM: image build failed for %s: %s", record.get("name"), exc)+ record.update({+ "state": failed_state,+ "latestFailedImageVersion": version,+ "updatedAt": _now(),+ })+ return+ record.update({+ "_docker_image": image_ref,+ "state": success_state,+ "imageVersion": version,+ "latestActiveImageVersion": version,+ "updatedAt": _now(),+ })++ threading.Thread(target=_run, daemon=True, name=f"microvm-build-{record.get('name')}").start()+++def _container_name(microvm_id: str) -> str:+ return f"microvm-{microvm_id}"+++def _container_for(record):+ client = _get_docker()+ if client is None:+ return None+ for reference in (+ record.get("_container_id"),+ record.get("_container_name"),+ _container_name(record["microvmId"]),+ ):+ if not reference:+ continue+ try:+ return client.containers.get(reference)+ except Exception:+ continue+ return None+++def _remove_container(record):+ container = _container_for(record)+ if container is not None:+ try:+ container.remove(force=True)+ except Exception as exc:+ logger.warning(+ "MicroVM: could not remove container for %s: %s",+ record.get("microvmId"),+ exc,+ )+ record.pop("_container_id", None)+ record.pop("_container_name", None)+ record.pop("_container_ip", None)+++def _start_container(record, image_ref):+ client = _get_docker()+ if client is None:+ raise RuntimeError("no Docker daemon available")+ if not _valid_container_image(image_ref):+ raise ValueError("containerImage is not a valid Docker image reference")++ network = _get_ministack_network(client)+ name = _container_name(record["microvmId"])+ try:+ client.containers.get(name).remove(force=True)+ except Exception:+ pass++ image_ref = apply_image_prefix(image_ref)+ kwargs = {+ "name": name,+ "detach": True,+ "init": True,+ "labels": {+ **container_reaper.own_labels("lambda-microvm"),+ "microvm_id": record["microvmId"],+ "account_id": get_account_id(),+ "region": get_region(),+ },+ **_workload_kwargs(record),+ }+ if not _image_has_entrypoint(client, image_ref):+ # Keep an image with no ENTRYPOINT/CMD alive.+ kwargs["command"] = ["sleep", "infinity"]+ if network:+ kwargs["network"] = network++ container = client.containers.run(image_ref, **kwargs)+ global _docker_in_use+ _docker_in_use = True+ record["_container_id"] = container.id+ record["_container_name"] = name+ record["backend"] = "docker"+ if _hook_enabled(record, "microvmHooks", "run"):+ try:+ _call_hook(+ record,+ container,+ "run",+ payload={+ "microvmId": record["microvmId"],+ "runHookPayload": record.get("runHookPayload"),+ },+ retry=True,+ )+ except Exception:+ _remove_container(record)+ raise+ return container+++def _container_image_for(record):+ image = _find_microvm_image(record.get("imageArn"))+ if not image:+ return None+ return image.get("_docker_image")+++def _reconcile_microvm(record):+ """Turn a Docker-backed record into TERMINATED when its workload is gone."""+ if record.get("backend") != "docker" or record.get("state") != "RUNNING":+ return+ container = _container_for(record)+ if container is None:+ record["state"] = "TERMINATED"+ record["terminatedAt"] = record.get("terminatedAt") or _now()+ record.pop("_container_id", None)+ record.pop("_container_name", None)+ return+ try:+ container.reload()+ except Exception:+ return+ if getattr(container, "status", "") in ("dead", "exited"):+ record["state"] = "TERMINATED"+ record["terminatedAt"] = record.get("terminatedAt") or _now()+ record.pop("_container_id", None)+ record.pop("_container_name", None)+++def _live_container_ids():+ return {+ record.get("_container_id")+ for record in _microvms.values()+ if record.get("_container_id")+ }+++container_reaper.register_live_ids("lambda-microvm", _live_container_ids)+++def _sweep_containers():+ if not _docker_in_use:+ return+ client = _get_docker()+ if client is None:+ return+ try:+ containers = client.containers.list(+ all=True,+ filters={+ "label": [+ "ministack=lambda-microvm",+ f"{container_reaper.INSTANCE_LABEL}={container_reaper.instance_id()}",+ ]+ },+ )+ except Exception as exc:+ logger.warning("MicroVM: reset container sweep failed: %s", exc)+ return+ container_reaper.drop_containers(containers, force=True)++# ---------------------------------------------------------------------------# MicroVM views# ---------------------------------------------------------------------------@@ -176,8 +646,32 @@ def _run_microvm(body):"egressNetworkConnectors": data.get("egressNetworkConnectors"),"ingressNetworkConnectors": data.get("ingressNetworkConnectors"),"maximumDurationInSeconds": data.get("maximumDurationInSeconds"),+ "runHookPayload": data.get("runHookPayload"),}+ image_record = _find_microvm_image(record["imageArn"])+ if image_record:+ for field in ("hooks", "environmentVariables", "additionalOsCapabilities"):+ record[field] = image_record.get(field)_microvms[microvm_id] = record++ # With Docker available a MicroVM must come from a successfully built image.+ if _docker_enabled():+ image_ref = _container_image_for(record)+ if not image_ref:+ _microvms.pop(microvm_id, None)+ return _not_found(+ f"MicroVM image {image_identifier} has no successful Docker build"+ )+ try:+ _start_container(record, image_ref)+ except Exception as exc:+ _microvms.pop(microvm_id, None)+ logger.warning("MicroVM: could not boot %s: %s", image_ref, exc)+ return error_response_json(+ "InternalError",+ f"failed to start MicroVM workload: {exc}",+ 500,+ )return json_response(_microvm_view(record))@@ -185,6 +679,7 @@ def _get_microvm(microvm_id):record = _microvms.get(microvm_id)if not record:return _not_found(f"MicroVM {microvm_id} not found")+ _reconcile_microvm(record)return json_response(_microvm_view(record))@@ -199,6 +694,7 @@ def _list_microvms(query_params):version_filter = _qp("imageVersion")items = []for record in _microvms.values():+ _reconcile_microvm(record)if image_filter and image_filter not in (record.get("imageArn"), record.get("imageIdentifier")):@@ -213,6 +709,17 @@ def _suspend_microvm(microvm_id):record = _microvms.get(microvm_id)if not record:return _not_found(f"MicroVM {microvm_id} not found")+ _reconcile_microvm(record)+ if record.get("backend") == "docker":+ container = _container_for(record)+ if container is None:+ return _not_found(f"MicroVM {microvm_id} workload is no longer running")+ try:+ if _hook_enabled(record, "microvmHooks", "suspend"):+ _call_hook(record, container, "suspend")+ container.pause()+ except Exception as exc:+ return error_response_json("InternalError", f"could not suspend MicroVM: {exc}", 500)record["state"] = "SUSPENDED"return _empty_ok()@@ -221,6 +728,22 @@ def _resume_microvm(microvm_id):record = _microvms.get(microvm_id)if not record:return _not_found(f"MicroVM {microvm_id} not found")+ if record.get("backend") == "docker":+ container = _container_for(record)+ if container is None:+ record["state"] = "TERMINATED"+ record["terminatedAt"] = record.get("terminatedAt") or _now()+ return _not_found(f"MicroVM {microvm_id} workload is no longer available")+ try:+ container.unpause()+ if _hook_enabled(record, "microvmHooks", "resume"):+ _call_hook(record, container, "resume")+ except Exception as exc:+ try:+ container.pause()+ except Exception:+ pass+ return error_response_json("InternalError", f"could not resume MicroVM: {exc}", 500)record["state"] = "RUNNING"return _empty_ok()@@ -229,6 +752,14 @@ def _terminate_microvm(microvm_id):record = _microvms.get(microvm_id)if not record:return _not_found(f"MicroVM {microvm_id} not found")+ if record.get("backend") == "docker":+ container = _container_for(record)+ if container is not None and _hook_enabled(record, "microvmHooks", "terminate"):+ try:+ _call_hook(record, container, "terminate")+ except Exception as exc:+ logger.warning("MicroVM: terminate hook failed for %s: %s", microvm_id, exc)+ _remove_container(record)# Idempotent: terminating an already-terminated MicroVM succeeds.record["state"] = "TERMINATED"record["terminatedAt"] = record.get("terminatedAt") or _now()@@ -264,6 +795,8 @@ def _create_microvm_image(body):for field in ("baseImageArn", "buildRoleArn", "name", "codeArtifact"):if not data.get(field):return _validation(f"{field} is required")+ if _hooks_missing_port(data.get("hooks")):+ return _validation("hooks.port is required when hooks are configured")name = data["name"]now = _now()record = {@@ -289,7 +822,11 @@ def _create_microvm_image(body):"tags": data.get("tags"),}_images[name] = record- view = {k: v for k, v in record.items() if v is not None}+ if _docker_enabled():+ record["state"] = "CREATING"+ record.pop("latestActiveImageVersion", None)+ _build_in_background(record, "CREATED", "CREATE_FAILED", "1")+ view = {k: v for k, v in record.items() if v is not None and not k.startswith("_")}return json_response(view, 201)@@ -399,6 +936,8 @@ def _update_microvm_image(image_identifier, body):for field in ("baseImageArn", "buildRoleArn", "codeArtifact"):if not data.get(field):return _validation(f"{field} is required")+ if _hooks_missing_port(data["hooks"] if "hooks" in data else record.get("hooks")):+ return _validation("hooks.port is required when hooks are configured")version = str(int(record.get("imageVersion", "0")) + 1)for field in (@@ -408,13 +947,23 @@ def _update_microvm_image(image_identifier, body):):if field in data:record[field] = data[field]+ if _docker_enabled():+ record.update({"state": "UPDATING", "updatedAt": _now()})+ _build_in_background(record, "UPDATED", "UPDATE_FAILED", version)+ return json_response({+ **{k: v for k, v in record.items() if v is not None and not k.startswith("_")},+ "imageVersion": version,+ })record.update({"imageVersion": version,"latestActiveImageVersion": version,"state": "UPDATED","updatedAt": _now(),})- return json_response({k: v for k, v in record.items() if v is not None and k != "tags"})+ return json_response({+ **{k: v for k, v in record.items() if v is not None and not k.startswith("_")},+ "imageVersion": version,+ })# ---------------------------------------------------------------------------diff --git a/ministack/services/ssm.py b/ministack/services/ssm.pyindex a5af98ec..67f8996d 100644--- a/ministack/services/ssm.py+++ b/ministack/services/ssm.py@@ -373,9 +373,44 @@ def resolve_parameter_value(name_or_arn, version=None, decrypt=False):return param.get("Value")+def _split_selector(name_or_arn):+ """Split a trailing ":version" / ":label"; parameter names cannot contain ":"."""+ if not name_or_arn:+ return name_or_arn, None+ base_colons = 5 if name_or_arn.startswith("arn:") else 0+ if name_or_arn.count(":") <= base_colons:+ return name_or_arn, None+ base, selector = name_or_arn.rsplit(":", 1)+ return base, selector+++def _select_parameter(name_or_arn):+ """(param, error) for GetParameter / GetParameters, honouring name:version and name:label."""+ base, selector = _split_selector(name_or_arn)+ name, param = _lookup_parameter(base)+ if not param:+ return None, "ParameterNotFound"+ if selector is None:+ return param, None+ history = _parameter_history.get(name) or []+ if selector.isdigit():+ entry = next((h for h in history if str(h.get("Version")) == selector), None)+ else:+ entry = next((h for h in history if selector in (h.get("Labels") or [])), None)+ if entry is None:+ return None, "ParameterVersionNotFound"+ return {**entry, "Name": param["Name"], "ARN": param["ARN"], "Selector": f":{selector}"}, None++def _get_parameter(data):name = data.get("Name")- _, param = _lookup_parameter(name)+ param, error = _select_parameter(name)+ if error == "ParameterVersionNotFound":+ return error_response_json(+ "ParameterVersionNotFound",+ f"Systems Manager could not find version {_split_selector(name)[1]} of {_split_selector(name)[0]}.",+ 400,+ )if not param:return error_response_json("ParameterNotFound", f"Parameter {name} not found", 400)with_decryption = data.get("WithDecryption", False)@@ -388,7 +423,7 @@ def _get_parameters(data):params = []invalid = []for name in names:- _, p = _lookup_parameter(name)+ p, _ = _select_parameter(name)if p:params.append(_param_out(p, with_decryption))else:diff --git a/tests/test_autoscaling.py b/tests/test_autoscaling.pyindex e178d43f..f4362607 100644--- a/tests/test_autoscaling.py+++ b/tests/test_autoscaling.py@@ -442,13 +442,7 @@ def test_put_and_describe_scaling_policy(autoscaling):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."""+ """Target-tracking and step policies read back with only their type's members."""asg = _uid("asg-ttpol")autoscaling.create_auto_scaling_group(AutoScalingGroupName=asg, MinSize=0, MaxSize=2,@@ -496,9 +490,7 @@ def test_put_scaling_policy_target_tracking_and_step_read_back(autoscaling):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)."""+ """PredictiveScalingConfiguration reads back with MaxCapacityBreachBehavior defaulted."""asg = _uid("asg-pred")autoscaling.create_auto_scaling_group(AutoScalingGroupName=asg, MinSize=0, MaxSize=2,@@ -531,10 +523,7 @@ def test_put_scaling_policy_predictive_read_back(autoscaling):{"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."""+ """A non-numeric number member is a ValidationError, not a 500."""asg = _uid("asg-badnum")autoscaling.create_auto_scaling_group(AutoScalingGroupName=asg, MinSize=0, MaxSize=2,@@ -796,8 +785,7 @@ def test_put_and_describe_scheduled_action(autoscaling):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)."""+ """StartTime (also as Time), EndTime and TimeZone read back."""asg = _uid("asg-stimes")autoscaling.create_auto_scaling_group(AutoScalingGroupName=asg, MinSize=0, MaxSize=2,diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 06c527af..b1cc7132 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -56,8 +56,7 @@ _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."""+ """The template plus _FAILING_RESOURCE after ``depends_on``."""template = json.loads(body)template["Resources"]["Bad"] = {**_FAILING_RESOURCE, "DependsOn": depends_on}return json.dumps(template)@@ -16891,12 +16890,7 @@ def test_cfn_create_rollback_delete_failure_lands_rollback_failed(cfn, lam):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."""+ """A delete that fails in the cleanup phase still lands UPDATE_ROLLBACK_COMPLETE."""suffix = _uuid_mod.uuid4().hex[:8]fn = f"cr-urb-fail-{suffix}"stack_name = f"cfn-update-rollback-cleanup-{suffix}"@@ -16960,36 +16954,35 @@ def test_cfn_update_rollback_cleanup_delete_failure_still_completes(cfn, lam):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 = """\+def _cr_mode_handler(fail_mode):+ """A custom-resource handler that refuses an Update to Mode ``fail_mode``."""+ return f"""\import json, urllib.request+FAIL_MODE = {fail_mode!r}+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",+ 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", "revert-fails-cr"),- }).encode()+ "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))},+ 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."""+ """A custom resource going from Mode before to after beside a failing resource."""def template(mode, with_bad):resources = {"Topic": {"Type": "AWS::SNS::Topic", "Properties": {"TopicName": topic_name}},@@ -17004,15 +16997,13 @@ def _cr_revert_fails_templates(fn, topic_name):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."""+ """A revert that fails lands UPDATE_ROLLBACK_FAILED and keeps the previous resources."""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)},+ Code={"ZipFile": _cr_make_zip(_cr_mode_handler("before"))},)base, updated = _cr_revert_fails_templates(fn, f"cfn-urb-topic-{suffix}")try:@@ -17080,7 +17071,7 @@ 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_REVERT_FAILS)},+ Code={"ZipFile": _cr_make_zip(_cr_mode_handler("before"))},)base, updated = _cr_revert_fails_templates(fn, f"cfn-cur-{suffix}")try:@@ -17104,8 +17095,7 @@ 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 sent back, the retry completes the- # rollback without skipping anything.+ # Once the revert is accepted, the retry completes.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)@@ -17138,7 +17128,7 @@ 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_REVERT_FAILS)},+ Code={"ZipFile": _cr_make_zip(_cr_mode_handler("before"))},)base, updated = _cr_revert_fails_templates(fn, f"cfn-cur-skip-{suffix}")try:@@ -17303,9 +17293,7 @@ def test_cfn_appsync_schema_stack_delete_removes_schema(cfn, appsync):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)+ return _output(cfn.describe_stacks(StackName=stack_name)["Stacks"][0], key)def _cfn_appsync_members_template(name, api_props, oidc):@@ -17323,14 +17311,7 @@ def _cfn_appsync_members_template(name, api_props, oidc):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."""+ """ClusterSettings, DefaultCapacityProviderStrategy and Configuration read back in camelCase."""suffix = _uuid_mod.uuid4().hex[:8]stack_name = f"cfn-ecs-cl-{suffix}"cluster = f"cfn-ecs-cl-{suffix}"@@ -21914,13 +21895,7 @@ def test_cfn_iam_instance_profile_path_change_under_generated_name_replaces_it(cdef test_cfn_update_rollback_keeps_the_resources_that_existed_before(cfn, sqs, ddb):- """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 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."""+ """The rollback sends an in-place change back and deletes only what the update created."""uid = _uuid_mod.uuid4().hex[:8]stack_name = f"cfn-rb-keep-{uid}"queue_name = f"cfn-rb-keep-{uid}"@@ -21959,9 +21934,7 @@ def test_cfn_update_rollback_keeps_the_resources_that_existed_before(cfn, sqs, dand 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.+ # The queue goes back first, the refused table is marked complete, then the added queue is deleted.rollback = next(i for i, e in enumerate(events)if e["LogicalResourceId"] == stack_nameand e["ResourceStatus"] == "UPDATE_ROLLBACK_IN_PROGRESS")@@ -21977,8 +21950,6 @@ def test_cfn_update_rollback_keeps_the_resources_that_existed_before(cfn, sqs, dQueueUrl=queue_url, AttributeNames=["VisibilityTimeout", "ApproximateNumberOfMessages"])["Attributes"]assert attributes["ApproximateNumberOfMessages"] == "1"- # 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)@@ -24950,3 +24921,2582 @@ def test_sqs_change_set_reports_the_issue_reproduction(cfn, stack):change = _change(cfn, stack(old), new)assert change["Replacement"] == "True"assert _requirements(change) == {"QueueName": "Always", "DelaySeconds": "Never"}+++def test_cfn_appconfig_application_updates_in_place(cfn, appconfig_client):+ """An application update keeps its id."""+ 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 sent back by the rollback."""+ 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):+ """An environment update keeps its id."""+ 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 profile update keeps its id and its hosted configuration versions."""+ 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 in ConfigurationProfileSummary.+ 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 updates in place; a rename replaces the strategy."""+ 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():+ # By Ref: the list pages at 50.+ 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}")+++def test_cfn_appsync_api_update_keeps_id_and_children(cfn, appsync):+ """A GraphQL API update keeps its id and its data sources."""+ 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"+ 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):+ """An API key update keeps its key id."""+ 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):+ """An added AdditionalAuthenticationProviders entry reads back in camelCase."""+ 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):+ """AdditionalAuthenticationProviders from the create read back in camelCase."""+ 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 sent back by the rollback 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 removed AdditionalAuthenticationProviders reads absent."""+ 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):+ """API members apply at create, change in place and reset when removed."""+ 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):+ """A Visibility change fails the update and rolls back."""+ 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):+ """The API carries the template and stack tags, without the aws: ones."""+ 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)+++def test_cfn_asg_update_keeps_arn_and_created_time(cfn, autoscaling):+ """A size change keeps the group's ARN and CreatedTime."""+ 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):+ """A policy update keeps its ARN."""+ 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):+ """A scheduled action update keeps its ARN."""+ 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 reads back typed and updates in place."""+ 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):+ """A template PolicyName names the policy at create."""+ 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):+ """A PolicyName change or removal keeps the policy's name and 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):+ """The action gets a generated name, which Ref returns; ScheduledActionName is ignored."""+ 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 read back and update in place."""+ 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 reads back with its default and updates in place."""+ 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):+ """The group answers the launch template's id and name, whichever it was given."""+ 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):+ """An InstanceId change replaces the group."""+ 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 names the replacement.+ 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):+ """Step and customized-metric policies read back typed."""+ 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):+ """A template tag change keeps tags from CreateOrUpdateTags."""+ 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):+ """A MaxSize change is sent back by the rollback."""+ 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 sent back by the rollback."""+ 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 sent back by the rollback."""+ 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)+++def test_cfn_ec2_vpc_update_keeps_id_and_leaves_no_default_children(cfn, ec2):+ """A VPC update keeps its id and leaves no second set of default children."""+ 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):+ """A stack delete removes the VPC's default children."""+ 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):+ """A security group made outside the stack blocks the VPC delete (DependencyViolation)."""+ 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 removed DNS property goes back to its default."""+ 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):+ """A template tag change keeps tags from CreateTags."""+ 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):+ """An EnableDnsHostnames change is sent back by the rollback."""+ 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):+ """An IPAM member change replaces the VPC."""+ 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):+ """A MapPublicIpOnLaunch change keeps the subnet's id."""+ 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 removed MapPublicIpOnLaunch keeps its value."""+ 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):+ """An AvailabilityZoneId change replaces the subnet."""+ 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 updates in place; EnableDns64 without IPv6 fails."""+ 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):+ """An ingress change keeps the group's id and its out-of-band rules."""+ 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):+ """Rule descriptions, prefix-list and group sources update in place."""+ 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):+ """Declaring egress drops allow-all; dropping the declaration does not bring it back."""+ 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 change is sent back by the rollback."""+ 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):+ """A data change adds a version and leaves the default."""+ 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 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):+ """The template's tags come from its launch-template TagSpecifications, at create only."""+ 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):+ """The rollback of a data change adds a version with the old data."""+ 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):+ """A tag change keeps the gateway's id and attachment."""+ 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 gateway tag change is sent back by the rollback."""+ 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):+ """A tag change keeps the table's id and routes."""+ 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 route table tag change is sent back by the rollback."""+ 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):+ """Subnet, group, gateway and table tag changes keep tags from CreateTags."""+ 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):+ """The networking types carry the stack and aws:cloudformation tags."""+ 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):+ """A target change replaces the route instead of adding a second one."""+ 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):+ """IPv4, IPv6 and prefix-list destinations are separate routes."""+ 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)+++def test_cfn_update_rollback_records_the_cleanup_phase(cfn):+ """The rollback's stack events, cleanup phase included."""+ 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")++ # 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):+ """A change set that rolls back restores the previous parameters."""+ 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 _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):+ """One resource's statuses since the 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):+ """ContinueUpdateRollback retries a failed revert as an update."""+ 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."""+ 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):+ """A custom resource whose update failed is sent back too."""+ 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 type's refused update is not resent; it is recorded UPDATE_COMPLETE."""+ 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_cfn_update_appconfig.py b/tests/test_cfn_update_appconfig.pydeleted file mode 100644index cad789dc..00000000--- a/tests/test_cfn_update_appconfig.py+++ /dev/null@@ -1,253 +0,0 @@-"""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.pydeleted file mode 100644index f7fff0c8..00000000--- a/tests/test_cfn_update_appsync.py+++ /dev/null@@ -1,344 +0,0 @@-"""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.pydeleted file mode 100644index 1393f609..00000000--- a/tests/test_cfn_update_autoscaling.py+++ /dev/null@@ -1,733 +0,0 @@-"""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.pydeleted file mode 100644index 5a29e712..00000000--- a/tests/test_cfn_update_ec2.py+++ /dev/null@@ -1,1228 +0,0 @@-"""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.pydeleted file mode 100644index f2472851..00000000--- a/tests/test_cfn_update_rollback.py+++ /dev/null@@ -1,339 +0,0 @@-"""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.pyindex f8422dac..26e14216 100644--- a/tests/test_ec2.py+++ b/tests/test_ec2.py@@ -1381,11 +1381,7 @@ def test_ec2_modify_vpc_attribute(ec2):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."""+ """DescribeSubnets answers the DNS and IPv6 attributes; ModifySubnetAttribute sets the DNS options."""vpc_id = subnet_id = Nonetry:vpc_id = ec2.create_vpc(CidrBlock="10.61.0.0/16")["Vpc"]["VpcId"]@@ -2633,9 +2629,7 @@ def test_ec2_launch_template_crud(ec2):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."""+ """DescribeLaunchTemplateVersions lists newest first."""name = f"qa-lt-order-{_uuid_mod.uuid4().hex[:8]}"lt_id = ec2.create_launch_template(LaunchTemplateName=name, LaunchTemplateData={"InstanceType": "t3.micro"},@@ -2652,10 +2646,7 @@ def test_ec2_launch_template_versions_newest_first(ec2):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."""+ """Launch template tags read back through tagSet."""name = f"qa-lt-tags-{_uuid_mod.uuid4().hex[:8]}"resp = ec2.create_launch_template(LaunchTemplateName=name,diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.pyindex c6e6d14c..b7ed657b 100644--- a/tests/test_stepfunctions.py+++ b/tests/test_stepfunctions.py@@ -6,6 +6,7 @@ import osimport timeimport uuid as _uuid_modimport zipfile+from contextlib import contextmanagerimport boto3import pytest@@ -8399,3 +8400,146 @@ def test_numeric_equals_path_still_works():data = {"value": 7, "expected": 7}assert _evaluate_rule({"Variable": "$.value", "NumericEqualsPath": "$.expected"}, data)assert not _evaluate_rule({"Variable": "$.value", "NumericEqualsPath": "$.other"}, {"value": 7, "other": 8})+++# --- Secrets Manager SecretBinary at the SDK integration boundary ---++@contextmanager+def _machine(sfn, start, states):+ arn = sfn.create_state_machine(+ name=f"sfn-binary-{_uuid_mod.uuid4().hex}",+ roleArn="arn:aws:iam::000000000000:role/R",+ type="STANDARD",+ definition=json.dumps({"StartAt": start, "States": states}),+ loggingConfiguration={"level": "OFF", "includeExecutionData": False},+ )["stateMachineArn"]+ try:+ yield arn+ finally:+ sfn.delete_state_machine(stateMachineArn=arn)+++def _run(sfn, arn, data):+ execution = sfn.start_execution(stateMachineArn=arn, input=json.dumps(data))["executionArn"]+ try:+ deadline = time.monotonic() + 30+ while time.monotonic() < deadline:+ result = sfn.describe_execution(executionArn=execution)+ if result["status"] != "RUNNING":+ assert result["status"] == "SUCCEEDED", result+ return json.loads(result["output"])+ time.sleep(0.05)+ pytest.fail("synthetic execution timed out")+ finally:+ if sfn.describe_execution(executionArn=execution)["status"] == "RUNNING":+ sfn.stop_execution(executionArn=execution)+++_READ_STATES = {+ "Read": {+ "Type": "Task",+ "Resource": "arn:aws:states:::aws-sdk:secretsmanager:getSecretValue",+ "Parameters": {"SecretId.$": "$.secretId"},+ "End": True,+ },+}+_WRITE_STATES = {+ "Create": {+ "Type": "Task",+ "Resource": "arn:aws:states:::aws-sdk:secretsmanager:createSecret",+ "Parameters": {"Name.$": "$.secretId", "SecretBinary.$": "$.binary"},+ "ResultPath": None,+ "Next": "Put",+ },+ "Put": {+ "Type": "Task",+ "Resource": "arn:aws:states:::aws-sdk:secretsmanager:putSecretValue",+ "Parameters": {+ "SecretId.$": "$.secretId",+ "SecretBinary.$": "$.updatedBinary",+ "VersionStages": ["AWSPENDING"],+ },+ "End": True,+ },+}++[email protected]("value", [+ pytest.param("abcdefghijklmnop", id="base64-invalid-utf8"),+ pytest.param("cmF3cGFzc3dvcmQ=", id="base64-valid-utf8"),+ pytest.param("not-base64!", id="non-base64"),+ pytest.param("quote'and\\slash", id="sql-metacharacters"),+])+def test_sfn_secret_binary_read_is_raw_text(sfn, sm, value):+ name = f"sfn-binary-{_uuid_mod.uuid4().hex}"+ created = sm.create_secret(Name=name, SecretBinary=value.encode("utf-8"))+ try:+ before = sm.get_secret_value(SecretId=name)+ assert before["SecretBinary"] == value.encode("utf-8")+ with _machine(sfn, "Read", _READ_STATES) as arn:+ result = _run(sfn, arn, {"secretId": name})+ assert result["SecretBinary"] == value+ assert result["SecretBinary"] != base64.b64encode(before["SecretBinary"]).decode("ascii")+ assert result["VersionId"] == created["VersionId"]+ assert "SecretString" not in result+ after = sm.get_secret_value(SecretId=name)+ assert after["SecretBinary"] == before["SecretBinary"]+ assert after["VersionId"] == before["VersionId"]+ finally:+ sm.delete_secret(SecretId=name, ForceDeleteWithoutRecovery=True)++[email protected]("representation", ["raw", "base64"])+def test_sfn_secret_binary_writes_store_supplied_text(sfn, sm, representation):+ name = f"sfn-binary-{_uuid_mod.uuid4().hex}"+ original, updated = "abcdefghijklmnop", "not-base64!-updated"+ if representation == "base64":+ supplied = base64.b64encode(original.encode()).decode("ascii")+ supplied_update = base64.b64encode(updated.encode()).decode("ascii")+ else:+ supplied, supplied_update = original, updated+ try:+ with _machine(sfn, "Create", _WRITE_STATES) as arn:+ result = _run(sfn, arn, {+ "secretId": name, "binary": supplied, "updatedBinary": supplied_update,+ })+ current = sm.get_secret_value(SecretId=name, VersionStage="AWSCURRENT")+ pending = sm.get_secret_value(SecretId=name, VersionStage="AWSPENDING")+ assert current["SecretBinary"] == supplied.encode("utf-8")+ assert pending["SecretBinary"] == supplied_update.encode("utf-8")+ assert (current["SecretBinary"] == original.encode()) == (representation == "raw")+ assert (pending["SecretBinary"] == updated.encode()) == (representation == "raw")+ assert current["VersionId"] != pending["VersionId"]+ assert pending["VersionId"] == result["VersionId"]+ assert current["VersionStages"] == ["AWSCURRENT"]+ assert pending["VersionStages"] == ["AWSPENDING"]+ finally:+ sm.delete_secret(SecretId=name, ForceDeleteWithoutRecovery=True)+++def test_sfn_secret_string_is_not_transformed(sfn, sm):+ name = f"sfn-binary-{_uuid_mod.uuid4().hex}"+ value = '{"password":"cmF3cGFzc3dvcmQ="}'+ sm.create_secret(Name=name, SecretString=value)+ try:+ with _machine(sfn, "Read", _READ_STATES) as arn:+ result = _run(sfn, arn, {"secretId": name})+ assert result["SecretString"] == value+ assert "SecretBinary" not in result+ finally:+ sm.delete_secret(SecretId=name, ForceDeleteWithoutRecovery=True)+++def test_direct_secret_binary_sdk_keeps_arbitrary_bytes(sm):+ """The HTTP API must still base64-encode binary, including non-UTF-8 bytes."""+ name = f"sfn-binary-{_uuid_mod.uuid4().hex}"+ value = bytes(range(256))+ sm.create_secret(Name=name, SecretBinary=value)+ try:+ assert sm.get_secret_value(SecretId=name)["SecretBinary"] == value+ updated = sm.put_secret_value(SecretId=name, SecretBinary=value[::-1])+ result = sm.get_secret_value(SecretId=name)+ assert result["SecretBinary"] == value[::-1]+ assert result["VersionId"] == updated["VersionId"]+ finally:+ sm.delete_secret(SecretId=name, ForceDeleteWithoutRecovery=True)