Skip to content

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

feat(cloudformation): twelve update handlers, ECR through the store, replaced resources kept until success (#1757)

iot-rocket24c8fd7b5764
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5cd80841..7f276494 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,11 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Fixed
- **IAM — three calls are authorized against the action and resource AWS uses** — a Lambda Function URL invoke is checked against its function ARN, alias qualifier included, and supplies `lambda:FunctionUrlAuthType`, so the policy `grantInvokeUrl` writes matches. The WebSocket `@connections` API asks for `execute-api:ManageConnections` instead of `execute-api:Invoke`. `iot-jobs-data` operations are authorized under `iotjobsdata:`, except `StartCommandExecution`, which stays on `iot:`. A policy written for the old action names stops matching, as on AWS. Contributed by @iot-rocket.
+- **CloudFormation — `AWS::ECR::Repository` keeps what the template declares** — scanning and encryption settings were stored in the template's PascalCase and read back empty, lifecycle policy, repository policy and tags were dropped, `PutImage` into the repository failed and a deleted repository left its images and policies behind. The repository is now created, updated in place and deleted through the ECR store. Contributed by @iot-rocket.
+- **CloudFormation — a rolled-back replacement keeps the old resource** — an update handler deleted the predecessor as soon as the replacement existed, so when a later resource failed the rollback removed the replacement too and the stack recorded a resource that was gone. The predecessor is now deleted in the cleanup phase after the update succeeds, and a rollback deletes only the replacement, as measured on AWS. Contributed by @iot-rocket.
+### Added
+- **CloudFormation: the `AWS::LanguageExtensions` transform**: a template declaring it was provisioned unexpanded, so an `Fn::ForEach` left the stack in `CREATE_IN_PROGRESS` for good and an `Fn::ToJsonString` reached SSM as a Python dict. The transform now runs between `AWS::Include` and SAM: `Fn::ForEach` over literal, `CommaDelimitedList` and intrinsic collections, nested and inside `Properties`, plus `Fn::Length` and `Fn::ToJsonString`. Where the identifier is substituted, the error sentences and the unexpanded `GetTemplateSummary` follow measurements on a real account. Contributed by @iot-rocket.
+- **CloudFormation — update handlers for twelve more types** — a stack update of these types re-ran the create: the four ELBv2 types, `AWS::Route53::HostedZone`, `AWS::WAFv2::WebACL` and `AWS::Backup::BackupPlan` came back under a new id, `AWS::IoT::ThingType` failed with `ResourceAlreadyExistsException`, and certificate, email identity, backup vault and API Gateway account changes were lost. Each type now updates in place where its reference allows, replaces otherwise and refuses to replace a custom-named resource. Also fixed: a stack's backup plan read back without rules, its email identity was invisible to SES v2, `DescribeTags` raised on its target groups, and ACM timestamps answered the time of the call. Contributed by @iot-rocket.
- **API Gateway — REST API gateway responses reach the data plane** — a customized gateway response was stored but never applied, so a 401 or 403 from the gateway carried none of the CORS headers a CDK stack declares for it. Gateway errors now resolve the response for their type, then `DEFAULT_4XX` or `DEFAULT_5XX`, then the built-in default, from the stage's last deployment, with header mappings, the `application/json` template and `x-amzn-ErrorType`. `GetGatewayResponse` reports an inherited `DEFAULT_4XX` or `DEFAULT_5XX`, and a response put without templates stores the default one. Contributed by @iot-rocket.
- **API Gateway — REST API gateway errors answer with the AWS status and message** — an authorizer that raised, a missing Lambda and an unreachable HTTP backend answered with invented statuses and exception text, and an unknown stage with `404`. They now answer `500` `AUTHORIZER_FAILURE` with a null message, `500` `API_CONFIGURATION_ERROR` with `Internal server error`, and `403` `Forbidden`; an explicit Deny carries the full AWS sentence, and a TOKEN authorizer policy without `principalId` is evaluated instead of refused. Contributed by @iot-rocket.
- **API Gateway — a MOCK integration honours its `statusCode`** — the `200` integration response was used whatever the request template set, so a MOCK method modelling an error returned `200`. The template's `statusCode` now selects the integration response by `selectionPattern`. Contributed by @iot-rocket.
diff --git a/ministack/services/acm.py b/ministack/services/acm.py
index f251dca8..b415aa5f 100644
--- a/ministack/services/acm.py
+++ b/ministack/services/acm.py
@@ -10,6 +10,7 @@ Supports: RequestCertificate, DescribeCertificate, ListCertificates,
"""
import copy
+import datetime
import hashlib
import json
import logging
@@ -130,11 +131,16 @@ def _future_iso(seconds):
def _epoch(iso_or_epoch):
- """Convert ISO timestamp to epoch float if needed. ACM API returns epoch floats."""
+ """Convert ISO timestamp to epoch float if needed. ACM API returns epoch
+ floats. The seconds-only format this used to parse does not match the
+ millisecond timestamps ``now_iso`` writes, so ``CreatedAt`` and
+ ``IssuedAt`` fell through to the fallback and every certificate answered
+ the time of the call, which made each read look like a fresh issue."""
if isinstance(iso_or_epoch, (int, float)):
return float(iso_or_epoch)
try:
- return time.mktime(time.strptime(iso_or_epoch, "%Y-%m-%dT%H:%M:%SZ")) - time.timezone
+ return datetime.datetime.fromisoformat(
+ str(iso_or_epoch).replace("Z", "+00:00")).timestamp()
except (ValueError, TypeError):
return time.time()
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 2dddc1dd..6d8d200f 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -634,6 +634,27 @@ _CUSTOM_NAME_REPLACEMENT = {
"name": "ThingGroupName",
"requires_replacement": lambda old, new: old.get("ParentGroupName") != new.get("ParentGroupName"),
},
+ # Measured on an account: a ThingTypeDescription or SearchableAttributes
+ # change under an explicit, unchanged ThingTypeName fails the update with
+ # the custom-named-resource sentence, while an Mqtt5Configuration change
+ # updates in place ("After a thing type is created, you can only update
+ # Mqtt5Configuration").
+ "AWS::IoT::ThingType": {
+ "name": "ThingTypeName",
+ "requires_replacement": lambda old, new: any(
+ (old.get("ThingTypeProperties") or {}).get(p)
+ != (new.get("ThingTypeProperties") or {}).get(p)
+ for p in ("ThingTypeDescription", "SearchableAttributes")
+ ),
+ },
+ # BackupVaultName is required, so every vault is custom-named. Measured on
+ # an account: adding EncryptionKeyArn fails with the refusal sentence.
+ "AWS::Backup::BackupVault": {
+ "name": "BackupVaultName",
+ "requires_replacement": lambda old, new: (
+ old.get("EncryptionKeyArn", "") != new.get("EncryptionKeyArn", "")
+ ),
+ },
# KmsKeyId is "Update requires: Replacement" in the resource reference.
"AWS::Location::Tracker": {
"name": "TrackerName",
@@ -643,6 +664,38 @@ _CUSTOM_NAME_REPLACEMENT = {
"name": "InstanceProfileName",
"requires_replacement": lambda old, new: old.get("Path", "/") != new.get("Path", "/"),
},
+ # "If you specify a name, you cannot perform updates that require
+ # replacement of this resource, but you can perform other updates"
+ # (aws-resource-elasticloadbalancingv2-loadbalancer), which is this rule
+ # written out on the type's own page. Scheme and Type are its two
+ # replacing properties.
+ "AWS::ElasticLoadBalancingV2::LoadBalancer": {
+ "name": "Name",
+ "requires_replacement": lambda old, new: (
+ old.get("Scheme", "internet-facing") != new.get("Scheme", "internet-facing")
+ or old.get("Type", "application") != new.get("Type", "application")
+ ),
+ },
+ # A target group name "must be unique per region per account"; Port,
+ # Protocol, ProtocolVersion, TargetType, VpcId and IpAddressType are
+ # "Update requires: Replacement".
+ "AWS::ElasticLoadBalancingV2::TargetGroup": {
+ "name": "Name",
+ "requires_replacement": lambda old, new: any(
+ old.get(p) != new.get(p) for p in (
+ "Port", "Protocol", "ProtocolVersion", "TargetType", "VpcId",
+ "IpAddressType",
+ )
+ ),
+ },
+ # A web ACL name is unique per scope per account and cannot be changed
+ # after creation; Scope is the other replacing property.
+ "AWS::WAFv2::WebACL": {
+ "name": "Name",
+ "requires_replacement": lambda old, new: (
+ old.get("Scope", "REGIONAL") != new.get("Scope", "REGIONAL")
+ ),
+ },
}
@@ -669,11 +722,27 @@ def _custom_named_replacement_error(resource_type, old_props, new_props):
return None
+def _requires_replacement(resource_type, old_props, new_props):
+ """Whether a replacing property of the type changed, read from the table
+ ``_custom_named_replacement_error`` reads. An explicit physical name
+ refuses that replacement above the handler; under a generated name there
+ is nothing to refuse and the handler performs it, so both answers come
+ from one definition."""
+ spec = _CUSTOM_NAME_REPLACEMENT.get(resource_type)
+ return bool(spec and spec["requires_replacement"](old_props, new_props))
+
+
# Set by the stack engine around an update whose resource carries
# ``UpdateReplacePolicy: Retain`` (or ``RetainExceptOnCreate``): a handler that
# replaces the resource must then leave the predecessor in place; the engine
# records the DELETE_SKIPPED event.
_RETAIN_REPLACED = contextvars.ContextVar("cfn_retain_replaced", default=False)
+# Set by the stack engine to a list around an update handler: a predecessor
+# delete is then queued there and run in the cleanup phase after the update
+# succeeds, so a rollback still finds the old resource. Unset (None), the
+# delete runs at once.
+_DEFERRED_PREDECESSOR_DELETES = contextvars.ContextVar(
+ "cfn_deferred_predecessor_deletes", default=None)
# The DeletionPolicy / UpdateReplacePolicy values that keep a resource; the
# engine reads the same tuple for the cleanup phase and the stack delete.
# Snapshot is not among them: the emulator takes no snapshots, so a Snapshot
@@ -716,16 +785,20 @@ def _delete_predecessor(delete_fn, *args, **kwargs):
retaining set): the engine then records the DELETE_SKIPPED event and the
predecessor stays, as on AWS. Every update handler that creates the
replacement itself removes the old resource through this, so the policy
- cannot be forgotten at one site, with three exceptions. Two have a
- deterministic generated name (the DynamoDB table and the Location
- tracker): the replacement takes the name back, so there is nothing left
- to retain. The third is the Lambda permission's degenerate ``Id`` branch,
+ cannot be forgotten at one site, with four exceptions. Three have a
+ deterministic generated name (the DynamoDB table, the Location tracker
+ and the IoT thing type): the replacement takes the name back, so there is
+ nothing left to retain. The fourth is the Lambda permission's degenerate ``Id`` branch,
which removes and re-puts one statement under a Sid that cannot change:
the physical id is kept, nothing is replaced, and the policy does not
apply.
"""
if _RETAIN_REPLACED.get():
return
+ deferred = _DEFERRED_PREDECESSOR_DELETES.get()
+ if deferred is not None:
+ deferred.append((delete_fn, args, kwargs))
+ return
delete_fn(*args, **kwargs)
@@ -866,6 +939,7 @@ _STACK_TAG_PROPERTY: dict[str, tuple[str, str]] = {
"AWS::Cognito::UserPool": ("UserPoolTags", "map"),
"AWS::DynamoDB::Table": ("Tags", "list"),
"AWS::EC2::VPCEndpoint": ("Tags", "list"),
+ "AWS::ECR::Repository": ("Tags", "list"),
"AWS::ECS::Cluster": ("Tags", "list"),
"AWS::ECS::Service": ("Tags", "list"),
"AWS::EKS::Cluster": ("Tags", "list"),
@@ -3762,12 +3836,16 @@ def _cfn_nested_stack_deploy(logical_id, props, parent_stack_name, *,
res_def, "UpdateReplacePolicy", provisioned, param_values,
conditions, mappings, child_name, child_stack_id,
) in _RETAINING_POLICIES)
+ # The child has no cleanup phase of its own: its handlers
+ # delete the predecessor at once, not into the parent's queue.
+ deferred_token = _DEFERRED_PREDECESSOR_DELETES.set(None)
try:
physical_id, attrs = _update_resource(
resource_type, prev.get("PhysicalResourceId", child_logical_id),
old_tagged, new_tagged, child_name, child_logical_id,
)
finally:
+ _DEFERRED_PREDECESSOR_DELETES.reset(deferred_token)
_RETAIN_REPLACED.reset(token)
else:
physical_id, attrs = _provision_resource(
@@ -4674,6 +4752,25 @@ def _apigw_account_delete(physical_id, props):
_apigw_v1._account_settings["settings"] = settings
+def _apigw_account_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update the account settings in place. ``CloudWatchRoleArn`` is the
+ type's only property and is "Update requires: No interruption"
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-account.html).
+ The create handler only ever wrote a declared role, so a template that
+ dropped the property left the old role in the settings the ``GetAccount``
+ call answers; here it is removed, as ``UpdateAccount`` with a null value
+ does."""
+ settings = dict(_apigw_v1._account_settings.get("settings") or {})
+ role_arn = new_props.get("CloudWatchRoleArn")
+ if role_arn is None:
+ settings.pop("cloudwatchRoleArn", None)
+ else:
+ settings["cloudwatchRoleArn"] = role_arn
+ _apigw_v1._account_settings["settings"] = settings
+ return physical_id, {}
+
+
# --- API Gateway DomainName ---
def _apigw_domain_name_create(logical_id, props, stack_name):
@@ -6121,25 +6218,71 @@ def _cognito_user_pool_domain_delete(physical_id, props):
# ===========================================================================
# --- ECR resource provisioners ---
-def _ecr_repo_create(logical_id, props, stack_name):
- name = props.get("RepositoryName", f"{stack_name}-{logical_id}".lower())
- arn = f"arn:aws:ecr:{get_region()}:{get_account_id()}:repository/{name}"
- _ecr._repositories[name] = {
- "repositoryName": name,
- "repositoryArn": arn,
- "registryId": get_account_id(),
- "repositoryUri": f"{get_account_id()}.dkr.ecr.{get_region()}.amazonaws.com/{name}",
- "createdAt": __import__("time").time(),
+def _ecr_cfn_to_api(props):
+ """The ``CreateRepository`` members an ``AWS::ECR::Repository`` declares,
+ in the API's casing and shapes: the store keeps what the API writes, and
+ ``DescribeRepositories`` and ``ListTagsForResource`` answer it verbatim.
+ A member the template leaves out takes the API's default."""
+ scanning = props.get("ImageScanningConfiguration") or {}
+ encryption = props.get("EncryptionConfiguration") or {}
+ encryption_config = {"encryptionType": encryption.get("EncryptionType", "AES256")}
+ if encryption.get("KmsKey"):
+ encryption_config["kmsKey"] = encryption["KmsKey"]
+ return {
"imageTagMutability": props.get("ImageTagMutability", "MUTABLE"),
- "imageScanningConfiguration": props.get("ImageScanningConfiguration", {"scanOnPush": False}),
- "encryptionConfiguration": props.get("EncryptionConfiguration", {"encryptionType": "AES256"}),
- "images": [],
+ "imageScanningConfiguration": {
+ "scanOnPush": str(scanning.get("ScanOnPush", False)).lower() == "true",
+ },
+ "encryptionConfiguration": encryption_config,
+ "tags": [{"Key": t["Key"], "Value": t.get("Value", "")}
+ for t in props.get("Tags") or [] if isinstance(t, dict) and "Key" in t],
}
- return name, {"Arn": arn, "RepositoryUri": _ecr._repositories[name]["repositoryUri"]}
+
+
+def _ecr_repo_apply_policies(name, props):
+ """Write the lifecycle policy and the repository policy through the ECR
+ calls that own them, and remove one the template no longer declares."""
+ lifecycle = (props.get("LifecyclePolicy") or {}).get("LifecyclePolicyText")
+ if lifecycle:
+ _ecr._put_lifecycle_policy({"repositoryName": name, "lifecyclePolicyText": lifecycle})
+ else:
+ _ecr._lifecycle_policies.pop(name, None)
+ policy = props.get("RepositoryPolicyText")
+ if policy:
+ _ecr._set_repository_policy({
+ "repositoryName": name,
+ "policyText": policy if isinstance(policy, str) else json.dumps(policy),
+ })
+ else:
+ _ecr._repo_policies.pop(name, None)
+
+
+def _ecr_repo_create(logical_id, props, stack_name):
+ name = props.get("RepositoryName", f"{stack_name}-{logical_id}".lower())
+ api = _ecr_cfn_to_api(props)
+ if name in _ecr._repositories:
+ # The create has always overwritten an existing record; refusing the
+ # duplicate is a separate change.
+ _ecr._repositories[name].update(api)
+ else:
+ _ecr._create_repository({"repositoryName": name, **api})
+ _ecr_repo_apply_policies(name, props)
+ repo = _ecr._repositories[name]
+ return name, {"Arn": repo["repositoryArn"], "RepositoryUri": repo["repositoryUri"]}
def _ecr_repo_delete(physical_id, props):
- _ecr._repositories.pop(physical_id, None)
+ """Delete through ``DeleteRepository``, which drops the images and both
+ policies with the repository and refuses one that still holds images
+ unless ``EmptyOnDelete`` is true."""
+ if physical_id not in _ecr._repositories:
+ return
+ status, _, body = _ecr._delete_repository({
+ "repositoryName": physical_id,
+ "force": str(props.get("EmptyOnDelete", False)).lower() == "true",
+ })
+ if status >= 400:
+ raise ValueError(json.loads(body).get("message", body))
# --- CodeBuild Project provisioner ---
@@ -6889,6 +7032,23 @@ def _elbv2_tags(tags):
return out
+def _elbv2_merge_attributes(store, declared):
+ """Apply the attributes a template declares over the ones the resource
+ already carries, which is what the resource reference documents for
+ ``LoadBalancerAttributes``, ``TargetGroupAttributes`` and
+ ``ListenerAttributes``: "Attributes that you do not modify retain their
+ current values". The list is changed in place."""
+ declared = [a for a in (declared or []) if isinstance(a, dict) and a.get("Key")]
+ if not declared:
+ return
+ merged = {a.get("Key"): a for a in store if isinstance(a, dict)}
+ for attribute in declared:
+ merged[attribute["Key"]] = {
+ "Key": attribute["Key"], "Value": str(attribute.get("Value", "")),
+ }
+ store[:] = list(merged.values())
+
+
def _elbv2_load_balancer_create(logical_id, props, stack_name):
name = props.get("Name") or _physical_name(
stack_name,
@@ -6962,26 +7122,75 @@ def _elbv2_load_balancer_delete(physical_id, props):
_alb._tags.pop(physical_id, None)
-def _elbv2_listener_create(logical_id, props, stack_name):
- lb_arn = props.get("LoadBalancerArn", "")
- lb = _alb._lbs.get(lb_arn)
- if not lb:
- raise ValueError(f"Load balancer not found for Listener: {lb_arn}")
+def _elbv2_load_balancer_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update a load balancer in place, keeping its ARN (what ``Ref``
+ returns), its DNS name, its listeners and the targets registered behind
+ them. ``IpAddressType``, ``SecurityGroups``, ``Subnets``,
+ ``LoadBalancerAttributes`` and ``Tags`` are "Update requires: No
+ interruption" on the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-loadbalancer.html);
+ ``Name``, ``Scheme`` and ``Type`` require replacement. A changed name
+ replaces through the shared prologue, and a ``Scheme`` or ``Type`` change
+ under a custom name is refused by ``_custom_named_replacement_error``,
+ which is what the reference states for this type: "If you specify a name,
+ you cannot perform updates that require replacement of this resource, but
+ you can perform other updates." Under a generated name there is nothing to
+ refuse and the replacement is performed here. ``SubnetMappings`` is No
+ interruption as well and is modelled on neither path, here or in the
+ create.
+ """
+ name = new_props.get("Name") or _physical_name(
+ stack_name, logical_id or physical_id, lowercase=True, max_len=32)
+ lb = _alb._lbs.get(physical_id)
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ name, lb.get("LoadBalancerName") if lb else None,
+ _elbv2_load_balancer_create, _elbv2_load_balancer_delete,
+ )
+ if replaced is not None:
+ return replaced
+ if _requires_replacement("AWS::ElasticLoadBalancingV2::LoadBalancer",
+ old_props, new_props):
+ # Scheme and Type replace. A generated name does not refuse that, and
+ # the new ARN carries a fresh id, so the predecessor is a resource of
+ # its own and an UpdateReplacePolicy of Retain can keep it.
+ created = _elbv2_load_balancer_create(
+ logical_id or physical_id, new_props, stack_name)
+ _delete_predecessor(_elbv2_load_balancer_delete, physical_id, old_props)
+ return created
- listener_id = _alb._short_id()
- lb_name = lb["LoadBalancerName"]
- lb_id = _alb._load_balancer_id_from_arn(lb_arn)
- listener_arn = (
- f"arn:aws:elasticloadbalancing:{get_region()}:{get_account_id()}:"
- f"listener/app/{lb_name}/{lb_id}/{listener_id}"
+ lb["IpAddressType"] = new_props.get("IpAddressType", "ipv4")
+ lb["Subnets"] = _elbv2_as_list(new_props.get("Subnets"))
+ lb["SecurityGroups"] = _elbv2_as_list(new_props.get("SecurityGroups"))
+ _elbv2_merge_attributes(
+ _alb._lb_attrs.setdefault(physical_id, []),
+ new_props.get("LoadBalancerAttributes"),
)
+ _reconcile_tag_list(_alb._tags.setdefault(physical_id, []), old_props, new_props)
+ lb_id = _alb._load_balancer_id_from_arn(physical_id)
+ return physical_id, {
+ "Arn": physical_id,
+ "LoadBalancerArn": physical_id,
+ "LoadBalancerName": lb["LoadBalancerName"],
+ "DNSName": lb["DNSName"],
+ "LoadBalancerFullName": f"app/{lb['LoadBalancerName']}/{lb_id}",
+ "CanonicalHostedZoneID": "Z35SXDOTRQ7X7K",
+ "SecurityGroups": lb["SecurityGroups"],
+ }
+
+def _elbv2_listener_actions(props, lb_arn, prop="DefaultActions"):
+ """The action records an ``AWS::ElasticLoadBalancingV2::Listener`` or
+ ``ListenerRule`` stores, in the shape the ALB service keeps. A forward
+ action also records the listener's load balancer on the target group, the
+ way ``CreateListener`` does; a rule passes no ``lb_arn`` and skips that."""
actions = []
- for idx, action in enumerate(props.get("DefaultActions", []) or [], start=1):
+ for idx, action in enumerate(props.get(prop) or [], start=1):
if not isinstance(action, dict):
continue
entry = {
- "Type": action.get("Type", "fixed-response"),
+ "Type": action.get("Type", "fixed-response" if lb_arn else "forward"),
"Order": int(action.get("Order", idx)),
}
tg_arn = action.get("TargetGroupArn")
@@ -6992,13 +7201,32 @@ def _elbv2_listener_create(logical_id, props, stack_name):
tg_arn = tg_list[0].get("TargetGroupArn")
if tg_arn:
entry["TargetGroupArn"] = tg_arn
- if tg_arn in _alb._tgs and lb_arn not in _alb._tgs[tg_arn].get("LoadBalancerArns", []):
+ if (lb_arn and tg_arn in _alb._tgs
+ and lb_arn not in _alb._tgs[tg_arn].get("LoadBalancerArns", [])):
_alb._tgs[tg_arn].setdefault("LoadBalancerArns", []).append(lb_arn)
if isinstance(action.get("FixedResponseConfig"), dict):
- entry["FixedResponseConfig"] = action["FixedResponseConfig"]
+ entry["FixedResponseConfig"] = dict(action["FixedResponseConfig"])
if isinstance(action.get("RedirectConfig"), dict):
- entry["RedirectConfig"] = action["RedirectConfig"]
+ entry["RedirectConfig"] = dict(action["RedirectConfig"])
actions.append(entry)
+ return actions
+
+
+def _elbv2_listener_create(logical_id, props, stack_name):
+ lb_arn = props.get("LoadBalancerArn", "")
+ lb = _alb._lbs.get(lb_arn)
+ if not lb:
+ raise ValueError(f"Load balancer not found for Listener: {lb_arn}")
+
+ listener_id = _alb._short_id()
+ lb_name = lb["LoadBalancerName"]
+ lb_id = _alb._load_balancer_id_from_arn(lb_arn)
+ listener_arn = (
+ f"arn:aws:elasticloadbalancing:{get_region()}:{get_account_id()}:"
+ f"listener/app/{lb_name}/{lb_id}/{listener_id}"
+ )
+
+ actions = _elbv2_listener_actions(props, lb_arn)
listener = {
"ListenerArn": listener_arn,
@@ -7036,6 +7264,43 @@ def _elbv2_listener_delete(physical_id, props):
_alb._tags.pop(rule_arn, None)
+def _elbv2_listener_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update a listener in place, keeping its ARN (what ``Ref`` returns) and
+ the rules attached to it, which the create handler removes with the
+ listener. ``Port``, ``Protocol``, ``DefaultActions``, ``Certificates``,
+ ``AlpnPolicy``, ``ListenerAttributes``, ``MutualAuthentication`` and
+ ``Tags`` are "Update requires: No interruption" and ``SslPolicy`` is
+ "Some interruptions"; only ``LoadBalancerArn`` requires replacement
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listener.html),
+ and a listener ARN carries its load balancer, so moving one is a
+ replacement under a new physical id. The default actions are written on
+ the listener's default rule as well, as ``ModifyListener`` does: the data
+ plane reads the rule.
+ """
+ listener = _alb._listeners.get(physical_id)
+ if listener is None or listener.get("LoadBalancerArn") != new_props.get("LoadBalancerArn"):
+ created = _elbv2_listener_create(
+ logical_id or physical_id, new_props, stack_name)
+ if listener is not None:
+ _delete_predecessor(_elbv2_listener_delete, physical_id, old_props)
+ return created
+
+ listener["Port"] = int(new_props.get("Port", 80) or 80)
+ listener["Protocol"] = new_props.get("Protocol", "HTTP")
+ actions = _elbv2_listener_actions(new_props, listener["LoadBalancerArn"])
+ listener["DefaultActions"] = actions
+ for rule in _alb._rules.values():
+ if rule.get("ListenerArn") == physical_id and rule.get("IsDefault"):
+ rule["Actions"] = actions
+ _elbv2_merge_attributes(
+ _alb._listener_attrs.setdefault(physical_id, []),
+ new_props.get("ListenerAttributes"),
+ )
+ _reconcile_tag_list(_alb._tags.setdefault(physical_id, []), old_props, new_props)
+ return physical_id, {"ListenerArn": physical_id, "Arn": physical_id}
+
+
# ---------------------------------------------------------------------------
# Lambda LayerVersion
# ---------------------------------------------------------------------------
@@ -7395,6 +7660,67 @@ def _acm_certificate_delete(physical_id, props):
_acm._certificates.pop(physical_id, None)
+# The properties that require replacing an AWS::CertificateManager::Certificate,
+# each "Update requires: Replacement" on the resource reference.
+_ACM_REPLACEMENT_PROPERTIES = (
+ "CertificateAuthorityArn", "CertificateExport", "DomainName",
+ "DomainValidationOptions", "KeyAlgorithm", "SubjectAlternativeNames",
+)
+
+
+def _acm_certificate_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update a certificate in place, keeping its ARN (what ``Ref`` returns),
+ its issue and expiry dates and its key material. ``Tags``,
+ ``ValidationMethod`` and ``CertificateTransparencyLoggingPreference`` are
+ "Update requires: No interruption" on the resource reference, which says
+ of the last one: "Changing the certificate transparency logging
+ preference will update the existing resource by calling
+ UpdateCertificateOptions on the certificate. This action will not create
+ a new resource."
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-certificatemanager-certificate.html).
+ The create handler instead re-issued the certificate on any change, which
+ moved its validity window and replaced the PEM the ACM read paths serve.
+ A changed ``DomainName``, ``SubjectAlternativeNames``, ``KeyAlgorithm``,
+ ``DomainValidationOptions``, ``CertificateAuthorityArn`` or
+ ``CertificateExport`` requires replacement: the new certificate is
+ requested before the old one is deleted, CloudFormation's replacement
+ order. A ``ValidationMethod`` change regenerates ``DomainValidationOptions``
+ the same way ``_acm_certificate_create`` derives them
+ (``acm._validation_options`` per SAN); left stale, they kept describing
+ the old method after ``describe_certificate`` had already started
+ reporting the new one.
+ """
+ cert = _acm._certificates.get(physical_id)
+ if cert is None or any(old_props.get(p) != new_props.get(p)
+ for p in _ACM_REPLACEMENT_PROPERTIES):
+ created = _acm_certificate_create(
+ logical_id or physical_id, new_props, stack_name)
+ if cert is not None:
+ _delete_predecessor(_acm_certificate_delete, physical_id, old_props)
+ return created
+
+ method = new_props.get("ValidationMethod", "DNS")
+ if method != cert.get("ValidationMethod"):
+ sans = cert.get("SubjectAlternativeNames") or [cert["DomainName"]]
+ cert["DomainValidationOptions"] = [
+ _acm._validation_options(d, method) for d in sans
+ ]
+ cert["ValidationMethod"] = method
+ _acm._update_options({
+ "CertificateArn": physical_id,
+ "Options": {
+ "CertificateTransparencyLoggingPreference":
+ (new_props.get("CertificateTransparencyLoggingPreference")
+ or (new_props.get("Options") or {}).get(
+ "CertificateTransparencyLoggingPreference")
+ or "ENABLED"),
+ },
+ })
+ _reconcile_tag_list(cert.setdefault("Tags", []), old_props, new_props)
+ return physical_id, {"CertificateArn": physical_id, "Arn": physical_id}
+
+
# ---------------------------------------------------------------------------
# ELBv2 TargetGroup + ListenerRule
# ---------------------------------------------------------------------------
@@ -7432,7 +7758,10 @@ def _elbv2_target_group_create(logical_id, props, stack_name):
}
_alb._tgs[arn] = tg
_alb._targets[arn] = []
- _alb._tags[arn] = {t["Key"]: t["Value"] for t in (props.get("Tags") or [])}
+ # The ALB tag store holds a list of {Key, Value} for every resource type,
+ # which is what DescribeTags iterates; a map here made that call raise on
+ # any CloudFormation-created target group.
+ _alb._tags[arn] = _elbv2_tags(props.get("Tags"))
_alb._tg_attrs[arn] = [
{"Key": a.get("Key", ""), "Value": a.get("Value", "")}
for a in (props.get("TargetGroupAttributes") or [])
@@ -7455,6 +7784,75 @@ def _elbv2_target_group_delete(physical_id, props):
_alb._tg_attrs.pop(physical_id, None)
+# The health-check properties the target group stores, with the value the
+# create applies when the template does not declare one, so a dropped
+# property goes back to that default instead of keeping the old value.
+_ELBV2_TG_HEALTH_CHECK = {
+ "HealthCheckProtocol": ("HealthCheckProtocol", "HTTP", str),
+ "HealthCheckPort": ("HealthCheckPort", "traffic-port", str),
+ "HealthCheckPath": ("HealthCheckPath", "/", str),
+ "HealthCheckIntervalSeconds": ("HealthCheckIntervalSeconds", 30, int),
+ "HealthCheckTimeoutSeconds": ("HealthCheckTimeoutSeconds", 5, int),
+ "HealthyThresholdCount": ("HealthyThresholdCount", 5, int),
+ "UnhealthyThresholdCount": ("UnhealthyThresholdCount", 2, int),
+}
+
+
+def _elbv2_target_group_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update a target group in place, keeping its ARN (what ``Ref`` returns)
+ and the targets registered in it. The health-check properties,
+ ``Matcher``, ``TargetGroupAttributes`` and ``Tags`` are "Update requires:
+ No interruption" on the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html);
+ ``Name``, ``Port``, ``Protocol``, ``ProtocolVersion``, ``TargetType``,
+ ``VpcId`` and ``IpAddressType`` require replacement. A changed name
+ replaces through the shared prologue; one of the others under an
+ unchanged custom name is refused by ``_custom_named_replacement_error``,
+ as CloudFormation refuses to replace a custom-named resource, and this
+ name "must be unique per region per account". Under a generated name the
+ replacement is performed here, and the registered targets go with the old
+ group.
+ """
+ name = new_props.get("Name") or _physical_name(
+ stack_name, logical_id or physical_id, max_len=32)
+ tg = _alb._tgs.get(physical_id)
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ name, tg.get("TargetGroupName") if tg else None,
+ _elbv2_target_group_create, _elbv2_target_group_delete,
+ )
+ if replaced is not None:
+ return replaced
+ if _requires_replacement("AWS::ElasticLoadBalancingV2::TargetGroup",
+ old_props, new_props):
+ # Port, Protocol, ProtocolVersion, TargetType, VpcId and IpAddressType
+ # replace; the targets registered in the old group stay with it, as on
+ # AWS, and its ARN carries a fresh id, so Retain can keep it.
+ created = _elbv2_target_group_create(
+ logical_id or physical_id, new_props, stack_name)
+ _delete_predecessor(_elbv2_target_group_delete, physical_id, old_props)
+ return created
+
+ for prop, (field, default, cast) in _ELBV2_TG_HEALTH_CHECK.items():
+ value = new_props.get(prop, default)
+ tg[field] = cast(value if value not in (None, "") else default)
+ enabled = new_props.get("HealthCheckEnabled", True)
+ tg["HealthCheckEnabled"] = (
+ enabled if isinstance(enabled, bool) else str(enabled).lower() == "true")
+ tg["Matcher"] = {"HttpCode": (new_props.get("Matcher") or {}).get("HttpCode", "200")}
+ _elbv2_merge_attributes(
+ _alb._tg_attrs.setdefault(physical_id, []),
+ new_props.get("TargetGroupAttributes"),
+ )
+ _reconcile_tag_list(_alb._tags.setdefault(physical_id, []), old_props, new_props)
+ return physical_id, {
+ "TargetGroupArn": physical_id,
+ "TargetGroupName": tg["TargetGroupName"],
+ "TargetGroupFullName": _alb._target_group_full_name_from_arn(physical_id),
+ }
+
+
def _flatten_listener_rule_conditions(cfn_conditions):
"""CFN ListenerRule Conditions accept both the flat `{Field, Values}` shape
and the per-field nested config form (`PathPatternConfig.Values`,
@@ -7505,22 +7903,12 @@ def _elbv2_listener_rule_create(logical_id, props, stack_name):
f":listener-rule/app/{lb_name}/{lb_id}/{l_id}/{rule_id}")
# CFN Actions: list of dicts with Type, Order, TargetGroupArn / RedirectConfig
# / FixedResponseConfig. MS' native shape matches this directly.
- actions = []
- for i, a in enumerate(props.get("Actions") or [], start=1):
- record = {"Type": a.get("Type", "forward"), "Order": int(a.get("Order", i))}
- if a.get("TargetGroupArn"):
- record["TargetGroupArn"] = a["TargetGroupArn"]
- if a.get("RedirectConfig"):
- record["RedirectConfig"] = dict(a["RedirectConfig"])
- if a.get("FixedResponseConfig"):
- record["FixedResponseConfig"] = dict(a["FixedResponseConfig"])
- actions.append(record)
rule = {
"RuleArn": rule_arn,
"ListenerArn": l_arn,
"Priority": str(props.get("Priority", 1)),
"Conditions": _flatten_listener_rule_conditions(props.get("Conditions") or []),
- "Actions": actions,
+ "Actions": _elbv2_listener_actions(props, None, prop="Actions"),
"IsDefault": False,
}
_alb._rules[rule_arn] = rule
@@ -7531,6 +7919,30 @@ def _elbv2_listener_rule_delete(physical_id, props):
_alb._rules.pop(physical_id, None)
+def _elbv2_listener_rule_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update a listener rule in place, keeping its ARN (what ``Ref``
+ returns). ``Actions``, ``Conditions`` and ``Priority`` are "Update
+ requires: No interruption" and only ``ListenerArn`` requires replacement
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listenerrule.html);
+ a rule ARN carries its listener, so moving one is a replacement under a
+ new physical id. ``Tags`` are left alone, because the create handler does
+ not store a rule's tags either.
+ """
+ rule = _alb._rules.get(physical_id)
+ if rule is None or rule.get("ListenerArn") != new_props.get("ListenerArn"):
+ created = _elbv2_listener_rule_create(
+ logical_id or physical_id, new_props, stack_name)
+ if rule is not None:
+ _delete_predecessor(_elbv2_listener_rule_delete, physical_id, old_props)
+ return created
+
+ rule["Priority"] = str(new_props.get("Priority", 1))
+ rule["Conditions"] = _flatten_listener_rule_conditions(new_props.get("Conditions") or [])
+ rule["Actions"] = _elbv2_listener_actions(new_props, None, prop="Actions")
+ return physical_id, {"RuleArn": physical_id}
+
+
# ---------------------------------------------------------------------------
# Route53 HostedZone
# ---------------------------------------------------------------------------
@@ -7560,6 +7972,38 @@ def _r53_hosted_zone_delete(physical_id, props):
_r53._records.pop(physical_id, None)
+def _r53_hosted_zone_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update a hosted zone in place, keeping its id (what ``Ref`` and
+ ``Fn::GetAtt Id`` return) and every record in it. ``HostedZoneConfig`` is
+ "Update requires: No interruption" on the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-route53-hostedzone.html),
+ so a changed comment is written on the zone the stack already has; the
+ create handler instead minted a second zone with a fresh id and the
+ default NS and SOA records only, which orphaned every
+ ``AWS::Route53::RecordSet`` that had been created in the first one. Only
+ ``Name`` requires replacement, and a hosted-zone name is not unique, so
+ the new zone is created before the old one is removed.
+ """
+ zone_name = new_props.get("Name", "")
+ if not zone_name.endswith("."):
+ zone_name += "."
+ zone = _r53._zones.get(physical_id)
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ zone_name, zone.get("name") if zone else None,
+ _r53_hosted_zone_create, _r53_hosted_zone_delete,
+ )
+ if replaced is not None:
+ return replaced
+
+ zone["comment"] = (new_props.get("HostedZoneConfig") or {}).get("Comment", "")
+ return physical_id, {
+ "Id": physical_id,
+ "NameServers": ["ns-1.awsdns-01.org", "ns-2.awsdns-02.co.uk"],
+ }
+
+
def _r53_normalize_hosted_zone_id(zone_ref: str) -> str:
if not zone_ref:
return ""
@@ -8226,15 +8670,84 @@ def _apigw_v2_authorizer_delete(physical_id, props):
# SES EmailIdentity
# ---------------------------------------------------------------------------
+def _ses_email_identity_apply(identity, props):
+ """Write the identity into both SES stores. ``AWS::SES::EmailIdentity``
+ is the v2 resource type, so an identity that lives in the v1 store alone
+ is invisible to ``GetEmailIdentity`` and ``ListEmailIdentities``, the
+ calls a template's own resource is read back with. The two records hold
+ the attributes each API serves; the members the template does not declare
+ keep the defaults ``CreateEmailIdentity`` applies."""
+ v1 = _ses._identities.get(identity) or _ses._make_identity(
+ identity, "Domain" if "@" not in identity else "EmailAddress")
+ feedback = props.get("FeedbackAttributes") or {}
+ if "EmailForwardingEnabled" in feedback:
+ v1["FeedbackForwardingEnabled"] = bool(feedback["EmailForwardingEnabled"])
+ dkim = props.get("DkimAttributes") or {}
+ if "SigningEnabled" in dkim:
+ v1["DkimEnabled"] = bool(dkim["SigningEnabled"])
+ _ses._identities[identity] = v1
+
+ v2 = _ses_v2._identities.get(identity) or {
+ "EmailIdentity": identity,
+ "IdentityType": "DOMAIN" if "@" not in identity else "EMAIL_ADDRESS",
+ "VerifiedForSendingStatus": True,
+ "DkimAttributes": {"SigningEnabled": False, "Status": "NOT_STARTED", "Tokens": []},
+ "MailFromAttributes": {"BehaviorOnMxFailure": "USE_DEFAULT_VALUE"},
+ "Tags": [],
+ "CreatedTimestamp": now_iso(),
+ }
+ v2["DkimAttributes"] = {
+ **v2["DkimAttributes"],
+ "SigningEnabled": bool(dkim.get("SigningEnabled", v2["DkimAttributes"]["SigningEnabled"])),
+ }
+ mail_from = props.get("MailFromAttributes") or {}
+ v2["MailFromAttributes"] = {
+ "MailFromDomain": mail_from.get("MailFromDomain", ""),
+ "BehaviorOnMxFailure": mail_from.get("BehaviorOnMxFailure", "USE_DEFAULT_VALUE"),
+ }
+ v2["ConfigurationSetName"] = (
+ props.get("ConfigurationSetAttributes") or {}).get("ConfigurationSetName", "")
+ v2["FeedbackForwardingStatus"] = bool(feedback.get("EmailForwardingEnabled", True))
+ v2["Tags"] = [{"Key": k, "Value": v} for k, v in _tag_map(props.get("Tags")).items()]
+ _ses_v2._identities[identity] = v2
+ return v2
+
+
def _ses_email_identity_create(logical_id, props, stack_name):
identity = props.get("EmailIdentity", "")
- _ses._identities[identity] = _ses._make_identity(identity,
- "Domain" if "@" not in identity else "EmailAddress")
+ _ses_email_identity_apply(identity, props)
return identity, {"EmailIdentity": identity}
def _ses_email_identity_delete(physical_id, props):
_ses._identities.pop(physical_id, None)
+ _ses_v2._identities.pop(physical_id, None)
+
+
+def _ses_email_identity_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update an email identity in place, keeping its verification status and
+ its DKIM tokens. ``ConfigurationSetAttributes``, ``DkimAttributes``,
+ ``FeedbackAttributes``, ``MailFromAttributes`` and ``Tags`` are "Update
+ requires: No interruption" on the resource reference and only
+ ``EmailIdentity`` requires replacement
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ses-emailidentity.html);
+ the create handler rebuilt the record from scratch, which put the
+ verification status and the DKIM tokens back to their defaults. A changed
+ identity is a replacement: the new one is verified before the old one is
+ deleted.
+ """
+ identity = new_props.get("EmailIdentity", "")
+ known = physical_id in _ses._identities or physical_id in _ses_v2._identities
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ identity, physical_id if known else None,
+ _ses_email_identity_create, _ses_email_identity_delete,
+ )
+ if replaced is not None:
+ return replaced
+ _ses_email_identity_apply(identity, new_props)
+ return physical_id, {"EmailIdentity": physical_id}
# ---------------------------------------------------------------------------
@@ -8303,6 +8816,48 @@ def _waf_web_acl_delete(physical_id, props):
_waf.delete_web_acl_record(physical_id, props.get("Scope", "REGIONAL"))
+def _waf_web_acl_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update a web ACL in place, keeping its id and ARN, so the resources
+ associated with it through ``AWS::WAFv2::WebACLAssociation`` keep
+ pointing at a live ACL. ``DefaultAction``, ``Description``, ``Rules`` and
+ ``VisibilityConfig`` are "Update requires: No interruption" on the
+ resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafv2-webacl.html);
+ ``Name`` and ``Scope`` require replacement. A changed name replaces
+ through the shared prologue; a ``Scope`` change under an unchanged
+ explicit name is refused by ``_custom_named_replacement_error``, and under
+ a generated name it is performed here. ``Tags`` are left alone on purpose:
+ the reference states that "With AWS CloudFormation, you can only add tags
+ to AWS WAF resources during resource creation".
+ """
+ name = new_props.get("Name") or _physical_name(
+ stack_name, logical_id or physical_id, max_len=128)
+ # Under the scope the ACL was created with, not the one the template now
+ # asks for: the store is keyed by the scope's home region, so the new
+ # scope addresses a different store. _waf_web_acl_delete reads old_props
+ # for the same reason.
+ acl = _waf.web_acl_record(physical_id, old_props.get("Scope", "REGIONAL"))
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ name, acl.get("Name") if acl else None,
+ _waf_web_acl_create, _waf_web_acl_delete,
+ )
+ if replaced is not None:
+ return replaced
+ if _requires_replacement("AWS::WAFv2::WebACL", old_props, new_props):
+ # The create lands the ACL in the new scope's store, the delete
+ # removes the record from the one it was created in, and the new id
+ # is a fresh uuid, so Retain can keep the predecessor.
+ created = _waf_web_acl_create(
+ logical_id or physical_id, new_props, stack_name)
+ _delete_predecessor(_waf_web_acl_delete, physical_id, old_props)
+ return created
+
+ _waf.update_web_acl_record(acl, new_props)
+ return physical_id, {"Arn": acl["ARN"], "Id": physical_id}
+
+
# ---------------------------------------------------------------------------
# CloudFront Origin Access Identity
# ---------------------------------------------------------------------------
@@ -8805,13 +9360,64 @@ def _backup_vault_delete(physical_id, props):
_backup._vaults.pop(physical_id, None)
+def _backup_vault_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update a backup vault in place, keeping its creation date and its
+ recovery-point count. Of the "Update requires: No interruption"
+ properties on the resource reference only ``BackupVaultTags`` is stored
+ by the create, so only the tags are applied here (``AccessPolicy``,
+ ``LockConfiguration`` and ``Notifications`` stay unmodelled);
+ ``BackupVaultName`` and ``EncryptionKeyArn`` require replacement
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-backup-backupvault.html).
+ Without a handler the create ran again and answered
+ ``AlreadyExistsException``, which the create handler drops, so a tag
+ change never reached the vault. A changed name replaces; a changed
+ encryption key under the unchanged, required name is refused by the
+ ``_CUSTOM_NAME_REPLACEMENT`` rule before this handler runs.
+ """
+ name = new_props.get("BackupVaultName") or _physical_name(
+ stack_name, logical_id or physical_id, max_len=50)
+ vault = _backup._vaults.get(physical_id)
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ name, vault.get("BackupVaultName") if vault else None,
+ _backup_vault_create, _backup_vault_delete,
+ )
+ if replaced is not None:
+ return replaced
+
+ _reconcile_tag_map(vault.setdefault("BackupVaultTags", {}),
+ old_props, new_props, prop="BackupVaultTags")
+ return physical_id, {
+ "BackupVaultArn": vault["BackupVaultArn"],
+ "BackupVaultName": physical_id,
+ }
+
+
+def _backup_plan_body(props):
+ """The ``CreateBackupPlan`` body for an ``AWS::Backup::BackupPlan``. The
+ CloudFormation type spells the rule list ``BackupPlanRule`` and the vault
+ of a rule ``TargetBackupVault`` where the API uses ``Rules`` and
+ ``TargetBackupVaultName``
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-backup-backupplan-backupplanresourcetype.html,
+ https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-backup-backupplan-backupruleresourcetype.html);
+ the other members carry the same names. Storing the template shape
+ verbatim left every CloudFormation plan with no rules at all when read
+ back through ``GetBackupPlan``."""
+ plan = dict(props.get("BackupPlan") or {})
+ rules = plan.pop("BackupPlanRule", None)
+ if rules is not None:
+ plan["Rules"] = [
+ {("TargetBackupVaultName" if key == "TargetBackupVault" else key): value
+ for key, value in rule.items()}
+ for rule in rules if isinstance(rule, dict)
+ ]
+ return {"BackupPlan": plan, "BackupPlanTags": _tag_map(props.get("BackupPlanTags"))}
+
+
def _backup_plan_create(logical_id, props, stack_name):
- plan_cfg = props.get("BackupPlan", {})
- tags = {t["Key"]: t["Value"] for t in props.get("BackupPlanTags", [])} if isinstance(props.get("BackupPlanTags"), list) else props.get("BackupPlanTags", {})
- body = {"BackupPlan": plan_cfg, "BackupPlanTags": tags}
- _, _, resp_bytes = _backup._create_plan(body)
- import json as _json
- resp = _json.loads(resp_bytes)
+ _, _, resp_bytes = _backup._create_plan(_backup_plan_body(props))
+ resp = json.loads(resp_bytes)
plan_id = resp["BackupPlanId"]
return plan_id, {"BackupPlanArn": resp["BackupPlanArn"], "BackupPlanId": plan_id, "VersionId": resp["VersionId"]}
@@ -8820,6 +9426,33 @@ def _backup_plan_delete(physical_id, props):
_backup._plans.pop(physical_id, None)
+def _backup_plan_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update a backup plan in place through ``UpdateBackupPlan``, keeping
+ its id (what ``Ref`` returns), its ARN and its version history. Both
+ properties of this type are "Update requires: No interruption", so it has
+ no replacement path at all
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-backup-backupplan.html);
+ the create handler minted a second plan under a fresh id and the engine
+ then deleted the first, so every ``AWS::Backup::BackupSelection`` and
+ every reader holding the old id lost it. ``VersionId`` rolls, as the call
+ does it.
+ """
+ body = _backup_plan_body(new_props)
+ status, _, resp_bytes = _backup._update_plan(physical_id, body)
+ if status >= 400:
+ raise ValueError(f"AWS::Backup::BackupPlan update failed: {resp_bytes!r}")
+ resp = json.loads(resp_bytes)
+ plan = _backup._plans[physical_id]
+ _reconcile_tag_map(plan.setdefault("Tags", {}), old_props, new_props,
+ prop="BackupPlanTags")
+ return physical_id, {
+ "BackupPlanArn": resp["BackupPlanArn"],
+ "BackupPlanId": physical_id,
+ "VersionId": resp["VersionId"],
+ }
+
+
def _s3tables_bucket_create(logical_id, props, stack_name):
name = props.get("TableBucketName") or _physical_name(stack_name, logical_id, lowercase=True, max_len=63)
arn = _s3tables._bucket_arn(name)
@@ -8969,6 +9602,12 @@ def _iot_thing_type_create(logical_id, props, stack_name):
resp = _iot._create_thing_type(name, payload)
if resp[0] >= 400:
raise ValueError(f"AWS::IoT::ThingType create failed: {resp[2]!r}")
+ if props.get("DeprecateThingType", False):
+ # A plain property of the type: a template that declares it from the
+ # start came up non-deprecated until the next update.
+ status, _headers, body = _iot._deprecate_thing_type(name, {"undoDeprecate": False})
+ if status >= 400:
+ raise ValueError(f"DeprecateThingType failed: {body}")
rec = _iot._thing_types.get(name) or {}
return name, {"Arn": rec.get("thingTypeArn", _iot._thing_type_arn(name)),
"Id": rec.get("thingTypeId", "")}
@@ -8978,6 +9617,52 @@ def _iot_thing_type_delete(physical_id, props):
_iot._thing_types.pop(physical_id, None)
+def _iot_thing_type_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update a thing type in place, keeping its id, its ARN and its creation
+ date. ``DeprecateThingType`` is "Update requires: No interruption" and
+ ``ThingTypeName`` requires replacement
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingtype.html).
+ Of ``ThingTypeProperties`` only ``Mqtt5Configuration`` updates in place,
+ the one member the page calls updatable after creation; measured on an
+ account, a template that drops it clears it. A ``ThingTypeDescription`` or
+ ``SearchableAttributes`` change is refused under a custom name by the
+ ``_CUSTOM_NAME_REPLACEMENT`` rule. Under a generated name the type is
+ deleted and re-created: the name is deterministic, so creating first
+ would collide with the predecessor. Without a handler the create ran and
+ ``CreateThingType`` answered ``ResourceAlreadyExistsException``.
+ """
+ name = new_props.get("ThingTypeName") or _physical_name(
+ stack_name, logical_id or physical_id)
+ record = _iot._thing_types.get(physical_id)
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ name, physical_id if record else None,
+ _iot_thing_type_create, _iot_thing_type_delete,
+ )
+ if replaced is not None:
+ return replaced
+ if _requires_replacement("AWS::IoT::ThingType", old_props, new_props):
+ _iot_thing_type_delete(physical_id, old_props)
+ return _iot_thing_type_create(logical_id or physical_id, new_props, stack_name)
+
+ stored = record.setdefault("thingTypeProperties", {})
+ mqtt5 = (new_props.get("ThingTypeProperties") or {}).get("Mqtt5Configuration")
+ if mqtt5:
+ stored["mqtt5Configuration"] = _pascal_to_camel(mqtt5)
+ else:
+ stored.pop("mqtt5Configuration", None)
+ deprecate = bool(new_props.get("DeprecateThingType", False))
+ if deprecate != bool(record.get("thingTypeMetadata", {}).get("deprecated")):
+ status, _headers, body = _iot._deprecate_thing_type(physical_id, {"undoDeprecate": not deprecate})
+ if status >= 400:
+ raise ValueError(f"DeprecateThingType failed: {body}")
+ return physical_id, {
+ "Arn": record.get("thingTypeArn", _iot._thing_type_arn(physical_id)),
+ "Id": record.get("thingTypeId", ""),
+ }
+
+
# --- IoT ThingGroup ---
# Ref is the thing group id (the resource reference), so the physical id is
# the id and the handlers find the record by it.
@@ -9452,11 +10137,20 @@ def _ecr_repo_update(physical_id, old_props, new_props, stack_name):
repo = _ecr._repositories.get(physical_id)
new_name = new_props.get("RepositoryName")
if repo is None or (new_name and new_name != physical_id):
- return _ecr_repo_create(physical_id, new_props, stack_name)
- for prop, key in (("ImageTagMutability", "imageTagMutability"),
- ("ImageScanningConfiguration", "imageScanningConfiguration")):
- if prop in new_props:
- repo[key] = new_props[prop]
+ # A new name is a replacement: create the new repository, then delete
+ # the old one through DeleteRepository, unless the template retains it.
+ result = _ecr_repo_create(physical_id, new_props, stack_name)
+ if repo is not None:
+ _delete_predecessor(_ecr_repo_delete, physical_id, old_props)
+ return result
+ # ImageTagMutability, ImageScanningConfiguration, LifecyclePolicy,
+ # RepositoryPolicyText and Tags update in place; EncryptionConfiguration
+ # requires replacement and stays as it is.
+ api = _ecr_cfn_to_api(new_props)
+ repo["imageTagMutability"] = api["imageTagMutability"]
+ repo["imageScanningConfiguration"] = api["imageScanningConfiguration"]
+ _reconcile_tag_list(repo.setdefault("tags", []), old_props, new_props)
+ _ecr_repo_apply_policies(physical_id, new_props)
return physical_id, {"Arn": repo["repositoryArn"], "RepositoryUri": repo["repositoryUri"]}
@@ -9849,7 +10543,12 @@ _RESOURCE_HANDLERS = {
"update": _apigw_base_path_mapping_update,
"delete": _apigw_base_path_mapping_delete,
},
- "AWS::ApiGateway::Account": {"create": _apigw_account_create, "delete": _apigw_account_delete},
+ "AWS::ApiGateway::Account": {
+ "create": _apigw_account_create,
+ "update": _apigw_account_update,
+ "update_with_logical_id": True,
+ "delete": _apigw_account_delete,
+ },
"AWS::ApiGateway::DomainName": {
"create": _apigw_domain_name_create,
"update": _apigw_domain_name_update,
@@ -9946,9 +10645,24 @@ _RESOURCE_HANDLERS = {
},
"AWS::Cognito::UserPoolDomain": {"create": _cognito_user_pool_domain_create, "delete": _cognito_user_pool_domain_delete},
"AWS::ECR::Repository": {"create": _ecr_repo_create, "update": _ecr_repo_update, "delete": _ecr_repo_delete},
- "AWS::CertificateManager::Certificate": {"create": _acm_certificate_create, "delete": _acm_certificate_delete},
- "AWS::ElasticLoadBalancingV2::TargetGroup": {"create": _elbv2_target_group_create, "delete": _elbv2_target_group_delete},
- "AWS::ElasticLoadBalancingV2::ListenerRule": {"create": _elbv2_listener_rule_create, "delete": _elbv2_listener_rule_delete},
+ "AWS::CertificateManager::Certificate": {
+ "create": _acm_certificate_create,
+ "update": _acm_certificate_update,
+ "update_with_logical_id": True,
+ "delete": _acm_certificate_delete,
+ },
+ "AWS::ElasticLoadBalancingV2::TargetGroup": {
+ "create": _elbv2_target_group_create,
+ "update": _elbv2_target_group_update,
+ "update_with_logical_id": True,
+ "delete": _elbv2_target_group_delete,
+ },
+ "AWS::ElasticLoadBalancingV2::ListenerRule": {
+ "create": _elbv2_listener_rule_create,
+ "update": _elbv2_listener_rule_update,
+ "update_with_logical_id": True,
+ "delete": _elbv2_listener_rule_delete,
+ },
"AWS::CodeBuild::Project": {"create": _codebuild_project_create, "update": _codebuild_project_update, "delete": _codebuild_project_delete},
"AWS::IAM::ManagedPolicy": {
"create": _iam_managed_policy_create,
@@ -9984,8 +10698,18 @@ _RESOURCE_HANDLERS = {
"AWS::ECS::TaskDefinition": {"create": _ecs_task_def_create, "delete": _ecs_task_def_delete},
"AWS::ECS::Service": {"create": _ecs_service_create, "delete": _ecs_service_delete},
"AWS::EC2::LaunchTemplate": {"create": _ec2_launch_template_create, "delete": _ec2_launch_template_delete},
- "AWS::ElasticLoadBalancingV2::LoadBalancer": {"create": _elbv2_load_balancer_create, "delete": _elbv2_load_balancer_delete,},
- "AWS::ElasticLoadBalancingV2::Listener": {"create": _elbv2_listener_create, "delete": _elbv2_listener_delete,},
+ "AWS::ElasticLoadBalancingV2::LoadBalancer": {
+ "create": _elbv2_load_balancer_create,
+ "update": _elbv2_load_balancer_update,
+ "update_with_logical_id": True,
+ "delete": _elbv2_load_balancer_delete,
+ },
+ "AWS::ElasticLoadBalancingV2::Listener": {
+ "create": _elbv2_listener_create,
+ "update": _elbv2_listener_update,
+ "update_with_logical_id": True,
+ "delete": _elbv2_listener_delete,
+ },
"AWS::Lambda::LayerVersion": {"create": _lambda_layer_create, "delete": _lambda_layer_delete},
"AWS::Lambda::LayerVersionPermission": {
"create": _lambda_layer_version_permission_create,
@@ -9997,7 +10721,12 @@ _RESOURCE_HANDLERS = {
"update_with_logical_id": True,
"delete": _sfn_state_machine_delete,
},
- "AWS::Route53::HostedZone": {"create": _r53_hosted_zone_create, "delete": _r53_hosted_zone_delete},
+ "AWS::Route53::HostedZone": {
+ "create": _r53_hosted_zone_create,
+ "update": _r53_hosted_zone_update,
+ "update_with_logical_id": True,
+ "delete": _r53_hosted_zone_delete,
+ },
"AWS::Route53::RecordSet": {"create": _r53_record_set_create, "update": _r53_record_set_update, "delete": _r53_record_set_delete},
"AWS::ApiGatewayV2::Api": {
"create": _apigw_v2_api_create,
@@ -10024,10 +10753,20 @@ _RESOURCE_HANDLERS = {
"delete": _apigw_v2_route_delete,
},
"AWS::ApiGatewayV2::Authorizer": {"create": _apigw_v2_authorizer_create, "update": _apigw_v2_authorizer_update, "delete": _apigw_v2_authorizer_delete},
- "AWS::SES::EmailIdentity": {"create": _ses_email_identity_create, "delete": _ses_email_identity_delete},
+ "AWS::SES::EmailIdentity": {
+ "create": _ses_email_identity_create,
+ "update": _ses_email_identity_update,
+ "update_with_logical_id": True,
+ "delete": _ses_email_identity_delete,
+ },
"AWS::SES::ConfigurationSet": {"create": _ses_configuration_set_create, "delete": _ses_configuration_set_delete},
"AWS::SES::ConfigurationSetEventDestination": {"create": _ses_configuration_set_event_destination_create, "delete": _ses_configuration_set_event_destination_delete},
- "AWS::WAFv2::WebACL": {"create": _waf_web_acl_create, "delete": _waf_web_acl_delete},
+ "AWS::WAFv2::WebACL": {
+ "create": _waf_web_acl_create,
+ "update": _waf_web_acl_update,
+ "update_with_logical_id": True,
+ "delete": _waf_web_acl_delete,
+ },
"AWS::CloudFront::CloudFrontOriginAccessIdentity": {
"create": _cf_oai_create,
"update": _cf_oai_update,
@@ -10089,7 +10828,12 @@ _RESOURCE_HANDLERS = {
"update_with_logical_id": True,
"delete": _iot_topic_rule_delete,
},
- "AWS::IoT::ThingType": {"create": _iot_thing_type_create, "delete": _iot_thing_type_delete},
+ "AWS::IoT::ThingType": {
+ "create": _iot_thing_type_create,
+ "update": _iot_thing_type_update,
+ "update_with_logical_id": True,
+ "delete": _iot_thing_type_delete,
+ },
"AWS::IoT::ThingGroup": {
"create": _iot_thing_group_create,
"update": _iot_thing_group_update,
@@ -10137,8 +10881,18 @@ _RESOURCE_HANDLERS = {
"AWS::EKS::Cluster": {"create": _eks_cluster_create, "delete": _eks_cluster_delete},
"AWS::EKS::Nodegroup": {"create": _eks_nodegroup_create, "delete": _eks_nodegroup_delete},
# AWS Backup
- "AWS::Backup::BackupVault": {"create": _backup_vault_create, "delete": _backup_vault_delete},
- "AWS::Backup::BackupPlan": {"create": _backup_plan_create, "delete": _backup_plan_delete},
+ "AWS::Backup::BackupVault": {
+ "create": _backup_vault_create,
+ "update": _backup_vault_update,
+ "update_with_logical_id": True,
+ "delete": _backup_vault_delete,
+ },
+ "AWS::Backup::BackupPlan": {
+ "create": _backup_plan_create,
+ "update": _backup_plan_update,
+ "update_with_logical_id": True,
+ "delete": _backup_plan_delete,
+ },
# CDK metadata — safe to ignore
"AWS::CDK::Metadata": {"create": lambda lid, props, sn: (f"CDKMetadata-{lid}", {}), "delete": lambda pid, props: None},
# AutoScaling
diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.py
index 86c9e879..00a0c86a 100644
--- a/ministack/services/cloudformation/stacks.py
+++ b/ministack/services/cloudformation/stacks.py
@@ -20,6 +20,7 @@ from .engine import (
_topological_sort,
)
from .provisioners import (
+ _DEFERRED_PREDECESSOR_DELETES,
_RETAIN_REPLACED,
_RETAINING_POLICIES,
_delete_resource,
@@ -350,6 +351,8 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
new_tagged = _with_stack_tags(
resource_type, resolved_props, stack_tags,
stack_name, stack_id, logical_id)
+ pending_deletes = []
+ deferred_token = _DEFERRED_PREDECESSOR_DELETES.set(pending_deletes)
try:
if _is_custom_resource(resource_type):
physical_id, attrs = await run_reentrant(
@@ -362,14 +365,16 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
stack_name, logical_id, old_attrs
)
finally:
+ _DEFERRED_PREDECESSOR_DELETES.reset(deferred_token)
_RETAIN_REPLACED.reset(token)
- if physical_id != old_pid:
- # A changed physical id is a replacement. Real
- # CloudFormation deletes the predecessor in the
- # UPDATE_COMPLETE_CLEANUP phase; without this the old
- # resource leaked forever, still holding its data.
+ if physical_id != old_pid or pending_deletes:
+ # A changed physical id, or a predecessor delete the
+ # handler queued, is a replacement. Real CloudFormation
+ # deletes the predecessor in the UPDATE_COMPLETE_CLEANUP
+ # phase and keeps it when the update rolls back.
replaced_resources.append(
- (logical_id, resource_type, old_pid, old_props))
+ (logical_id, resource_type, old_pid, physical_id,
+ old_props, pending_deletes))
else:
new_tagged = _with_stack_tags(
resource_type, resolved_props, stack_tags,
@@ -407,10 +412,35 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
_add_event(stack_id, stack_name, logical_id, resource_type,
f"{status_prefix}_COMPLETE", physical_id=physical_id)
+ resolved_outputs: list = []
+ new_exports: dict = {}
+ if not failed:
+ try:
+ # A resource the update removes is still recorded here (its delete
+ # runs below); an output that reads it must fail, as on AWS.
+ surviving = {k: v for k, v in provisioned_resources.items() if k not in to_remove}
+ resolved_outputs, new_exports = _resolve_stack_outputs(
+ outputs_defs, conditions, surviving, param_values,
+ mappings, stack_name, stack_id)
+ except Exception as exc:
+ # An output that cannot be resolved -- typically Fn::GetAtt to an
+ # attribute the resource does not expose -- fails the operation
+ # after every resource was created. Real CloudFormation rolls back
+ # at exactly this point, with the resolution error as the reason.
+ logger.error("Failed to resolve outputs of %s: %s", stack_name, exc)
+ failed = True
+ fail_reason = str(exc)
+ _add_event(stack_id, stack_name, stack_name,
+ "AWS::CloudFormation::Stack", f"{status_prefix}_FAILED",
+ fail_reason, stack_id)
+
# Replacement cleanup (update case): delete each replaced resource's
- # predecessor, as real CloudFormation does after UPDATE_COMPLETE.
+ # predecessor, as real CloudFormation does after UPDATE_COMPLETE, in
+ # reverse order so a dependent goes before what it depends on. Nothing
+ # is deleted before this point, so a rollback keeps the old resources.
if not failed and replaced_resources:
- for logical_id, rtype, old_pid, old_props in replaced_resources:
+ for (logical_id, rtype, old_pid, new_pid, old_props,
+ pending_deletes) in reversed(replaced_resources):
policy = _resource_policy(
resources_defs.get(logical_id), "UpdateReplacePolicy",
provisioned_resources, param_values, conditions, mappings,
@@ -418,10 +448,17 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
if policy in _RETAINING_POLICIES:
# The predecessor leaves CloudFormation's scope and keeps
# existing, as on AWS (a DELETE_SKIPPED event, no delete call).
- _add_event(stack_id, stack_name, logical_id, rtype,
- "DELETE_SKIPPED", physical_id=old_pid)
+ if new_pid != old_pid:
+ _add_event(stack_id, stack_name, logical_id, rtype,
+ "DELETE_SKIPPED", physical_id=old_pid)
continue
try:
+ # The handler's own delete first: it knows the old record's
+ # key where the physical id does not carry it.
+ for delete_fn, args, kwargs in pending_deletes:
+ delete_fn(*args, **kwargs)
+ if new_pid == old_pid:
+ continue
if _is_custom_resource(rtype):
await run_reentrant(
_delete_resource, rtype, old_pid, old_props,
@@ -484,25 +521,6 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
await asyncio.sleep(0)
- resolved_outputs: list = []
- new_exports: dict = {}
- if not failed:
- try:
- resolved_outputs, new_exports = _resolve_stack_outputs(
- outputs_defs, conditions, provisioned_resources, param_values,
- mappings, stack_name, stack_id)
- except Exception as exc:
- # An output that cannot be resolved -- typically Fn::GetAtt to an
- # attribute the resource does not expose -- fails the operation
- # after every resource was created. Real CloudFormation rolls back
- # at exactly this point, with the resolution error as the reason.
- logger.error("Failed to resolve outputs of %s: %s", stack_name, exc)
- failed = True
- fail_reason = str(exc)
- _add_event(stack_id, stack_name, stack_name,
- "AWS::CloudFormation::Stack", f"{status_prefix}_FAILED",
- fail_reason, stack_id)
-
if failed:
if disable_rollback:
stack["StackStatus"] = f"{status_prefix}_FAILED"
@@ -524,19 +542,22 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
previous_stack.get("_resources", {})
if is_update and previous_stack else {}
)
+ replaced_ids = {entry[0] for entry in replaced_resources}
for logical_id in reversed(created_in_this_run):
res = provisioned_resources.get(logical_id, {})
rtype = res.get("ResourceType", "")
pid = res.get("PhysicalResourceId", "")
res_props = res.get("Properties", {})
prev = previous_resources.get(logical_id)
- if prev is not None and prev.get("PhysicalResourceId") == pid:
+ if (prev is not None and prev.get("PhysicalResourceId") == pid
+ and logical_id not in replaced_ids):
# The resource existed before this update and kept its
# identity (untouched, or updated in place), so it is not
# something this run created: deleting it would destroy a
# resource the restored stack still records. Only new
- # resources and replacements under a new physical id are
- # undone. An in-place change is not reverted here.
+ # resources and replacements are undone, a replacement
+ # under an unchanged id by its new properties. An in-place
+ # change is not reverted here.
continue
policy = _resource_policy(
resources_defs.get(logical_id), "DeletionPolicy",
diff --git a/ministack/services/waf.py b/ministack/services/waf.py
index df996766..772578d3 100644
--- a/ministack/services/waf.py
+++ b/ministack/services/waf.py
@@ -229,6 +229,24 @@ def create_web_acl_record(name, scope, props):
return uid, arn, record
+def web_acl_record(uid, scope):
+ """The stored web ACL, or None. The CloudFormation provisioner reads it
+ to update an ACL in place."""
+ return _resource_from_scope(_web_acls, uid, scope)
+
+
+def update_web_acl_record(acl, props):
+ """Apply the members ``create_web_acl_record`` stores to an existing web
+ ACL and roll its lock token, as ``UpdateWebACL`` does. The ACL keeps its
+ id, ARN and tags."""
+ acl["Description"] = props.get("Description", "")
+ acl["DefaultAction"] = props.get("DefaultAction", {"Allow": {}})
+ acl["Rules"] = props.get("Rules", [])
+ acl["VisibilityConfig"] = props.get("VisibilityConfig", {})
+ acl["LockToken"] = new_uuid()
+ return acl
+
+
def delete_web_acl_record(uid, scope):
acl = _web_acls.pop_scoped(get_account_id(), _scope_home_region(scope), uid, None)
if acl:
diff --git a/tests/conftest.py b/tests/conftest.py
index 7fd5a67f..a9db94de 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -415,6 +415,11 @@ def sts_as_role(sts):
return _make
[email protected](scope="session")
+def backup():
+ return make_client("backup")
+
+
@pytest.fixture(scope="session")
def sm():
return make_client("secretsmanager")
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 393574cf..d02d13e8 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -5524,6 +5524,152 @@ def test_cfn_cdk_bootstrap_resources(cfn, s3, ecr):
cfn.delete_stack(StackName="CDKToolkit-v44")
+
+def _cfn_ecr_template(name, *, v2=False, policies=True, empty_on_delete=None):
+ props = {
+ "RepositoryName": name,
+ "ImageTagMutability": "MUTABLE" if v2 else "IMMUTABLE",
+ "ImageScanningConfiguration": {"ScanOnPush": not v2},
+ "EncryptionConfiguration": {"EncryptionType": "AES256"},
+ "Tags": [{"Key": "stage", "Value": "v2" if v2 else "v1"}]
+ + ([] if v2 else [{"Key": "dropme", "Value": "x"}]),
+ }
+ if policies:
+ props["LifecyclePolicy"] = {"LifecyclePolicyText": json.dumps({"rules": [{
+ "rulePriority": 1, "selection": {
+ "tagStatus": "untagged", "countType": "sinceImagePushed",
+ "countUnit": "days", "countNumber": 30 if v2 else 14},
+ "action": {"type": "expire"}}]})}
+ props["RepositoryPolicyText"] = {"Version": "2012-10-17", "Statement": [{
+ "Sid": "pull", "Effect": "Allow",
+ "Principal": {"AWS": "arn:aws:iam::000000000000:root"},
+ "Action": ["ecr:BatchGetImage"]}]}
+ if empty_on_delete is not None:
+ props["EmptyOnDelete"] = empty_on_delete
+ return json.dumps({"Resources": {"Repo": {"Type": "AWS::ECR::Repository",
+ "Properties": props}}})
+
+
+def _ecr_lifecycle_days(ecr, name):
+ text = ecr.get_lifecycle_policy(repositoryName=name)["lifecyclePolicyText"]
+ return json.loads(text)["rules"][0]["selection"]["countNumber"]
+
+
+def test_cfn_ecr_repository_reads_back_and_updates_in_place(cfn, ecr):
+ """Every property reads back through the ECR API as the API writes it:
+ the scanning and encryption settings in camelCase, the lifecycle and
+ repository policies from their own calls, the tags with the three
+ aws:cloudformation tags. An update applies all but the encryption in
+ place, keeps createdAt, removes a dropped tag and a dropped policy."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = name = f"cfn-ecr-{uid}"
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_ecr_template(name))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ repo = ecr.describe_repositories(repositoryNames=[name])["repositories"][0]
+ assert repo["imageTagMutability"] == "IMMUTABLE"
+ assert repo["imageScanningConfiguration"] == {"scanOnPush": True}
+ assert repo["encryptionConfiguration"] == {"encryptionType": "AES256"}
+ assert _ecr_lifecycle_days(ecr, name) == 14
+ policy = json.loads(ecr.get_repository_policy(repositoryName=name)["policyText"])
+ assert policy["Statement"][0]["Sid"] == "pull"
+ tags = {t["Key"]: t["Value"] for t in ecr.list_tags_for_resource(
+ resourceArn=repo["repositoryArn"])["tags"]}
+ assert tags == {"stage": "v1", "dropme": "x", **_system_tags(stack, "Repo")}
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=_cfn_ecr_template(name, v2=True))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ after = ecr.describe_repositories(repositoryNames=[name])["repositories"][0]
+ assert after["createdAt"] == repo["createdAt"]
+ assert after["imageTagMutability"] == "MUTABLE"
+ assert after["imageScanningConfiguration"] == {"scanOnPush": False}
+ assert _ecr_lifecycle_days(ecr, name) == 30
+ tags = {t["Key"]: t["Value"] for t in ecr.list_tags_for_resource(
+ resourceArn=repo["repositoryArn"])["tags"]}
+ assert tags == {"stage": "v2", **_system_tags(stack, "Repo")}
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_ecr_template(
+ name, v2=True, policies=False))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ with pytest.raises(ClientError, match="LifecyclePolicyNotFoundException"):
+ ecr.get_lifecycle_policy(repositoryName=name)
+ with pytest.raises(ClientError, match="RepositoryPolicyNotFoundException"):
+ ecr.get_repository_policy(repositoryName=name)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
[email protected]("empty_on_delete", [None, True])
+def test_cfn_ecr_repository_takes_images_and_deletes_like_the_api(
+ cfn, ecr, empty_on_delete):
+ """A stack's repository accepts PutImage. Deleting the stack goes through
+ DeleteRepository: a repository with images fails the delete unless
+ EmptyOnDelete is true, and a deleted one leaves no images or policies
+ behind for a repository created later under the same name."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = name = f"cfn-ecr-del-{uid}"
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_ecr_template(
+ name, empty_on_delete=empty_on_delete))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ ecr.put_image(repositoryName=name, imageTag="v1",
+ imageManifest='{"schemaVersion": 2}')
+ assert len(ecr.describe_images(repositoryName=name)["imageDetails"]) == 1
+
+ cfn.delete_stack(StackName=stack_name)
+ stack = _wait_stack(cfn, stack_name)
+ if empty_on_delete is None:
+ assert stack["StackStatus"] == "DELETE_FAILED"
+ assert f"The repository with name '{name}' is not empty" in \
+ _stack_event_reasons(cfn, stack_name)
+ assert len(ecr.describe_images(repositoryName=name)["imageDetails"]) == 1
+ ecr.delete_repository(repositoryName=name, force=True)
+ return
+ assert stack["StackStatus"] == "DELETE_COMPLETE"
+ ecr.create_repository(repositoryName=name)
+ try:
+ assert ecr.describe_images(repositoryName=name)["imageDetails"] == []
+ with pytest.raises(ClientError, match="LifecyclePolicyNotFoundException"):
+ ecr.get_lifecycle_policy(repositoryName=name)
+ with pytest.raises(ClientError, match="RepositoryPolicyNotFoundException"):
+ ecr.get_repository_policy(repositoryName=name)
+ finally:
+ ecr.delete_repository(repositoryName=name, force=True)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_ecr_repository_rename_deletes_the_old_repository(cfn, ecr):
+ """RepositoryName is create-only: a new name creates the new repository
+ and deletes the old one through DeleteRepository once the update succeeds."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-ecr-ren-{uid}"
+ old_name, new_name = f"cfn-ecr-old-{uid}", f"cfn-ecr-new-{uid}"
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_ecr_template(old_name))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_ecr_template(new_name))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", _stack_event_reasons(cfn, stack_name)
+ names = {r["repositoryName"] for r in ecr.describe_repositories()["repositories"]}
+ assert new_name in names and old_name not in names
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ for name in (old_name, new_name):
+ try:
+ ecr.delete_repository(repositoryName=name, force=True)
+ except ClientError:
+ pass
+
+
def test_cfn_ec2_launch_template(cfn, ec2):
"""CloudFormation should provision and delete an EC2 LaunchTemplate."""
template = {
@@ -5890,175 +6036,1184 @@ def test_cfn_elbv2_load_balancer_and_listener(cfn, elbv2):
assert lbs[0]["Scheme"] == "internal"
assert lbs[0]["Type"] == "application"
- listeners = elbv2.describe_listeners(LoadBalancerArn=lb_arn)["Listeners"]
- assert len(listeners) == 1
- listener = listeners[0]
- assert listener["Port"] == 443
- assert listener["Protocol"] == "HTTPS"
- assert listener["DefaultActions"][0]["Type"] == "fixed-response"
+ listeners = elbv2.describe_listeners(LoadBalancerArn=lb_arn)["Listeners"]
+ assert len(listeners) == 1
+ listener = listeners[0]
+ assert listener["Port"] == 443
+ assert listener["Protocol"] == "HTTPS"
+ assert listener["DefaultActions"][0]["Type"] == "fixed-response"
+
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+ with pytest.raises(ClientError) as exc:
+ elbv2.describe_load_balancers(Names=[lb_name])
+ assert exc.value.response["Error"]["Code"] == "LoadBalancerNotFound"
+
+
+def test_cfn_cloudwatch_alarm_lifecycle(cfn, cw):
+ """CloudFormation creates a metric alarm and removes it on stack delete."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cwal-{uid}"
+ alarm_name = f"cfn-cw-alarm-{uid}"
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "CpuAlarm": {
+ "Type": "AWS::CloudWatch::Alarm",
+ "Properties": {
+ "AlarmName": alarm_name,
+ "AlarmDescription": "CFN integration test",
+ "MetricName": "CPUUtilization",
+ "Namespace": f"CfnCwTest/{uid}",
+ "Statistic": "Average",
+ "Period": 60,
+ "EvaluationPeriods": 1,
+ "Threshold": 80.0,
+ "ComparisonOperator": "GreaterThanThreshold",
+ "TreatMissingData": "notBreaching",
+ },
+ },
+ },
+ "Outputs": {
+ "AlarmNameOut": {"Value": {"Ref": "CpuAlarm"}},
+ "AlarmArnOut": {"Value": {"Fn::GetAtt": ["CpuAlarm", "Arn"]}},
+ },
+ }
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+
+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack.get("Outputs", [])}
+ assert outputs["AlarmNameOut"] == alarm_name
+ assert outputs["AlarmArnOut"].endswith(f":alarm:{alarm_name}")
+
+ resp = cw.describe_alarms(AlarmNames=[alarm_name])
+ assert len(resp["MetricAlarms"]) == 1
+ a = resp["MetricAlarms"][0]
+ assert a["MetricName"] == "CPUUtilization"
+ assert a["Namespace"] == f"CfnCwTest/{uid}"
+ assert float(a["Threshold"]) == 80.0
+
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+ resp2 = cw.describe_alarms(AlarmNames=[alarm_name])
+ assert resp2["MetricAlarms"] == []
+
+
+def test_cfn_cloudwatch_dashboard_lifecycle(cfn, cw):
+ """CloudFormation creates, updates, and removes a CloudWatch dashboard."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cwdash-{uid}"
+ dashboard_name = f"cfn-dashboard-{uid}"
+ replacement_name = f"cfn-dashboard-replaced-{uid}"
+ body = json.dumps({"widgets": [{"type": "text", "properties": {"markdown": "Created"}}]})
+ updated_body = json.dumps({"widgets": [{"type": "text", "properties": {"markdown": "Updated"}}]})
+
+ def template(dashboard_body, name=dashboard_name):
+ return {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Dashboard": {
+ "Type": "AWS::CloudWatch::Dashboard",
+ "Properties": {
+ "DashboardName": name,
+ "DashboardBody": dashboard_body,
+ },
+ },
+ },
+ "Outputs": {
+ "DashboardName": {"Value": {"Ref": "Dashboard"}},
+ },
+ }
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template(body)))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+ assert stack["Outputs"][0]["OutputValue"] == dashboard_name
+ assert cw.get_dashboard(DashboardName=dashboard_name)["DashboardBody"] == body
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(template(updated_body)))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE"
+ assert cw.get_dashboard(DashboardName=dashboard_name)["DashboardBody"] == updated_body
+
+ cfn.update_stack(
+ StackName=stack_name,
+ TemplateBody=json.dumps(template(updated_body, replacement_name)),
+ )
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE"
+ assert stack["Outputs"][0]["OutputValue"] == replacement_name
+ with pytest.raises(ClientError) as exc:
+ cw.get_dashboard(DashboardName=dashboard_name)
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFound"
+ assert cw.get_dashboard(DashboardName=replacement_name)["DashboardBody"] == updated_body
+
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+ with pytest.raises(ClientError) as exc:
+ cw.get_dashboard(DashboardName=replacement_name)
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFound"
+
+
+def test_cfn_route53_hosted_zone_and_record_set(cfn, r53):
+ """CloudFormation provisions Route53 HostedZone + RecordSet and removes records on delete."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-r53rs-{uid}"
+ zone_name = f"cfnrs{uid}.com."
+ record_name = f"www.cfnrs{uid}.com"
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Zone": {
+ "Type": "AWS::Route53::HostedZone",
+ "Properties": {"Name": zone_name},
+ },
+ "WebA": {
+ "Type": "AWS::Route53::RecordSet",
+ "Properties": {
+ "HostedZoneId": {"Ref": "Zone"},
+ "Name": record_name,
+ "Type": "A",
+ "TTL": 300,
+ "ResourceRecords": [{"Value": "198.51.100.10"}],
+ },
+ },
+ },
+ "Outputs": {
+ "RecordFqdn": {"Value": {"Ref": "WebA"}},
+ },
+ }
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+
+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack.get("Outputs", [])}
+ assert outputs["RecordFqdn"].endswith(".")
+
+ resources = {r["LogicalResourceId"]: r for r in cfn.describe_stack_resources(StackName=stack_name)["StackResources"]}
+ zone_id = resources["Zone"]["PhysicalResourceId"]
+
+ rrs = r53.list_resource_record_sets(HostedZoneId=zone_id)["ResourceRecordSets"]
+ a_rrs = [r for r in rrs if r["Type"] == "A" and "cfnrs" in r["Name"]]
+ assert len(a_rrs) == 1
+ assert a_rrs[0]["ResourceRecords"][0]["Value"] == "198.51.100.10"
+
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+
+ with pytest.raises(ClientError) as exc:
+ r53.get_hosted_zone(Id=zone_id)
+ assert exc.value.response["Error"]["Code"] == "NoSuchHostedZone"
+
+
+# ---------------------------------------------------------------------------
+# Update handlers, batch 5: the twelve types of #1601 C1 whose stack update
+# fell through to the create handler and lost what the resource was holding.
+# ---------------------------------------------------------------------------
+
+def _cfn_elbv2_template(uid, *, health_path="/a", idle_timeout="60",
+ priority=10, scheme="internet-facing", name=None,
+ tg_port=80, listener_port=80, listener_protocol="HTTP",
+ listener_actions=None, listener_lb="LB",
+ second_lb=False):
+ resources = {
+ "LB": {
+ "Type": "AWS::ElasticLoadBalancingV2::LoadBalancer",
+ "Properties": {
+ "Name": name or f"cfn-lb-{uid}",
+ "Type": "application",
+ "Scheme": scheme,
+ "LoadBalancerAttributes": [
+ {"Key": "idle_timeout.timeout_seconds", "Value": idle_timeout},
+ ],
+ },
+ },
+ "TG": {
+ "Type": "AWS::ElasticLoadBalancingV2::TargetGroup",
+ "Properties": {
+ "Name": f"cfn-tg-{uid}",
+ "Port": tg_port,
+ "Protocol": "HTTP",
+ "TargetType": "ip",
+ "HealthCheckPath": health_path,
+ "Tags": [{"Key": "team", "Value": "ops"}],
+ },
+ },
+ "L": {
+ "Type": "AWS::ElasticLoadBalancingV2::Listener",
+ "Properties": {
+ "LoadBalancerArn": {"Ref": listener_lb},
+ "Port": listener_port,
+ "Protocol": listener_protocol,
+ "DefaultActions": listener_actions or [
+ {"Type": "forward", "TargetGroupArn": {"Ref": "TG"}},
+ ],
+ },
+ },
+ "R": {
+ "Type": "AWS::ElasticLoadBalancingV2::ListenerRule",
+ "Properties": {
+ "ListenerArn": {"Ref": "L"},
+ "Priority": priority,
+ "Conditions": [
+ {"Field": "path-pattern", "Values": [f"{health_path}*"]},
+ ],
+ "Actions": [{"Type": "forward", "TargetGroupArn": {"Ref": "TG"}}],
+ },
+ },
+ }
+ if second_lb:
+ resources["LB2"] = {
+ "Type": "AWS::ElasticLoadBalancingV2::LoadBalancer",
+ "Properties": {"Name": f"cfn-lb2-{uid}", "Type": "application"},
+ }
+ return json.dumps({
+ "Resources": resources,
+ "Outputs": {
+ "LbRef": {"Value": {"Ref": "LB"}},
+ "LbDns": {"Value": {"Fn::GetAtt": ["LB", "DNSName"]}},
+ "TgRef": {"Value": {"Ref": "TG"}},
+ "ListenerRef": {"Value": {"Ref": "L"}},
+ "RuleRef": {"Value": {"Ref": "R"}},
+ **({"Lb2Ref": {"Value": {"Ref": "LB2"}}} if second_lb else {}),
+ },
+ })
+
+
+def test_cfn_elbv2_update_keeps_the_arns_and_the_registered_targets(cfn, elbv2):
+ """The load balancer attributes, the health-check path and a rule's
+ priority are all No interruption on the resource reference, so the four
+ ELBv2 resources keep their ARNs, the load balancer keeps its DNS name and
+ the target registered in the group survives. Without update handlers each
+ of the four was re-created under a fresh ARN and the registration went
+ with the old target group."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-elbv2-upd-{uid}"
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_elbv2_template(uid))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ lb_arn = _output(stack, "LbRef")
+ dns = _output(stack, "LbDns")
+ tg_arn = _output(stack, "TgRef")
+ listener_arn = _output(stack, "ListenerRef")
+ rule_arn = _output(stack, "RuleRef")
+ elbv2.register_targets(TargetGroupArn=tg_arn,
+ Targets=[{"Id": "10.0.0.5", "Port": 80}])
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_elbv2_template(
+ uid, health_path="/b", idle_timeout="90", priority=20))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "LbRef") == lb_arn
+ assert _output(stack, "LbDns") == dns
+ assert _output(stack, "TgRef") == tg_arn
+ assert _output(stack, "ListenerRef") == listener_arn
+ assert _output(stack, "RuleRef") == rule_arn
+
+ health = elbv2.describe_target_health(TargetGroupArn=tg_arn)
+ assert [t["Target"]["Id"] for t in health["TargetHealthDescriptions"]] \
+ == ["10.0.0.5"]
+ tg = elbv2.describe_target_groups(TargetGroupArns=[tg_arn])["TargetGroups"][0]
+ assert tg["HealthCheckPath"] == "/b"
+ attrs = {a["Key"]: a["Value"] for a in elbv2.describe_load_balancer_attributes(
+ LoadBalancerArn=lb_arn)["Attributes"]}
+ assert attrs["idle_timeout.timeout_seconds"] == "90"
+ rules = {r["RuleArn"]: r for r in elbv2.describe_rules(
+ ListenerArn=listener_arn)["Rules"]}
+ assert rules[rule_arn]["Priority"] == "20"
+ assert rules[rule_arn]["Conditions"][0]["Values"] == ["/b*"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_elbv2_listener_update_changes_port_protocol_and_actions(cfn, elbv2):
+ """Port, Protocol and DefaultActions are all "Update requires: No
+ interruption" on the Listener resource reference, so a change to any of
+ them updates the listener in place under the same ARN."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-elbv2-listener-upd-{uid}"
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_elbv2_template(uid))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ listener_arn = _output(stack, "ListenerRef")
+
+ new_actions = [{
+ "Type": "fixed-response",
+ "FixedResponseConfig": {
+ "StatusCode": "404",
+ "ContentType": "application/json",
+ "MessageBody": '{"status":404}',
+ },
+ }]
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_elbv2_template(
+ uid, listener_port=8443, listener_protocol="HTTPS",
+ listener_actions=new_actions))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "ListenerRef") == listener_arn
+
+ listener = elbv2.describe_listeners(
+ ListenerArns=[listener_arn])["Listeners"][0]
+ assert listener["Port"] == 8443
+ assert listener["Protocol"] == "HTTPS"
+ assert listener["DefaultActions"][0]["Type"] == "fixed-response"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_elbv2_listener_moved_to_another_load_balancer_is_replaced(cfn, elbv2):
+ """LoadBalancerArn is the listener's one replacing property and a
+ listener ARN carries its load balancer, so the move comes back under a
+ new ARN. The rule's ListenerArn follows the Ref and replaces the rule the
+ same way, and the old load balancer is left without a listener."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-elbv2-move-{uid}"
+
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_elbv2_template(uid, listener_lb="LB2",
+ second_lb=True))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ old_listener = _output(stack, "ListenerRef")
+ old_rule = _output(stack, "RuleRef")
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=_cfn_elbv2_template(uid, second_lb=True))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ listener_arn = _output(stack, "ListenerRef")
+ rule_arn = _output(stack, "RuleRef")
+ assert listener_arn != old_listener
+ assert rule_arn != old_rule
+ listeners = elbv2.describe_listeners(LoadBalancerArn=_output(stack, "LbRef"))
+ assert [lst["ListenerArn"] for lst in listeners["Listeners"]] == [listener_arn]
+ assert rule_arn in {r["RuleArn"] for r in elbv2.describe_rules(
+ ListenerArn=listener_arn)["Rules"]}
+ assert elbv2.describe_listeners(
+ LoadBalancerArn=_output(stack, "Lb2Ref"))["Listeners"] == []
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_elbv2_target_group_tags_read_through_describe_tags(cfn, elbv2):
+ """The ALB tag store holds a list of {Key, Value} per ARN, which is what
+ DescribeTags iterates. The target group create wrote a map there, so the
+ call raised for any CloudFormation-created group."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-elbv2-tags-{uid}"
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_elbv2_template(uid))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ tg_arn = _output(stack, "TgRef")
+ tags = elbv2.describe_tags(ResourceArns=[tg_arn])["TagDescriptions"][0]["Tags"]
+ assert {"Key": "team", "Value": "ops"} in tags
+ assert {t["Key"] for t in tags} >= {"team", "aws:cloudformation:stack-name"}
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def _cfn_hosted_zone_template(uid, comment, name=None):
+ return json.dumps({
+ "Resources": {
+ "Zone": {
+ "Type": "AWS::Route53::HostedZone",
+ "Properties": {
+ "Name": name or f"cfn-{uid}.example.com.",
+ "HostedZoneConfig": {"Comment": comment},
+ },
+ },
+ },
+ "Outputs": {"ZoneRef": {"Value": {"Ref": "Zone"}}},
+ })
+
+
+def test_cfn_route53_hosted_zone_update_keeps_its_id_and_records(cfn, r53):
+ """HostedZoneConfig is No interruption, so a comment change leaves the
+ zone where it is. Without an update handler the create minted a second
+ zone with a fresh id and only the default NS and SOA records, which
+ orphaned every record set created in the first one."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-r53-upd-{uid}"
+
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_hosted_zone_template(uid, "before"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ zone_id = _output(stack, "ZoneRef")
+ r53.change_resource_record_sets(HostedZoneId=zone_id, ChangeBatch={
+ "Changes": [{
+ "Action": "CREATE",
+ "ResourceRecordSet": {
+ "Name": f"www.cfn-{uid}.example.com.", "Type": "A", "TTL": 60,
+ "ResourceRecords": [{"Value": "10.0.0.1"}],
+ },
+ }],
+ })
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=_cfn_hosted_zone_template(uid, "after"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "ZoneRef") == zone_id
+ records = r53.list_resource_record_sets(HostedZoneId=zone_id)
+ assert [r["Name"] for r in records["ResourceRecordSets"]
+ if r["Type"] == "A"] == [f"www.cfn-{uid}.example.com."]
+ zone = r53.get_hosted_zone(Id=zone_id)["HostedZone"]
+ assert zone["Config"]["Comment"] == "after"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_route53_hosted_zone_rename_replaces_the_zone(cfn, r53):
+ """Name requires replacement and a hosted-zone name is not unique, so the
+ rename goes through: a new zone id, and the old zone is gone."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-r53-rename-{uid}"
+
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_hosted_zone_template(uid, "same"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ old_zone = _output(stack, "ZoneRef")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_hosted_zone_template(
+ uid, "same", name=f"cfn-{uid}-moved.example.com."))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ new_zone = _output(stack, "ZoneRef")
+ assert new_zone != old_zone
+ assert r53.get_hosted_zone(Id=new_zone)["HostedZone"]["Name"] \
+ == f"cfn-{uid}-moved.example.com."
+ with pytest.raises(ClientError):
+ r53.get_hosted_zone(Id=old_zone)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def _cfn_web_acl_template(uid, description, scope="REGIONAL", metric="cfnacl"):
+ return json.dumps({
+ "Resources": {
+ "Acl": {
+ "Type": "AWS::WAFv2::WebACL",
+ "Properties": {
+ "Name": f"cfn-acl-{uid}",
+ "Scope": scope,
+ "Description": description,
+ "DefaultAction": {"Allow": {}},
+ "VisibilityConfig": {
+ "SampledRequestsEnabled": True,
+ "CloudWatchMetricsEnabled": True,
+ "MetricName": metric,
+ },
+ },
+ },
+ },
+ "Outputs": {
+ "AclRef": {"Value": {"Ref": "Acl"}},
+ "AclArn": {"Value": {"Fn::GetAtt": ["Acl", "Arn"]}},
+ },
+ })
+
+
+def test_cfn_wafv2_web_acl_update_keeps_its_id_and_arn(cfn, wafv2):
+ """Description and VisibilityConfig are No interruption, so the web ACL
+ keeps the id and ARN that a WebACLAssociation points at. Without an
+ update handler the create minted a second ACL under a fresh id and the
+ engine deleted the first."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-waf-upd-{uid}"
+
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_web_acl_template(uid, "before"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ acl_id = _output(stack, "AclRef")
+ acl_arn = _output(stack, "AclArn")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_web_acl_template(
+ uid, "after", metric="cfnaclrenamed"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "AclRef") == acl_id
+ assert _output(stack, "AclArn") == acl_arn
+ acl = wafv2.get_web_acl(Name=f"cfn-acl-{uid}", Scope="REGIONAL",
+ Id=acl_id)["WebACL"]
+ assert acl["Description"] == "after"
+ assert acl["VisibilityConfig"]["MetricName"] == "cfnaclrenamed"
+ assert [a["Id"] for a in wafv2.list_web_acls(Scope="REGIONAL")["WebACLs"]
+ if a["Name"] == f"cfn-acl-{uid}"] == [acl_id]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def _cfn_backup_template(uid, hour, tag, encryption_key_arn=None):
+ vault_props = {
+ "BackupVaultName": f"cfn-vault-{uid}",
+ "BackupVaultTags": {"team": tag},
+ }
+ if encryption_key_arn is not None:
+ vault_props["EncryptionKeyArn"] = encryption_key_arn
+ return json.dumps({
+ "Resources": {
+ "Vault": {
+ "Type": "AWS::Backup::BackupVault",
+ "Properties": vault_props,
+ },
+ "Plan": {
+ "Type": "AWS::Backup::BackupPlan",
+ "DependsOn": "Vault",
+ "Properties": {
+ "BackupPlan": {
+ "BackupPlanName": f"cfn-plan-{uid}",
+ "BackupPlanRule": [{
+ "RuleName": "daily",
+ "TargetBackupVault": f"cfn-vault-{uid}",
+ "ScheduleExpression": f"cron(0 {hour} * * ? *)",
+ }],
+ },
+ },
+ },
+ },
+ "Outputs": {
+ "VaultRef": {"Value": {"Ref": "Vault"}},
+ "VaultArn": {"Value": {"Fn::GetAtt": ["Vault", "BackupVaultArn"]}},
+ "PlanRef": {"Value": {"Ref": "Plan"}},
+ },
+ })
+
+
+def test_cfn_backup_plan_update_keeps_its_id_and_reads_back_its_rules(cfn, backup):
+ """Both properties of AWS::Backup::BackupPlan are No interruption, so the
+ plan keeps the id a BackupSelection references while its rule changes;
+ the create minted a second plan and the engine deleted the first. The
+ rules read back at all only because the create now translates the
+ template's BackupPlanRule into the Rules the API serves."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-backup-plan-{uid}"
+
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_backup_template(uid, 1, "a"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ plan_id = _output(stack, "PlanRef")
+ plan = backup.get_backup_plan(BackupPlanId=plan_id)
+ assert [r["RuleName"] for r in plan["BackupPlan"]["Rules"]] == ["daily"]
+ assert plan["BackupPlan"]["Rules"][0]["TargetBackupVaultName"] \
+ == f"cfn-vault-{uid}"
+ assert plan["BackupPlan"]["Rules"][0]["ScheduleExpression"] == "cron(0 1 * * ? *)"
+ version = plan["VersionId"]
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=_cfn_backup_template(uid, 5, "a"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "PlanRef") == plan_id
+ plan = backup.get_backup_plan(BackupPlanId=plan_id)
+ assert plan["BackupPlan"]["Rules"][0]["ScheduleExpression"] == "cron(0 5 * * ? *)"
+ assert plan["VersionId"] != version
+ assert [p["BackupPlanId"] for p in backup.list_backup_plans()["BackupPlansList"]
+ if p["BackupPlanName"] == f"cfn-plan-{uid}"] == [plan_id]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_backup_vault_tags_update_in_place(cfn, backup):
+ """BackupVaultTags is No interruption. The vault keeps its creation date
+ and the tags set through TagResource, and the changed template tag
+ reaches it: the create handler ran into AlreadyExistsException and
+ dropped the change."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-backup-vault-{uid}"
+
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_backup_template(uid, 1, "a"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ vault_arn = _output(stack, "VaultArn")
+ created = backup.describe_backup_vault(
+ BackupVaultName=f"cfn-vault-{uid}")["CreationDate"]
+ backup.tag_resource(ResourceArn=vault_arn, Tags={"owner": "ops"})
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=_cfn_backup_template(uid, 1, "b"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "VaultArn") == vault_arn
+ vault = backup.describe_backup_vault(BackupVaultName=f"cfn-vault-{uid}")
+ assert vault["CreationDate"] == created
+ tags = backup.list_tags(ResourceArn=vault_arn)["Tags"]
+ assert tags["team"] == "b"
+ assert tags["owner"] == "ops"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def _cfn_certificate_template(uid, tag, domain=None):
+ return json.dumps({
+ "Resources": {
+ "Cert": {
+ "Type": "AWS::CertificateManager::Certificate",
+ "Properties": {
+ "DomainName": domain or f"cfn-{uid}.example.com",
+ "ValidationMethod": "DNS",
+ "Tags": [{"Key": "team", "Value": tag}],
+ },
+ },
+ },
+ "Outputs": {"CertRef": {"Value": {"Ref": "Cert"}}},
+ })
+
+
+def test_cfn_acm_certificate_tag_update_does_not_reissue_it(cfn, acm_client):
+ """Tags is No interruption, so the certificate keeps its ARN, its
+ validity window and its key material while the tag changes. The create
+ handler re-requested the certificate on every property change, which
+ moved IssuedAt and left the tag at its old value."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-acm-upd-{uid}"
+
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_certificate_template(uid, "a"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ arn = _output(stack, "CertRef")
+ before = acm_client.describe_certificate(CertificateArn=arn)["Certificate"]
+ pem = acm_client.get_certificate(CertificateArn=arn)["Certificate"]
+ acm_client.add_tags_to_certificate(
+ CertificateArn=arn, Tags=[{"Key": "owner", "Value": "ops"}])
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=_cfn_certificate_template(uid, "b"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "CertRef") == arn
+ after = acm_client.describe_certificate(CertificateArn=arn)["Certificate"]
+ assert after["IssuedAt"] == before["IssuedAt"]
+ assert after["NotAfter"] == before["NotAfter"]
+ assert acm_client.get_certificate(CertificateArn=arn)["Certificate"] == pem
+ tags = {t["Key"]: t["Value"] for t in acm_client.list_tags_for_certificate(
+ CertificateArn=arn)["Tags"]}
+ assert tags["team"] == "b"
+ assert tags["owner"] == "ops"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_acm_certificate_domain_change_replaces_it(cfn, acm_client):
+ """DomainName requires replacement: a new certificate is requested under
+ a new ARN and the old one is deleted, CloudFormation's replacement
+ order."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-acm-repl-{uid}"
+
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_certificate_template(uid, "a"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ old_arn = _output(stack, "CertRef")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_certificate_template(
+ uid, "a", domain=f"cfn-{uid}-moved.example.com"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ new_arn = _output(stack, "CertRef")
+ assert new_arn != old_arn
+ assert acm_client.describe_certificate(CertificateArn=new_arn)["Certificate"][
+ "DomainName"] == f"cfn-{uid}-moved.example.com"
+ with pytest.raises(ClientError):
+ acm_client.describe_certificate(CertificateArn=old_arn)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_acm_certificate_validation_method_change_regenerates_options(
+ cfn, acm_client):
+ """ValidationMethod is No interruption and updates in place; the
+ DomainValidationOptions, one entry per SAN keyed by the method, are
+ regenerated with it instead of reporting the old method."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-acm-method-{uid}"
+
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_certificate_template(uid, "a"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ arn = _output(stack, "CertRef")
+ before = acm_client.describe_certificate(CertificateArn=arn)["Certificate"]
+ assert before["DomainValidationOptions"][0]["ValidationMethod"] == "DNS"
+
+ template = json.loads(_cfn_certificate_template(uid, "a"))
+ template["Resources"]["Cert"]["Properties"]["ValidationMethod"] = "EMAIL"
+ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "CertRef") == arn
+
+ after = acm_client.describe_certificate(CertificateArn=arn)["Certificate"]
+ assert len(after["DomainValidationOptions"]) == 1
+ assert after["DomainValidationOptions"][0]["ValidationMethod"] == "EMAIL"
+ assert after["DomainValidationOptions"][0]["DomainName"] == \
+ before["DomainValidationOptions"][0]["DomainName"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def _cfn_email_identity_template(uid, mail_from, identity=None):
+ return json.dumps({
+ "Resources": {
+ "Ident": {
+ "Type": "AWS::SES::EmailIdentity",
+ "Properties": {
+ "EmailIdentity": identity or f"cfn-{uid}.example.com",
+ "MailFromAttributes": {"MailFromDomain": mail_from},
+ },
+ },
+ },
+ "Outputs": {"IdentRef": {"Value": {"Ref": "Ident"}}},
+ })
+
+
+def test_cfn_ses_email_identity_reads_through_the_v2_api(cfn, sesv2):
+ """AWS::SES::EmailIdentity is the SES v2 resource type, but the create
+ handler registered the identity in the v1 store alone, so
+ GetEmailIdentity and ListEmailIdentities could not see a template's own
+ identity."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-ses-v2-{uid}"
+ domain = f"cfn-{uid}.example.com"
+
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_email_identity_template(uid, "mail.example.com"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ identity = sesv2.get_email_identity(EmailIdentity=domain)
+ assert identity["IdentityType"] == "DOMAIN"
+ assert identity["MailFromAttributes"]["MailFromDomain"] == "mail.example.com"
+ assert domain in [i["IdentityName"]
+ for i in sesv2.list_email_identities()["EmailIdentities"]]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ with pytest.raises(ClientError):
+ sesv2.get_email_identity(EmailIdentity=domain)
+
+
+def test_cfn_ses_email_identity_update_keeps_its_dkim_tokens(cfn, ses, sesv2):
+ """MailFromAttributes is No interruption, so the identity keeps the DKIM
+ tokens and the verification status it holds; the create handler rebuilt
+ the record and put both back to their defaults."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-ses-upd-{uid}"
+ domain = f"cfn-{uid}.example.com"
+
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_email_identity_template(uid, "mail.example.com"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ tokens = ses.verify_domain_dkim(Domain=domain)["DkimTokens"]
+ assert tokens
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_email_identity_template(
+ uid, "bounces.example.com"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "IdentRef") == domain
+ assert ses.get_identity_dkim_attributes(Identities=[domain])[
+ "DkimAttributes"][domain]["DkimTokens"] == tokens
+ identity = sesv2.get_email_identity(EmailIdentity=domain)
+ assert identity["MailFromAttributes"]["MailFromDomain"] == "bounces.example.com"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def _cfn_thing_type_template(uid, description, name=None, deprecate=None,
+ generated_name=False, searchable=("serial",),
+ mqtt5_key=None, policy=None):
+ props = {
+ "ThingTypeProperties": {
+ "ThingTypeDescription": description,
+ "SearchableAttributes": list(searchable),
+ },
+ }
+ if mqtt5_key:
+ props["ThingTypeProperties"]["Mqtt5Configuration"] = {"PropagatingAttributes": [
+ {"UserPropertyKey": mqtt5_key, "ConnectionAttribute": "iot:ClientId"},
+ ]}
+ if not generated_name:
+ props["ThingTypeName"] = name or f"cfn-tt-{uid}"
+ if deprecate is not None:
+ props["DeprecateThingType"] = deprecate
+ resource = {"Type": "AWS::IoT::ThingType", "Properties": props}
+ if policy:
+ resource["UpdateReplacePolicy"] = policy
+ return json.dumps({
+ "Resources": {"TT": resource},
+ "Outputs": {
+ "TTRef": {"Value": {"Ref": "TT"}},
+ "TTArn": {"Value": {"Fn::GetAtt": ["TT", "Arn"]}},
+ },
+ })
+
+
+def test_cfn_iot_thing_type_update_in_place(cfn, iot_client):
+ """DeprecateThingType and Mqtt5Configuration update in place through a
+ change set, and a template that drops Mqtt5Configuration clears it
+ (measured). The thing type keeps its id and its creation date. A type
+ declared deprecated from the start comes up deprecated."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-iot-tt-{uid}"
+ name = f"cfn-tt-{uid}"
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_thing_type_template(
+ uid, "same", deprecate=True, mqtt5_key="k1"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ described = iot_client.describe_thing_type(thingTypeName=name)
+ type_id = described["thingTypeId"]
+ created = described["thingTypeMetadata"]["creationDate"]
+ assert described["thingTypeMetadata"]["deprecated"] is True
+
+ cfn.create_change_set(StackName=stack_name, ChangeSetName="mqtt5",
+ TemplateBody=_cfn_thing_type_template(
+ uid, "same", deprecate=False, mqtt5_key="k2"))
+ cfn.execute_change_set(StackName=stack_name, ChangeSetName="mqtt5")
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "TTRef") == name
+ described = iot_client.describe_thing_type(thingTypeName=name)
+ assert described["thingTypeId"] == type_id
+ assert described["thingTypeMetadata"]["creationDate"] == created
+ assert described["thingTypeMetadata"]["deprecated"] is False
+ assert described["thingTypeProperties"]["mqtt5Configuration"] == {
+ "propagatingAttributes": [
+ {"userPropertyKey": "k2", "connectionAttribute": "iot:ClientId"},
+ ],
+ }
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_thing_type_template(
+ uid, "same", deprecate=False))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ described = iot_client.describe_thing_type(thingTypeName=name)
+ assert described["thingTypeId"] == type_id
+ assert "mqtt5Configuration" not in described["thingTypeProperties"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
- cfn.delete_stack(StackName=stack_name)
- _wait_stack(cfn, stack_name)
- with pytest.raises(ClientError) as exc:
- elbv2.describe_load_balancers(Names=[lb_name])
- assert exc.value.response["Error"]["Code"] == "LoadBalancerNotFound"
+def test_cfn_iot_thing_type_properties_change_under_generated_name_replaces_it(
+ cfn, iot_client):
+ """Under a generated name there is nothing to refuse, so a description
+ change replaces the thing type. The generated name is deterministic, so
+ the handler deletes before it creates, and an UpdateReplacePolicy of
+ Retain cannot keep the predecessor."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-iot-tt-gen-{uid}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_thing_type_template(
+ uid, "before", generated_name=True, policy="Retain"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ name = _output(stack, "TTRef")
+ old_id = iot_client.describe_thing_type(thingTypeName=name)["thingTypeId"]
-def test_cfn_cloudwatch_alarm_lifecycle(cfn, cw):
- """CloudFormation creates a metric alarm and removes it on stack delete."""
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_thing_type_template(
+ uid, "after", generated_name=True, policy="Retain"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "TTRef") == name
+ described = iot_client.describe_thing_type(thingTypeName=name)
+ assert described["thingTypeId"] != old_id
+ assert described["thingTypeProperties"]["thingTypeDescription"] == "after"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_iot_thing_type_rename_replaces_it(cfn, iot_client):
+ """ThingTypeName requires replacement: the thing type under the new name
+ is created before the old one is removed."""
uid = _uuid_mod.uuid4().hex[:8]
- stack_name = f"cfn-cwal-{uid}"
- alarm_name = f"cfn-cw-alarm-{uid}"
- template = {
- "AWSTemplateFormatVersion": "2010-09-09",
- "Resources": {
- "CpuAlarm": {
- "Type": "AWS::CloudWatch::Alarm",
- "Properties": {
- "AlarmName": alarm_name,
- "AlarmDescription": "CFN integration test",
- "MetricName": "CPUUtilization",
- "Namespace": f"CfnCwTest/{uid}",
- "Statistic": "Average",
- "Period": 60,
- "EvaluationPeriods": 1,
- "Threshold": 80.0,
- "ComparisonOperator": "GreaterThanThreshold",
- "TreatMissingData": "notBreaching",
- },
- },
- },
- "Outputs": {
- "AlarmNameOut": {"Value": {"Ref": "CpuAlarm"}},
- "AlarmArnOut": {"Value": {"Fn::GetAtt": ["CpuAlarm", "Arn"]}},
- },
- }
- cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
- stack = _wait_stack(cfn, stack_name)
- assert stack["StackStatus"] == "CREATE_COMPLETE"
+ stack_name = f"cfn-iot-tt-ren-{uid}"
- outputs = {o["OutputKey"]: o["OutputValue"] for o in stack.get("Outputs", [])}
- assert outputs["AlarmNameOut"] == alarm_name
- assert outputs["AlarmArnOut"].endswith(f":alarm:{alarm_name}")
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_thing_type_template(uid, "same"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
- resp = cw.describe_alarms(AlarmNames=[alarm_name])
- assert len(resp["MetricAlarms"]) == 1
- a = resp["MetricAlarms"][0]
- assert a["MetricName"] == "CPUUtilization"
- assert a["Namespace"] == f"CfnCwTest/{uid}"
- assert float(a["Threshold"]) == 80.0
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_thing_type_template(
+ uid, "same", name=f"cfn-tt-{uid}-moved"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "TTRef") == f"cfn-tt-{uid}-moved"
+ assert iot_client.describe_thing_type(
+ thingTypeName=f"cfn-tt-{uid}-moved")["thingTypeProperties"][
+ "thingTypeDescription"] == "same"
+ with pytest.raises(ClientError):
+ iot_client.describe_thing_type(thingTypeName=f"cfn-tt-{uid}")
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
- cfn.delete_stack(StackName=stack_name)
- _wait_stack(cfn, stack_name)
- resp2 = cw.describe_alarms(AlarmNames=[alarm_name])
- assert resp2["MetricAlarms"] == []
+def test_cfn_apigateway_account_update_removes_a_dropped_role():
+ """CloudWatchRoleArn is No interruption. The create handler only ever
+ wrote a declared role, so a template that dropped the property left the
+ old role in the account settings GetAccount answers.
-def test_cfn_cloudwatch_dashboard_lifecycle(cfn, cw):
- """CloudFormation creates, updates, and removes a CloudWatch dashboard."""
+ The settings are one record per account and region, and
+ tests/test_apigatewayv1.py writes the default region's, so this runs in
+ us-west-2 rather than racing it."""
uid = _uuid_mod.uuid4().hex[:8]
- stack_name = f"cfn-cwdash-{uid}"
- dashboard_name = f"cfn-dashboard-{uid}"
- replacement_name = f"cfn-dashboard-replaced-{uid}"
- body = json.dumps({"widgets": [{"type": "text", "properties": {"markdown": "Created"}}]})
- updated_body = json.dumps({"widgets": [{"type": "text", "properties": {"markdown": "Updated"}}]})
+ stack_name = f"cfn-apigw-account-{uid}"
+ role_arn = f"arn:aws:iam::000000000000:role/cfn-apigw-{uid}"
+ cfn = _regional_cfn_test_client("cloudformation", "us-west-2")
+ apigw_v1 = _regional_cfn_test_client("apigateway", "us-west-2")
- def template(dashboard_body, name=dashboard_name):
- return {
- "AWSTemplateFormatVersion": "2010-09-09",
- "Resources": {
- "Dashboard": {
- "Type": "AWS::CloudWatch::Dashboard",
- "Properties": {
- "DashboardName": name,
- "DashboardBody": dashboard_body,
- },
- },
- },
- "Outputs": {
- "DashboardName": {"Value": {"Ref": "Dashboard"}},
- },
- }
+ def template(with_role):
+ return json.dumps({"Resources": {"Account": {
+ "Type": "AWS::ApiGateway::Account",
+ "Properties": {"CloudWatchRoleArn": role_arn} if with_role else {},
+ }}})
- cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template(body)))
- stack = _wait_stack(cfn, stack_name)
- assert stack["StackStatus"] == "CREATE_COMPLETE"
- assert stack["Outputs"][0]["OutputValue"] == dashboard_name
- assert cw.get_dashboard(DashboardName=dashboard_name)["DashboardBody"] == body
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(True))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ assert apigw_v1.get_account()["cloudwatchRoleArn"] == role_arn
- cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(template(updated_body)))
- stack = _wait_stack(cfn, stack_name)
- assert stack["StackStatus"] == "UPDATE_COMPLETE"
- assert cw.get_dashboard(DashboardName=dashboard_name)["DashboardBody"] == updated_body
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(False))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert "cloudwatchRoleArn" not in apigw_v1.get_account()
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
- cfn.update_stack(
- StackName=stack_name,
- TemplateBody=json.dumps(template(updated_body, replacement_name)),
- )
- stack = _wait_stack(cfn, stack_name)
- assert stack["StackStatus"] == "UPDATE_COMPLETE"
- assert stack["Outputs"][0]["OutputValue"] == replacement_name
- with pytest.raises(ClientError) as exc:
- cw.get_dashboard(DashboardName=dashboard_name)
- assert exc.value.response["Error"]["Code"] == "ResourceNotFound"
- assert cw.get_dashboard(DashboardName=replacement_name)["DashboardBody"] == updated_body
- cfn.delete_stack(StackName=stack_name)
- _wait_stack(cfn, stack_name)
- with pytest.raises(ClientError) as exc:
- cw.get_dashboard(DashboardName=replacement_name)
- assert exc.value.response["Error"]["Code"] == "ResourceNotFound"
+ "lb_scheme", "tg_port", "web_acl_scope", "vault_key",
+ "thing_type_description", "thing_type_searchable",
+])
+def test_cfn_replacing_change_under_custom_name_fails_loudly(
+ cfn, elbv2, wafv2, backup, iot_client, case):
+ """A change that requires replacing a resource whose name the template
+ sets is refused: the stack rolls back and the resource keeps its value.
+ Measured for the vault key and the thing type properties; the load
+ balancer page states it ("If you specify a name, you cannot perform
+ updates that require replacement of this resource")."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-custom-repl-{uid}"
+ tt = f"cfn-tt-{uid}"
+ before, after, read, kept = {
+ "lb_scheme": (
+ _cfn_elbv2_template(uid), _cfn_elbv2_template(uid, scheme="internal"),
+ lambda st: elbv2.describe_load_balancers(LoadBalancerArns=[
+ _output(st, "LbRef")])["LoadBalancers"][0]["Scheme"],
+ "internet-facing"),
+ "tg_port": (
+ _cfn_elbv2_template(uid), _cfn_elbv2_template(uid, tg_port=8080),
+ lambda st: elbv2.describe_target_groups(TargetGroupArns=[
+ _output(st, "TgRef")])["TargetGroups"][0]["Port"],
+ 80),
+ "web_acl_scope": (
+ _cfn_web_acl_template(uid, "d"),
+ _cfn_web_acl_template(uid, "d", scope="CLOUDFRONT"),
+ lambda st: [a["Id"] for a in wafv2.list_web_acls(Scope="REGIONAL")["WebACLs"]
+ if a["Name"] == f"cfn-acl-{uid}"] == [_output(st, "AclRef")],
+ True),
+ "vault_key": (
+ _cfn_backup_template(uid, 1, "a"),
+ _cfn_backup_template(uid, 1, "a", encryption_key_arn=(
+ f"arn:aws:kms:us-east-1:000000000000:key/cfn-{uid}")),
+ lambda st: backup.describe_backup_vault(
+ BackupVaultName=f"cfn-vault-{uid}")["EncryptionKeyArn"],
+ ""),
+ "thing_type_description": (
+ _cfn_thing_type_template(uid, "before"),
+ _cfn_thing_type_template(uid, "after"),
+ lambda st: iot_client.describe_thing_type(
+ thingTypeName=tt)["thingTypeProperties"]["thingTypeDescription"],
+ "before"),
+ "thing_type_searchable": (
+ _cfn_thing_type_template(uid, "same"),
+ _cfn_thing_type_template(uid, "same", searchable=("serial", "batch")),
+ lambda st: iot_client.describe_thing_type(
+ thingTypeName=tt)["thingTypeProperties"]["searchableAttributes"],
+ ["serial"]),
+ }[case]
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=before)
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ cfn.update_stack(StackName=stack_name, TemplateBody=after)
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", \
+ stack.get("StackStatusReason")
+ assert "custom-named resource requires replacing" in \
+ _stack_event_reasons(cfn, stack_name)
+ assert read(stack) == kept
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
-def test_cfn_route53_hosted_zone_and_record_set(cfn, r53):
- """CloudFormation provisions Route53 HostedZone + RecordSet and removes records on delete."""
- uid = _uuid_mod.uuid4().hex[:8]
- stack_name = f"cfn-r53rs-{uid}"
- zone_name = f"cfnrs{uid}.com."
- record_name = f"www.cfnrs{uid}.com"
- template = {
- "AWSTemplateFormatVersion": "2010-09-09",
+def _cfn_auto_named_template(uid, *, lb_type="application", port=80,
+ scope="REGIONAL"):
+ """A load balancer, a target group and a web ACL with no name property, so
+ each carries the name the emulator generates for it."""
+ return json.dumps({
"Resources": {
- "Zone": {
- "Type": "AWS::Route53::HostedZone",
- "Properties": {"Name": zone_name},
+ "LB": {
+ "Type": "AWS::ElasticLoadBalancingV2::LoadBalancer",
+ "Properties": {"Type": lb_type},
},
- "WebA": {
- "Type": "AWS::Route53::RecordSet",
+ "TG": {
+ "Type": "AWS::ElasticLoadBalancingV2::TargetGroup",
+ "Properties": {"Port": port, "Protocol": "HTTP",
+ "TargetType": "ip"},
+ },
+ "Acl": {
+ "Type": "AWS::WAFv2::WebACL",
"Properties": {
- "HostedZoneId": {"Ref": "Zone"},
- "Name": record_name,
- "Type": "A",
- "TTL": 300,
- "ResourceRecords": [{"Value": "198.51.100.10"}],
+ "Scope": scope,
+ "DefaultAction": {"Allow": {}},
+ "VisibilityConfig": {
+ "SampledRequestsEnabled": True,
+ "CloudWatchMetricsEnabled": True,
+ "MetricName": f"cfnauto{uid}",
+ },
},
},
},
"Outputs": {
- "RecordFqdn": {"Value": {"Ref": "WebA"}},
+ "LbRef": {"Value": {"Ref": "LB"}},
+ "TgRef": {"Value": {"Ref": "TG"}},
+ "AclRef": {"Value": {"Ref": "Acl"}},
},
- }
- cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
- stack = _wait_stack(cfn, stack_name)
- assert stack["StackStatus"] == "CREATE_COMPLETE"
+ })
- outputs = {o["OutputKey"]: o["OutputValue"] for o in stack.get("Outputs", [])}
- assert outputs["RecordFqdn"].endswith(".")
- resources = {r["LogicalResourceId"]: r for r in cfn.describe_stack_resources(StackName=stack_name)["StackResources"]}
- zone_id = resources["Zone"]["PhysicalResourceId"]
+def test_cfn_replacing_property_replaces_an_auto_named_resource(
+ cfn, elbv2, wafv2):
+ """The custom-name refusal covers a resource whose name the template sets.
+ Under a generated name there is nothing to refuse, so a load balancer's
+ Type, a target group's Port and a web ACL's Scope come back under a new
+ physical id carrying the new value instead of being dropped."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-auto-replace-{uid}"
- rrs = r53.list_resource_record_sets(HostedZoneId=zone_id)["ResourceRecordSets"]
- a_rrs = [r for r in rrs if r["Type"] == "A" and "cfnrs" in r["Name"]]
- assert len(a_rrs) == 1
- assert a_rrs[0]["ResourceRecords"][0]["Value"] == "198.51.100.10"
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_auto_named_template(uid))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ lb_arn = _output(stack, "LbRef")
+ tg_arn = _output(stack, "TgRef")
+ acl_id = _output(stack, "AclRef")
- cfn.delete_stack(StackName=stack_name)
- _wait_stack(cfn, stack_name)
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_auto_named_template(
+ uid, lb_type="network", port=8080, scope="CLOUDFRONT"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ new_lb = _output(stack, "LbRef")
+ new_tg = _output(stack, "TgRef")
+ new_acl = _output(stack, "AclRef")
+ assert new_lb != lb_arn
+ assert new_tg != tg_arn
+ assert new_acl != acl_id
+ assert elbv2.describe_load_balancers(
+ LoadBalancerArns=[new_lb])["LoadBalancers"][0]["Type"] == "network"
+ assert elbv2.describe_target_groups(
+ TargetGroupArns=[new_tg])["TargetGroups"][0]["Port"] == 8080
+ assert new_acl in {a["Id"] for a
+ in wafv2.list_web_acls(Scope="CLOUDFRONT")["WebACLs"]}
+ assert acl_id not in {a["Id"] for a
+ in wafv2.list_web_acls(Scope="REGIONAL")["WebACLs"]}
+ with pytest.raises(ClientError):
+ elbv2.describe_load_balancers(LoadBalancerArns=[lb_arn])
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
- with pytest.raises(ClientError) as exc:
- r53.get_hosted_zone(Id=zone_id)
- assert exc.value.response["Error"]["Code"] == "NoSuchHostedZone"
+
+def test_cfn_auto_named_replacement_retains_the_predecessor(cfn, elbv2):
+ """That replacement is deleted through the shared helper, so an
+ UpdateReplacePolicy of Retain keeps the load balancer a Type change
+ replaced; without the policy the predecessor goes."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-auto-retain-{uid}"
+ kept = []
+
+ def template(lb_type, policy):
+ res = {"Type": "AWS::ElasticLoadBalancingV2::LoadBalancer",
+ "Properties": {"Type": lb_type}}
+ if policy:
+ res["UpdateReplacePolicy"] = policy
+ return json.dumps({
+ "Resources": {"LB": res},
+ "Outputs": {"LbRef": {"Value": {"Ref": "LB"}}},
+ })
+
+ def exists(arn):
+ try:
+ elbv2.describe_load_balancers(LoadBalancerArns=[arn])
+ return True
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "LoadBalancerNotFound", \
+ exc.response["Error"]
+ return False
+
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=template("application", "Retain"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ first = _output(stack, "LbRef")
+ kept.append(first)
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=template("network", "Retain"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ second = _output(stack, "LbRef")
+ assert second != first
+ assert exists(first), "the retained predecessor was deleted"
+ assert exists(second)
+ assert "DELETE_SKIPPED" in [
+ s for s, _ in _resource_events(cfn, stack_name, "LB")]
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=template("application", None))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ third = _output(stack, "LbRef")
+ assert third != second
+ assert not exists(second)
+ assert exists(third)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ for arn in kept:
+ try:
+ elbv2.delete_load_balancer(LoadBalancerArn=arn)
+ except ClientError:
+ pass
def test_cfn_ssm_parameter_timestamp_is_epoch(cfn, ssm):
@@ -7914,18 +9069,19 @@ def test_cfn_change_set_keeps_tagged_resources_without_update_handler(cfn, sqs):
_delete_cfn_test_stack(cfn, name)
-def test_cfn_stack_tag_change_keeps_a_resource_without_update_handler(cfn):
+def test_cfn_stack_tag_change_keeps_a_resource_without_update_handler(cfn, scheduler):
"""A stack-tag change is an update; a tagged type without an update
- handler (a certificate) keeps its ARN instead of being re-created."""
+ handler (a schedule group) keeps its physical id instead of being
+ re-created."""
name = f"cfn-tag-only-{_uuid_mod.uuid4().hex[:8]}"
template = json.dumps({
"Resources": {
- "Cert": {
- "Type": "AWS::CertificateManager::Certificate",
- "Properties": {"DomainName": f"{name}.example.local", "ValidationMethod": "DNS"},
+ "Group": {
+ "Type": "AWS::Scheduler::ScheduleGroup",
+ "Properties": {"Name": name},
},
},
- "Outputs": {"CertArn": {"Value": {"Ref": "Cert"}}},
+ "Outputs": {"GroupArn": {"Value": {"Fn::GetAtt": ["Group", "Arn"]}}},
})
cfn.create_stack(
StackName=name, TemplateBody=template, Tags=[{"Key": "owner", "Value": "team-a"}],
@@ -7933,22 +9089,22 @@ def test_cfn_stack_tag_change_keeps_a_resource_without_update_handler(cfn):
try:
stack = _wait_stack(cfn, name)
assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
- arn = _output(stack, "CertArn")
+ arn = _output(stack, "GroupArn")
cfn.update_stack(
StackName=name, UsePreviousTemplate=True,
Tags=[{"Key": "owner", "Value": "team-b"}],
)
stack = _wait_stack(cfn, name)
assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
- assert _output(stack, "CertArn") == arn
+ assert _output(stack, "GroupArn") == arn
assert stack["Tags"] == [{"Key": "owner", "Value": "team-b"}]
- detail = cfn.describe_stack_resource(StackName=name, LogicalResourceId="Cert")
- assert detail["StackResourceDetail"]["PhysicalResourceId"] == arn
- # Without an update handler the certificate keeps the tags it was
- # created with; the changed stack tag does not reach it.
- acm = _regional_cfn_test_client("acm", cfn.meta.region_name)
- cert_tags = {t["Key"]: t["Value"] for t in acm.list_tags_for_certificate(CertificateArn=arn)["Tags"]}
- assert cert_tags == {"owner": "team-a", **_system_tags(stack, "Cert")}
+ detail = cfn.describe_stack_resource(StackName=name, LogicalResourceId="Group")
+ assert detail["StackResourceDetail"]["PhysicalResourceId"] == name
+ # Without an update handler the group keeps the tags it was created
+ # with; the changed stack tag does not reach it.
+ group_tags = {t["Key"]: t["Value"]
+ for t in scheduler.list_tags_for_resource(ResourceArn=arn)["Tags"]}
+ assert group_tags == {"owner": "team-a", **_system_tags(stack, "Group")}
finally:
_delete_cfn_test_stack(cfn, name)
@@ -12707,12 +13863,15 @@ def test_cfn_logs_subscription_filter_updates_in_place(cfn, logs):
_delete_cfn_test_stack(cfn, stack_name)
-def test_cfn_logs_subscription_filter_group_change_moves_it(cfn, logs):
[email protected]("rollback", [False, True])
+def test_cfn_logs_subscription_filter_group_change_moves_it(cfn, logs, rollback):
"""LogGroupName requires replacement: the filter is created on the new
group and removed from the old one. The filter keeps its explicit
FilterName, so the physical id does not change; without an update
handler the create wrote the new filter and the old group kept its
- copy, since the engine saw no replacement to clean up."""
+ copy, since the engine saw no replacement to clean up. When a later
+ resource fails the update, the rollback removes the new filter and the
+ old one stays on its group."""
uid = _uuid_mod.uuid4().hex[:8]
stack_name = f"cfn-subfilter-move-{uid}"
group_a = f"/cfn/subfilter-upd-a-{uid}"
@@ -12729,14 +13888,19 @@ def test_cfn_logs_subscription_filter_group_change_moves_it(cfn, logs):
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
- cfn.update_stack(StackName=stack_name,
- TemplateBody=_cfn_subfilter_template(uid, filter_props("GroupB")))
+ body = json.loads(_cfn_subfilter_template(uid, filter_props("GroupB")))
+ if rollback:
+ body["Resources"]["Bad"] = {"Type": "AWS::SSM::Parameter", "DependsOn": "Filter",
+ "Properties": {"Type": "Bogus", "Value": "v"}}
+ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(body))
stack = _wait_stack(cfn, stack_name)
- assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ expected = "UPDATE_ROLLBACK_COMPLETE" if rollback else "UPDATE_COMPLETE"
+ assert stack["StackStatus"] == expected, stack.get("StackStatusReason")
assert _output(stack, "FilterRef") == f"cfn-move-{uid}"
- assert logs.describe_subscription_filters(logGroupName=group_a)["subscriptionFilters"] == []
- moved = logs.describe_subscription_filters(logGroupName=group_b)["subscriptionFilters"]
- assert [f["filterName"] for f in moved] == [f"cfn-move-{uid}"]
+ kept, moved = (group_a, group_b) if rollback else (group_b, group_a)
+ filters = logs.describe_subscription_filters(logGroupName=kept)["subscriptionFilters"]
+ assert [(f["filterName"], f["filterPattern"]) for f in filters] == [(f"cfn-move-{uid}", "[Producer]")]
+ assert logs.describe_subscription_filters(logGroupName=moved)["subscriptionFilters"] == []
finally:
_delete_cfn_test_stack(cfn, stack_name)
@@ -19164,8 +20328,7 @@ def test_cfn_lambda_permission_rollback_of_a_replacement_removes_the_new_stateme
"""When an update that replaced the permission fails later in the run,
the rollback removes the statement the replacement added, since the
delete resolves the Sid the way the create did. The previous statement
- is not re-added: the rollback restores the stack record without
- re-provisioning, which is disclosed in the PR."""
+ stays: its removal waits for the cleanup phase of a successful update."""
uid = _uuid_mod.uuid4().hex[:8]
stack_name = f"cfn-perm-rb-{uid}"
fn_name = f"cfn-perm-rb-{uid}"
@@ -19203,8 +20366,7 @@ def test_cfn_lambda_permission_rollback_of_a_replacement_removes_the_new_stateme
cfn.update_stack(StackName=stack_name, TemplateBody=template("events.amazonaws.com", "N"))
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
- statements = _lambda_policy_statements(lam, fn_name)
- assert {s["Sid"] for s in statements} == {"kept"}
+ assert {s["Sid"] for s in _lambda_policy_statements(lam, fn_name)} == sids
assert ddb.describe_table(TableName=table_name)["Table"]["AttributeDefinitions"] == [
{"AttributeName": "pk", "AttributeType": "S"}]
finally:
@@ -20215,36 +21377,30 @@ def test_cfn_update_rollback_keeps_the_resources_that_existed_before(cfn, sqs, d
sqs.get_queue_url(QueueName=queue_name)
-def test_cfn_update_rollback_deletes_the_replacement_and_restores_the_old_record(cfn, sqs, ddb):
- """A resource replaced under a new physical id during a failed update has
- the replacement deleted on rollback, and the restored stack record points
- at the old physical id again. The queue is renamed, which is a replacement
- (QueueName is create-only); the table, whose attribute type change is
- refused under its custom name, is what fails the update.
-
- AWS, "Understand update behaviors of stack resources": a replacement
- "recreates the resource during an update, which also generates a new
- physical ID. CloudFormation usually creates the replacement resource
- first, changes references from other dependent resources to point to the
- replacement resource, and then deletes the old resource." And on a failed
- operation ("Managing AWS resources as a single unit"): "CloudFormation
- rolls the stack back and automatically deletes any resources that were
- created."
-
- The emulator's replacement deletes the old queue as soon as the new one
- exists, so the rollback cannot bring it back: the restored record names a
- queue that no longer exists. That is the disclosed limit this test pins.
+def test_cfn_update_rollback_deletes_the_replacement_and_keeps_the_old_resource(cfn, sqs, ssm, ddb):
+ """A resource replaced during a failed update has the replacement deleted
+ on rollback and the old resource kept, and the restored stack record
+ points at it again. The queue and the parameter are renamed (both names
+ are create-only); the table, whose attribute type change is refused under
+ its custom name, is what fails the update. A later successful update
+ deletes the predecessors in the cleanup phase.
+
+ Measured on AWS 2026-09-15 with a renamed SSM parameter and a resource
+ failing after it: the new parameter is deleted in
+ UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS and the old one survives.
"""
uid = _uuid_mod.uuid4().hex[:8]
stack_name = f"cfn-rb-replace-{uid}"
- old_name = f"cfn-rb-old-{uid}"
- new_name = f"cfn-rb-new-{uid}"
+ old_name, new_name = f"cfn-rb-old-{uid}", f"cfn-rb-new-{uid}"
+ old_param, new_param = f"/cfn-rb-{uid}/old", f"/cfn-rb-{uid}/new"
table_name = f"cfn-rb-replace-{uid}"
- def template(queue_name, key_type):
+ def template(queue_name, param_name, key_type):
return json.dumps({"Resources": {
"Queue": {"Type": "AWS::SQS::Queue", "Properties": {"QueueName": queue_name}},
- "Table": {"Type": "AWS::DynamoDB::Table", "DependsOn": "Queue", "Properties": {
+ "Param": {"Type": "AWS::SSM::Parameter", "Properties": {
+ "Name": param_name, "Type": "String", "Value": "v"}},
+ "Table": {"Type": "AWS::DynamoDB::Table", "DependsOn": ["Queue", "Param"], "Properties": {
"TableName": table_name,
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": key_type}],
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
@@ -20252,33 +21408,48 @@ def test_cfn_update_rollback_deletes_the_replacement_and_restores_the_old_record
}},
}})
- cfn.create_stack(StackName=stack_name, TemplateBody=template(old_name, "S"))
+ def param_exists(name):
+ try:
+ ssm.get_parameter(Name=name)
+ return True
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "ParameterNotFound", exc.response["Error"]
+ return False
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(old_name, old_param, "S"))
try:
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
old_url = sqs.get_queue_url(QueueName=old_name)["QueueUrl"]
+ new_url = f"{old_url.rsplit('/', 1)[0]}/{new_name}"
- cfn.update_stack(StackName=stack_name, TemplateBody=template(new_name, "N"))
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(new_name, new_param, "N"))
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
- events = [e for e in cfn.describe_stack_events(StackName=stack_name)["StackEvents"]
- if e["LogicalResourceId"] == "Queue"]
- deleted = [e for e in events if e["ResourceStatus"] == "DELETE_COMPLETE"]
- assert [e["PhysicalResourceId"] for e in deleted] == [f"{old_url.rsplit('/', 1)[0]}/{new_name}"]
-
- with pytest.raises(ClientError):
- sqs.get_queue_url(QueueName=new_name)
- with pytest.raises(ClientError): # the replacement already removed it; not restored
- sqs.get_queue_url(QueueName=old_name)
- resources = {r["LogicalResourceId"]: r for r in cfn.describe_stack_resources(
- StackName=stack_name)["StackResources"]}
- assert set(resources) == {"Queue", "Table"}
- assert resources["Queue"]["PhysicalResourceId"] == old_url
- assert resources["Table"]["PhysicalResourceId"] == table_name
+ for logical_id, new_pid in (("Queue", new_url), ("Param", new_param)):
+ deleted = [pid for status, pid in _resource_events(cfn, stack_name, logical_id)
+ if status.startswith("DELETE")]
+ assert deleted == [new_pid], (logical_id, deleted)
+ assert _queue_exists(sqs, old_name) and not _queue_exists(sqs, new_name)
+ assert param_exists(old_param) and not param_exists(new_param)
+ resources = {r["LogicalResourceId"]: r["PhysicalResourceId"]
+ for r in cfn.describe_stack_resources(StackName=stack_name)["StackResources"]}
+ assert resources == {"Queue": old_url, "Param": old_param, "Table": table_name}
table = ddb.describe_table(TableName=table_name)["Table"]
assert table["AttributeDefinitions"] == [{"AttributeName": "pk", "AttributeType": "S"}]
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(new_name, new_param, "S"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _queue_exists(sqs, new_name) and not _queue_exists(sqs, old_name)
+ assert param_exists(new_param) and not param_exists(old_param)
finally:
_delete_cfn_test_stack(cfn, stack_name)
+ for name in (old_name, new_name):
+ _delete_queue_if_present(sqs, name)
+ ssm.delete_parameters(Names=[old_param, new_param])
+
+
def _queue_exists(sqs, name):
try:
sqs.get_queue_url(QueueName=name)