Skip to content

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

feat(cloudformation): stack tags propagate to the resources (#1655)

iot-rocket927386d34dd2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7e64eb9e..6d6b51af 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **S3 — the Multi-Region Access Point alias starts with a letter and follows the documented pattern** — the alias was the first 13 hex characters of a uuid, so it could come out as digits only (`1240729989764.mrap`), which is not what S3 mints (`mfzwi23gnjvgw.mrap`) and made `test_cfn_s3_multi_region_access_point` fail whenever no letter was drawn (`str.islower()` is False without a cased character). The alias now follows the documented pattern `^[a-z][a-z0-9]*[.]mrap$`: a letter, then twelve lowercase letters or digits; the test checks that pattern. Contributed by @iot-rocket.
### Added
- **CloudFormation — `ListImports`, `UpdateTerminationProtection`, `SetStackPolicy`, `GetStackPolicy`, `CancelUpdateStack` and `ContinueUpdateRollback`** — the first four were routed to the service and answered `InvalidAction`, the last two did not exist, so a stack in `UPDATE_ROLLBACK_FAILED` had no way out short of a reset. `ListImports` names the stacks importing an export (a `ValidationError` when none does); termination protection is set on create or later and makes `DeleteStack` refuse with the stack unchanged (`DescribeStacks` reports `EnableTerminationProtection`); a stack policy is stored and returned (it is not enforced); `CancelUpdateStack` stops an `UPDATE_IN_PROGRESS` update before its next resource and rolls it back ("User Initiated"); `ContinueUpdateRollback` retries the deletes that failed the rollback, skips the `ResourcesToSkip` (their status becomes `UPDATE_COMPLETE`, the resource stays) and lands the stack in `UPDATE_ROLLBACK_COMPLETE`. Contributed by @iot-rocket.
+- **CloudFormation — the `Tags` property of a queue, topic, table, function, log group and stream reaches the service** — `AWS::SQS::Queue`, `AWS::SNS::Topic`, `AWS::DynamoDB::Table`, `AWS::Lambda::Function`, `AWS::Logs::LogGroup` and `AWS::Kinesis::Stream` stored their tags nowhere, so the service's own list-tags call answered an empty set for a tagged resource. The tags now land where `ListQueueTags`, `ListTagsForResource`, `ListTagsOfResource`, `ListTags`, `ListTagsLogGroup` and `ListTagsForStream` read them; a template change is reconciled on update (dropped keys removed, the rest set) and tags added through the service API stay. Contributed by @iot-rocket.
+- **CloudFormation — stack-level tags propagate to the resources** — the `Tags` of `CreateStack` and `UpdateStack` were stored on the stack record and went nowhere, and no resource carried the `aws:cloudformation:stack-name`, `aws:cloudformation:stack-id` and `aws:cloudformation:logical-id` tags a real deploy adds. For the 44 types whose provisioner stores a tag property (list-shaped `Tags`, the map-shaped `Tags` of SSM and API Gateway v2, `UserPoolTags`, `IdentityPoolTags`, `BackupVaultTags`, `BackupPlanTags`), the stack tags and the three `aws:cloudformation:` tags are merged into that property before the resource is created or updated; a key the template sets wins. A stack-tag change on `UpdateStack` reaches the resources whose type has an update handler (the 20 types without one keep their tags and are not re-created), a nested stack passes the tags on, an empty `Tags` on `UpdateStack` or a change set removes the stack's tags (as the API documents for an empty value), more than 50 tags or an `aws:` prefixed key are refused before a stack exists, and the stack record keeps the template's own properties, so change sets and the no-change check still compare templates. Contributed by @iot-rocket.
- **CloudFormation — the list and describe actions page their results** — `DescribeStacks`, `ListStacks`, `DescribeStackEvents`, `ListStackResources`, `ListExports`, `ListImports` and `ListChangeSets` answered the whole store in one response and ignored `NextToken`, so a paginator drained nothing and a caller that pages (`ListExports` pages at 100 values on AWS, the others at 1 MB) never saw a second page. They now return 100 items per page with a `NextToken` for the rest; a token the service did not hand out is a `ValidationError`. `DescribeStackEvents` also orders events of one millisecond newest first, so the pages are strictly reverse-chronological. Contributed by @iot-rocket.
- **CloudFormation — `DescribeStackResource` returns the resource `Metadata`** — the `Metadata` attribute of a resource was accepted and never returned; `StackResourceDetail` now carries it as a JSON string with intrinsics interpreted, as the API reference defines it (a CDK stack's `aws:cdk:path` is the common case); a `Metadata` that resolves away or cannot be resolved comes back as declared. Contributed by @iot-rocket.
### Fixed
diff --git a/README.md b/README.md
index f4101dcd..92ebf949 100644
--- a/README.md
+++ b/README.md
@@ -458,6 +458,7 @@ subnet = ec2.create_subnet(
| **Intrinsic Functions** | Ref, Fn::GetAtt, Fn::Join, Fn::Sub (both forms), Fn::Select, Fn::Split, Fn::If, Fn::Equals, Fn::And, Fn::Or, Fn::Not, Fn::Base64, Fn::FindInMap, Fn::ImportValue, Fn::GetAZs, Fn::Cidr |
| **Pseudo-Parameters** | AWS::StackName, AWS::StackId, AWS::Region, AWS::AccountId, AWS::URLSuffix, AWS::Partition, AWS::NoValue |
| **Parameters** | Default values, AllowedValues validation, NoEcho masking, String/Number/CommaDelimitedList types |
+| **Stack Tags** | The `Tags` of CreateStack, UpdateStack and change sets reach every resource whose type carries a tag property, together with `aws:cloudformation:stack-name`, `stack-id` and `logical-id`; a key the template sets wins |
| **Conditions** | Fn::Equals, Fn::And, Fn::Or, Fn::Not — conditional resource creation |
| **Rollback** | Configurable via `DisableRollback` — on failure, previously created resources are cleaned up in reverse dependency order |
| **Async Status** | Stacks deploy asynchronously (`CREATE_IN_PROGRESS` → `CREATE_COMPLETE`) — poll with DescribeStacks |
diff --git a/ministack/services/cloudformation/__init__.py b/ministack/services/cloudformation/__init__.py
index 2e250301..a1accfe4 100644
--- a/ministack/services/cloudformation/__init__.py
+++ b/ministack/services/cloudformation/__init__.py
@@ -51,7 +51,9 @@ async def handle_request(method: str, path: str, headers: dict,
except (json.JSONDecodeError, TypeError):
pass
elif method == "POST" and body:
- form_params = parse_qs(body.decode("utf-8", errors="replace"))
+ # keep_blank_values: an empty list arrives as ``Tags=`` and must stay
+ # distinguishable from an omitted parameter.
+ form_params = parse_qs(body.decode("utf-8", errors="replace"), keep_blank_values=True)
for k, v in form_params.items():
params[k] = v
diff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.py
index 42cb5e7e..53777d99 100644
--- a/ministack/services/cloudformation/changesets.py
+++ b/ministack/services/cloudformation/changesets.py
@@ -102,6 +102,13 @@ def _create_change_set(params):
provided_params = _extract_members(params, "Parameters")
tags = _extract_members(params, "Tags")
+ # An empty Tags list arrives as ``Tags=``: given-empty clears the stack's
+ # tags on execute, an omitted Tags keeps them (as UpdateStack does).
+ tags_given = "Tags" in params or bool(tags)
+ from .helpers import _validate_stack_tags
+ tags_error = _validate_stack_tags(tags)
+ if tags_error:
+ return tags_error
stack = _resolve_stack(stack_name)
if stack is not None and cs_type != "CREATE":
@@ -228,6 +235,7 @@ def _create_change_set(params):
for k, v in param_values.items()
],
"Tags": tags,
+ "_tags_given": tags_given,
"_template": template,
"_template_body": template_body,
"_resolved_params": param_values,
@@ -377,6 +385,7 @@ def _execute_change_set(params):
"_template_body": stack.get("_template_body", ""),
"_resolved_params": copy.deepcopy(stack.get("_resolved_params", {})),
"_conditions": copy.deepcopy(stack.get("_conditions", {})),
+ "Tags": copy.deepcopy(stack.get("Tags", [])),
"Outputs": copy.deepcopy(stack.get("Outputs", [])),
}
else:
@@ -387,7 +396,7 @@ def _execute_change_set(params):
stack["StackStatus"] = f"{status_prefix}_IN_PROGRESS"
stack["LastUpdatedTime"] = now_iso()
stack["_template_body"] = template_body
- if tags:
+ if tags or cs.get("_tags_given"):
stack["Tags"] = tags
stack["Parameters"] = [
{"ParameterKey": k, "ParameterValue": v["Value"], "NoEcho": v["NoEcho"]}
diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.py
index b0c3baaf..78d82d58 100644
--- a/ministack/services/cloudformation/handlers.py
+++ b/ministack/services/cloudformation/handlers.py
@@ -83,6 +83,10 @@ def _create_stack(params):
tags = _extract_members(params, "Tags")
disable_rollback = _p(params, "DisableRollback", "false").lower() == "true"
retain_except_on_create = _p(params, "RetainExceptOnCreate", "false").lower() == "true"
+ from .helpers import _validate_stack_tags
+ tags_error = _validate_stack_tags(tags)
+ if tags_error:
+ return tags_error
# Resolve parameters
try:
@@ -637,7 +641,7 @@ def _delete_stack(params):
# --- UpdateStack ---
def _stack_has_no_updates(stack, template, param_values, tags,
- use_previous_template=False):
+ use_previous_template=False, tags_given=False):
"""True when an UpdateStack would change nothing: the template equals the
one the stack runs, every parameter resolves to its current value, and the
request either carries no tags or the tags the stack already has. Real
@@ -652,7 +656,7 @@ def _stack_has_no_updates(stack, template, param_values, tags,
current = {k: v.get("Value") for k, v in stack.get("_resolved_params", {}).items()}
if {k: v.get("Value") for k, v in param_values.items()} != current:
return False
- if tags and tags != stack.get("Tags", []):
+ if (tags or tags_given) and tags != stack.get("Tags", []):
return False
return True
@@ -706,6 +710,14 @@ def _update_stack(params):
tags = _extract_members(params, "Tags")
disable_rollback = _p(params, "DisableRollback", "false").lower() == "true"
retain_except_on_create = _p(params, "RetainExceptOnCreate", "false").lower() == "true"
+ # botocore sends an empty Tags list as ``Tags=``: given and empty clears
+ # the stack's tags ("If you specify an empty value, CloudFormation
+ # removes all associated tags"); an omitted Tags keeps them.
+ tags_given = "Tags" in params or bool(tags)
+ from .helpers import _validate_stack_tags
+ tags_error = _validate_stack_tags(tags)
+ if tags_error:
+ return tags_error
try:
param_values = _resolve_parameters(
@@ -720,7 +732,7 @@ def _update_stack(params):
return _error("ValidationError", str(exc))
if _stack_has_no_updates(stack, template, param_values, tags,
- use_previous_template):
+ use_previous_template, tags_given):
return _error("ValidationError", "No updates are to be performed.")
# Save previous state for rollback
@@ -755,7 +767,7 @@ def _update_stack(params):
stack["StackStatus"] = "UPDATE_IN_PROGRESS"
stack["LastUpdatedTime"] = now_iso()
stack["_template_body"] = template_body
- if tags:
+ if tags or tags_given:
stack["Tags"] = tags
stack["Parameters"] = [
{"ParameterKey": k, "ParameterValue": v["Value"], "NoEcho": v["NoEcho"]}
diff --git a/ministack/services/cloudformation/helpers.py b/ministack/services/cloudformation/helpers.py
index b0110650..1f96773e 100644
--- a/ministack/services/cloudformation/helpers.py
+++ b/ministack/services/cloudformation/helpers.py
@@ -62,6 +62,31 @@ def _extract_members(params, prefix):
i += 1
return result
+def _validate_stack_tags(tags):
+ """The checks CreateStack, UpdateStack and CreateChangeSet apply to the
+ stack-level ``Tags``: at most 50, no ``aws:`` prefix (reserved for AWS),
+ keys up to 128 and values up to 256 characters. Returns the error
+ response, or None when the tags pass."""
+ if len(tags) > 50:
+ return _error("ValidationError", "A maximum number of 50 tags can be specified")
+ for tag in tags:
+ key = str(tag.get("Key", ""))
+ value = str(tag.get("Value", ""))
+ if key.lower().startswith("aws:"):
+ return _error(
+ "ValidationError",
+ f"Tag key '{key}' is reserved: the aws: prefix cannot be used")
+ if len(key) > 128:
+ return _error(
+ "ValidationError",
+ f"Tag key '{key[:32]}...' exceeds the maximum length of 128 characters")
+ if len(value) > 256:
+ return _error(
+ "ValidationError",
+ f"Tag value for key '{key}' exceeds the maximum length of 256 characters")
+ return None
+
+
def _resolve_template(params):
"""Resolve TemplateBody or TemplateURL to a template string.
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 7f679abe..571bcd91 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -499,12 +499,24 @@ def _update_resource(resource_type: str, physical_id: str, old_props: dict,
# still referencing it via Ref/Fn::GetAtt would then pick up the
# instant it was reprocessed later in the same update.
return physical_id, old_attrs or {}
+ handler = _RESOURCE_HANDLERS.get(resource_type)
+ tag_spec = _STACK_TAG_PROPERTY.get(resource_type)
+ if tag_spec and not (handler and "update" in handler):
+ # Only the tag property differs (a stack-tag change reaches every
+ # tagged resource): without an update handler the fallback below
+ # would re-create the resource under a new physical id. The tags
+ # stay as they are rather than that.
+ tag_prop = tag_spec[0]
+ if ({k: v for k, v in old_props.items() if k != tag_prop}
+ == {k: v for k, v in new_props.items() if k != tag_prop}):
+ logger.debug("Tag-only change on %s %s ignored: no update handler",
+ resource_type, physical_id)
+ return physical_id, old_attrs or {}
replacement_error = _custom_named_replacement_error(
resource_type, old_props, new_props
)
if replacement_error:
raise ValueError(replacement_error)
- handler = _RESOURCE_HANDLERS.get(resource_type)
if handler and "update" in handler:
if handler.get("update_with_logical_id"):
return handler["update"](
@@ -527,6 +539,136 @@ def _update_resource(resource_type: str, physical_id: str, old_props: dict,
return _provision_resource(resource_type, logical_id or physical_id, new_props, stack_name)
+# ---------------------------------------------------------------------------
+# Tags
+# ---------------------------------------------------------------------------
+
+def _tag_map(tags) -> dict:
+ """The ``{Key: Value}`` view of a CloudFormation ``Tags`` property; a map
+ (the shape SSM and API Gateway v2 use) passes through."""
+ if isinstance(tags, dict):
+ return {str(k): str(v) for k, v in tags.items()}
+ return {
+ str(t["Key"]): str(t.get("Value", ""))
+ for t in (tags or [])
+ if isinstance(t, dict) and "Key" in t
+ }
+
+
+def _reconcile_tag_map(store: dict, old_props: dict, new_props: dict,
+ prop: str = "Tags") -> None:
+ """Apply a tag property change to a service's ``{key: value}`` tag
+ store: keys the template dropped are removed, the rest set. Tags added
+ through the service's own tagging API stay untouched, as on AWS."""
+ old_tags = _tag_map(old_props.get(prop))
+ new_tags = _tag_map(new_props.get(prop))
+ if old_tags == new_tags:
+ return
+ for key in old_tags.keys() - new_tags.keys():
+ store.pop(key, None)
+ store.update(new_tags)
+
+
+def _reconcile_tag_list(store: list, old_props: dict, new_props: dict,
+ key: str = "Key", value: str = "Value") -> None:
+ """The list-store twin of ``_reconcile_tag_map``: entries the template
+ dropped are removed, the new ones set, entries from elsewhere kept. The
+ list is changed in place; ``key``/``value`` name the entry fields."""
+ old_tags = _tag_map(old_props.get("Tags"))
+ new_tags = _tag_map(new_props.get("Tags"))
+ if old_tags == new_tags:
+ return
+ store[:] = [
+ t for t in store
+ if t.get(key) not in old_tags and t.get(key) not in new_tags
+ ] + [{key: k, value: v} for k, v in new_tags.items()]
+
+
+# The types whose provisioner stores a tag property, with that property's name
+# and shape. Stack-level tags and the three ``aws:cloudformation:`` tags are
+# merged into the property before the resource is created or updated; a type
+# outside this table has no tag store the stack tags could reach.
+_STACK_TAG_PROPERTY: dict[str, tuple[str, str]] = {
+ "AWS::ApiGateway::ApiKey": ("Tags", "list"),
+ "AWS::ApiGateway::DomainName": ("Tags", "list"),
+ "AWS::ApiGateway::RestApi": ("Tags", "list"),
+ "AWS::ApiGateway::Stage": ("Tags", "list"),
+ "AWS::ApiGateway::UsagePlan": ("Tags", "list"),
+ "AWS::ApiGatewayV2::Api": ("Tags", "map"),
+ "AWS::ApiGatewayV2::Stage": ("Tags", "map"),
+ "AWS::AppConfig::Application": ("Tags", "list"),
+ "AWS::AppConfig::ConfigurationProfile": ("Tags", "list"),
+ "AWS::AppConfig::Deployment": ("Tags", "list"),
+ "AWS::AppConfig::DeploymentStrategy": ("Tags", "list"),
+ "AWS::AppConfig::Environment": ("Tags", "list"),
+ "AWS::AutoScaling::AutoScalingGroup": ("Tags", "list"),
+ "AWS::Backup::BackupPlan": ("BackupPlanTags", "map"),
+ "AWS::Backup::BackupVault": ("BackupVaultTags", "map"),
+ "AWS::CertificateManager::Certificate": ("Tags", "list"),
+ "AWS::CloudFormation::Stack": ("Tags", "list"),
+ "AWS::CloudWatch::Alarm": ("Tags", "list"),
+ "AWS::CodeBuild::Project": ("Tags", "list"),
+ "AWS::Cognito::IdentityPool": ("IdentityPoolTags", "map"),
+ "AWS::Cognito::UserPool": ("UserPoolTags", "map"),
+ "AWS::DynamoDB::Table": ("Tags", "list"),
+ "AWS::EC2::VPCEndpoint": ("Tags", "list"),
+ "AWS::ECS::Cluster": ("Tags", "list"),
+ "AWS::ECS::Service": ("Tags", "list"),
+ "AWS::EKS::Cluster": ("Tags", "list"),
+ "AWS::EKS::Nodegroup": ("Tags", "map"),
+ "AWS::ElasticLoadBalancingV2::Listener": ("Tags", "list"),
+ "AWS::ElasticLoadBalancingV2::LoadBalancer": ("Tags", "list"),
+ "AWS::ElasticLoadBalancingV2::TargetGroup": ("Tags", "list"),
+ "AWS::Events::EventBus": ("Tags", "list"),
+ "AWS::IAM::Role": ("Tags", "list"),
+ "AWS::KMS::Key": ("Tags", "list"),
+ "AWS::Kinesis::Stream": ("Tags", "list"),
+ "AWS::Lambda::Function": ("Tags", "list"),
+ "AWS::Logs::LogGroup": ("Tags", "list"),
+ "AWS::OpenSearchService::Domain": ("Tags", "list"),
+ "AWS::RDS::DBInstance": ("Tags", "list"),
+ "AWS::SNS::Topic": ("Tags", "list"),
+ "AWS::SQS::Queue": ("Tags", "list"),
+ "AWS::SSM::Parameter": ("Tags", "map"),
+ "AWS::Scheduler::ScheduleGroup": ("Tags", "list"),
+ "AWS::SecretsManager::Secret": ("Tags", "list"),
+ "AWS::StepFunctions::StateMachine": ("Tags", "list"),
+}
+
+
+def _with_stack_tags(resource_type: str, props: dict, stack_tags: list,
+ stack_name: str, stack_id: str, logical_id: str) -> dict:
+ """The properties a resource is provisioned with: the template's own tag
+ property plus the stack-level tags and the three ``aws:cloudformation:``
+ tags CloudFormation adds, for the types in ``_STACK_TAG_PROPERTY``. A key
+ the template sets wins over the stack-level tag of the same name. Returns
+ ``props`` itself for every other type, and a copy otherwise: the stack
+ record keeps the template's properties."""
+ spec = _STACK_TAG_PROPERTY.get(resource_type)
+ if spec is None:
+ return props
+ prop, shape = spec
+ extra = _tag_map(stack_tags)
+ extra["aws:cloudformation:stack-name"] = stack_name
+ extra["aws:cloudformation:stack-id"] = stack_id
+ extra["aws:cloudformation:logical-id"] = logical_id
+ own = props.get(prop)
+ if shape == "map":
+ merged = {**extra, **(own if isinstance(own, dict) else _tag_map(own))}
+ else:
+ if isinstance(own, dict):
+ own = [{"Key": key, "Value": value} for key, value in own.items()]
+ own_list = [t for t in (own or []) if isinstance(t, dict) and "Key" in t]
+ present = {t["Key"] for t in own_list}
+ merged = own_list + [
+ {"Key": key, "Value": value}
+ for key, value in extra.items() if key not in present
+ ]
+ out = dict(props)
+ out[prop] = merged
+ return out
+
+
# ===========================================================================
# Resource Provisioners
# ===========================================================================
@@ -877,7 +1019,7 @@ def _sqs_create(logical_id, props, stack_name):
"is_fifo": is_fifo,
"attributes": attributes,
"messages": [],
- "tags": {},
+ "tags": _tag_map(props.get("Tags")),
"dedup_cache": {},
"fifo_seq": 0,
}
@@ -919,6 +1061,7 @@ def _sqs_update(physical_id, old_props, new_props, stack_name, logical_id=None):
).lower()
else:
attributes.pop("ContentBasedDeduplication", None)
+ _reconcile_tag_map(queue.setdefault("tags", {}), old_props, new_props)
attributes["LastModifiedTimestamp"] = str(int(time.time()))
arn = attributes["QueueArn"]
return physical_id, {"Arn": arn, "QueueName": name, "QueueUrl": physical_id}
@@ -969,7 +1112,7 @@ def _sns_create(logical_id, props, stack_name):
},
"subscriptions": [],
"messages": [],
- "tags": {},
+ "tags": _tag_map(props.get("Tags")),
}
# Handle Subscription property. The private _cfn_inline marker is what
@@ -1013,6 +1156,7 @@ def _sns_update(physical_id, old_props, new_props, stack_name, logical_id=None):
if replaced is not None:
return replaced
topic["attributes"]["DisplayName"] = new_props.get("DisplayName", name)
+ _reconcile_tag_map(topic.setdefault("tags", {}), old_props, new_props)
# Reconcile the template-inline subscriptions by (Protocol, Endpoint).
# Only records carrying the _cfn_inline marker are eligible for removal:
# a standalone AWS::SNS::Subscription resource (or a plain Subscribe call)
@@ -1153,6 +1297,10 @@ def _ddb_create(logical_id, props, stack_name):
"Tags": [],
}
_dynamodb._tables[name] = table
+ if props.get("Tags"):
+ _dynamodb._tags[arn] = [
+ {"Key": k, "Value": v} for k, v in _tag_map(props["Tags"]).items()
+ ]
attrs = {"Arn": arn}
if stream_arn:
@@ -1203,6 +1351,9 @@ def _ddb_update(physical_id, old_props, new_props, stack_name, logical_id=None):
_ddb_delete(physical_id, old_props)
return _ddb_create(logical_id or physical_id, new_props, stack_name)
+ _reconcile_tag_list(
+ _dynamodb._tags.setdefault(table["TableArn"], []), old_props, new_props)
+
data = {"TableName": name}
old_billing = old_props.get("BillingMode", "PROVISIONED")
new_billing = new_props.get("BillingMode", "PROVISIONED")
@@ -1387,7 +1538,7 @@ def _lambda_create(logical_id, props, stack_name):
"code_s3_object_version": code.get("S3ObjectVersion"),
"versions": {},
"next_version": 1,
- "tags": {},
+ "tags": _tag_map(props.get("Tags")),
"policy": {"Version": "2012-10-17", "Id": "default", "Statement": []},
"event_invoke_config": None,
"event_invoke_configs": {},
@@ -1495,6 +1646,7 @@ def _lambda_update(physical_id, old_props, new_props, stack_name, logical_id=Non
resp = _lambda_svc._update_config(name, config_data)
if resp[0] >= 400:
raise ValueError(f"AWS::Lambda::Function configuration update failed: {resp[2]!r}")
+ _reconcile_tag_map(func.setdefault("tags", {}), old_props, new_props)
return name, {"Arn": func["config"]["FunctionArn"]}
@@ -1946,9 +2098,15 @@ def _ssm_update(physical_id, old_props, new_props, stack_name):
# pinned Version at 1 forever).
data = _ssm_put_data(physical_id, new_props)
data["Overwrite"] = True
+ # PutParameter replaces the parameter's tag set; reconcile it instead so
+ # tags added through AddTagsToResource stay.
+ data.pop("Tags", None)
status, _headers, body = _ssm._put_parameter(data)
if status >= 400:
raise ValueError(f"AWS::SSM::Parameter update failed: {body!r}")
+ _reconcile_tag_map(
+ _ssm._tags.setdefault(_ssm._param_arn(physical_id), {}), old_props, new_props
+ )
return physical_id, _ssm_attrs(physical_id, data)
@@ -2215,7 +2373,7 @@ def _cwlogs_create(logical_id, props, stack_name):
"arn": arn,
"creationTime": int(time.time() * 1000),
"retentionInDays": int(retention) if retention else None,
- "tags": {},
+ "tags": _tag_map(props.get("Tags")),
"streams": {},
"subscriptionFilters": {},
}
@@ -2237,6 +2395,7 @@ def _cwlogs_update(physical_id, old_props, new_props, stack_name, logical_id=Non
return replaced
retention = new_props.get("RetentionInDays")
group["retentionInDays"] = int(retention) if retention else None
+ _reconcile_tag_map(group.setdefault("tags", {}), old_props, new_props)
return name, {"Arn": group["arn"]}
@@ -2564,7 +2723,7 @@ def _eks_nodegroup_create(logical_id, props, stack_name):
"amiType": props.get("AmiType", "AL2_x86_64"),
"diskSize": props.get("DiskSize", 20),
"labels": props.get("Labels", {}),
- "tags": {t["Key"]: t["Value"] for t in props.get("Tags", [])},
+ "tags": _tag_map(props.get("Tags")),
}
_eks._create_nodegroup(cluster_name, body)
key = f"{cluster_name}/{ng_name}"
@@ -2631,7 +2790,7 @@ def _kinesis_stream_create(logical_id, props, stack_name):
"StreamModeDetails": {"StreamMode": stream_mode},
"RetentionPeriodHours": retention,
"shards": _kinesis._build_shards(shard_count),
- "tags": {},
+ "tags": _tag_map(props.get("Tags")),
"CreationTimestamp": int(time.time()),
"EncryptionType": "NONE",
}
@@ -2909,7 +3068,11 @@ def _cfn_nested_stack_deploy(logical_id, props, parent_stack_name, *,
{"ParameterKey": k, "ParameterValue": v["Value"], "NoEcho": v["NoEcho"]}
for k, v in param_values.items()
],
- "Tags": [],
+ "Tags": [
+ {"Key": key, "Value": value}
+ for key, value in _tag_map(props.get("Tags")).items()
+ if not key.startswith("aws:")
+ ],
"Outputs": [],
"DisableRollback": True,
"_resources": (previous_stack_snapshot.get("_resources", {})
@@ -2967,15 +3130,21 @@ def _cfn_nested_stack_deploy(logical_id, props, parent_stack_name, *,
f"{status_prefix}_IN_PROGRESS")
try:
prev = prev_resources.get(child_logical_id)
+ new_tagged = _with_stack_tags(
+ resource_type, resolved_props, child_stack["Tags"],
+ child_name, child_stack_id, child_logical_id)
if prev:
+ old_tagged = _with_stack_tags(
+ resource_type, prev.get("Properties", {}),
+ (previous_stack_snapshot or {}).get("Tags") or [],
+ child_name, child_stack_id, child_logical_id)
physical_id, attrs = _update_resource(
resource_type, prev.get("PhysicalResourceId", child_logical_id),
- prev.get("Properties", {}), resolved_props, child_name,
- child_logical_id,
+ old_tagged, new_tagged, child_name, child_logical_id,
)
else:
physical_id, attrs = _provision_resource(
- resource_type, child_logical_id, resolved_props, child_name,
+ resource_type, child_logical_id, new_tagged, child_name,
)
except Exception as exc:
child_stack["StackStatus"] = f"{status_prefix}_FAILED"
@@ -3628,13 +3797,6 @@ def _apigw_stage_delete(physical_id, props):
# --- API Gateway ApiKey / UsagePlan (v1) ---
-def _apigw_tag_map(raw):
- """Normalize CFN ``Tags`` (a map, or a list of {Key, Value}) to a dict."""
- if isinstance(raw, dict):
- return dict(raw)
- return {t["Key"]: t["Value"] for t in raw or []}
-
-
def _apigw_throttle(raw):
"""Map a CFN ThrottleSettings block to the API Gateway wire shape."""
if not raw:
@@ -3674,7 +3836,7 @@ def _apigw_api_key_create(logical_id, props, stack_name):
{"restApiId": sk.get("RestApiId", ""), "stageName": sk.get("StageName", "")}
for sk in props.get("StageKeys", [])
],
- "tags": _apigw_tag_map(props.get("Tags")),
+ "tags": _tag_map(props.get("Tags")),
}
status, _headers, body = _apigw_v1._create_api_key(data)
if status >= 400:
@@ -3708,6 +3870,7 @@ def _apigw_api_key_update(physical_id, old_props, new_props, stack_name):
key["enabled"] = new_props.get("Enabled", True)
key["customerId"] = new_props.get("CustomerId", key.get("customerId", ""))
key["lastUpdatedDate"] = _apigw_v1._now_unix()
+ _reconcile_tag_map(key.setdefault("tags", {}), old_props, new_props)
return physical_id, {"APIKeyId": physical_id}
@@ -3730,7 +3893,7 @@ def _apigw_usage_plan_body(props):
],
"throttle": _apigw_throttle(props.get("Throttle")),
"quota": _apigw_quota(props.get("Quota")),
- "tags": _apigw_tag_map(props.get("Tags")),
+ "tags": _tag_map(props.get("Tags")),
}
@@ -3755,7 +3918,10 @@ def _apigw_usage_plan_update(physical_id, old_props, new_props, stack_name):
return _apigw_usage_plan_create(physical_id, new_props, stack_name)
if new_props.get("UsagePlanName"):
plan["name"] = new_props["UsagePlanName"]
- plan.update(_apigw_usage_plan_body(new_props))
+ body = _apigw_usage_plan_body(new_props)
+ body["tags"] = dict(plan.get("tags") or {})
+ _reconcile_tag_map(body["tags"], old_props, new_props)
+ plan.update(body)
return physical_id, {"Id": physical_id}
@@ -4595,10 +4761,9 @@ def _sm_secret_update(physical_id, old_props, new_props, stack_name, logical_id=
resp = _sm._update_secret(data)
if resp[0] >= 400:
raise ValueError(f"AWS::SecretsManager::Secret update failed: {resp[2]!r}")
- if "Tags" in new_props or "Tags" in old_props:
- # Same rule as above: tags applied through TagResource on a secret
- # whose template never declared any are not the stack's to clear.
- secret["Tags"] = list(new_props.get("Tags", []))
+ # Keys the template dropped go, the rest are set; tags applied through
+ # TagResource are not the stack's to clear.
+ _reconcile_tag_list(secret.setdefault("Tags", []), old_props, new_props)
if new_props.get("ReplicaRegions") and new_props["ReplicaRegions"] != old_props.get("ReplicaRegions"):
# Regions added or re-keyed since the previous template are applied;
# a region dropped from the template keeps its replica, the service
@@ -5030,6 +5195,8 @@ def _cognito_identity_pool_create(logical_id, props, stack_name):
"_identities": {},
}
_cognito._identity_pools[iid] = pool
+ # ListTagsForResource reads the pool's tag store, not the record.
+ _cognito._identity_tags[iid] = _tag_map(props.get("IdentityPoolTags"))
# The one Fn::GetAtt the resource reference lists is Name.
return iid, {"Name": name}
@@ -5068,6 +5235,8 @@ def _cognito_identity_pool_update(physical_id, old_props, new_props, stack_name,
status, _, body = _cognito._update_identity_pool(payload)
if status >= 400:
raise ValueError(f"AWS::Cognito::IdentityPool update failed: {body!r}")
+ _reconcile_tag_map(_cognito._identity_tags.setdefault(physical_id, {}),
+ old_props, new_props, prop="IdentityPoolTags")
return physical_id, {"Name": name}
@@ -8189,6 +8358,7 @@ def _kinesis_stream_update(physical_id, old_props, new_props, stack_name):
smd = new_props.get("StreamModeDetails")
if isinstance(smd, dict) and smd.get("StreamMode"):
stream["StreamModeDetails"] = {"StreamMode": smd["StreamMode"]}
+ _reconcile_tag_map(stream.setdefault("tags", {}), old_props, new_props)
# ShardCount changes keep the existing shards — records live in them.
return physical_id, {"Arn": stream["StreamARN"]}
@@ -8227,7 +8397,9 @@ def _eb_event_bus_update(physical_id, old_props, new_props, stack_name):
if bus is not None and isinstance(bus, dict):
if "Description" in new_props:
bus["Description"] = new_props["Description"]
- return physical_id, {"Arn": f"arn:aws:events:{get_region()}:{get_account_id()}:event-bus/{physical_id}", "Name": physical_id}
+ arn = f"arn:aws:events:{get_region()}:{get_account_id()}:event-bus/{physical_id}"
+ _reconcile_tag_map(_eb._tags.setdefault(arn, {}), old_props, new_props)
+ return physical_id, {"Arn": arn, "Name": physical_id}
def _codebuild_project_update(physical_id, old_props, new_props, stack_name):
@@ -8242,6 +8414,8 @@ def _codebuild_project_update(physical_id, old_props, new_props, stack_name):
project[key] = new_props[prop]
if "TimeoutInMinutes" in new_props:
project["timeoutInMinutes"] = int(new_props["TimeoutInMinutes"])
+ _reconcile_tag_list(project.setdefault("tags", []), old_props, new_props,
+ key="key", value="value")
return physical_id, {"Arn": _codebuild._project_arn(physical_id)}
diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.py
index d03f46e4..2c692608 100644
--- a/ministack/services/cloudformation/stacks.py
+++ b/ministack/services/cloudformation/stacks.py
@@ -24,6 +24,7 @@ from .provisioners import (
_delete_resource,
_provision_resource,
_update_resource,
+ _with_stack_tags,
)
logger = logging.getLogger("cloudformation")
@@ -246,6 +247,11 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
provisioned_resources: dict = stack.get("_resources", {})
created_in_this_run = []
+ # Stack-level tags reach the resources through their own tag property;
+ # the stack record keeps the template's properties (below), so the
+ # change-set diff and the next update compare templates, not tags.
+ stack_tags = stack.get("Tags") or []
+ previous_tags = (previous_stack or {}).get("Tags") or []
# If update: figure out what to add/modify/remove
if is_update and previous_stack:
@@ -334,15 +340,21 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
param_values, conditions, mappings, stack_name, stack_id,
) in _RETAINING_POLICIES
token = _RETAIN_REPLACED.set(retain_replaced)
+ old_tagged = _with_stack_tags(
+ resource_type, old_props, previous_tags,
+ stack_name, stack_id, logical_id)
+ new_tagged = _with_stack_tags(
+ resource_type, resolved_props, stack_tags,
+ stack_name, stack_id, logical_id)
try:
if _is_custom_resource(resource_type):
physical_id, attrs = await run_reentrant(
- _update_resource, resource_type, old_pid, old_props,
- resolved_props, stack_name, logical_id, old_attrs
+ _update_resource, resource_type, old_pid, old_tagged,
+ new_tagged, stack_name, logical_id, old_attrs
)
else:
physical_id, attrs = _update_resource(
- resource_type, old_pid, old_props, resolved_props,
+ resource_type, old_pid, old_tagged, new_tagged,
stack_name, logical_id, old_attrs
)
finally:
@@ -355,13 +367,16 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
replaced_resources.append(
(logical_id, resource_type, old_pid, old_props))
else:
+ new_tagged = _with_stack_tags(
+ resource_type, resolved_props, stack_tags,
+ stack_name, stack_id, logical_id)
if _is_custom_resource(resource_type):
physical_id, attrs = await run_reentrant(
- _provision_resource, resource_type, logical_id, resolved_props, stack_name
+ _provision_resource, resource_type, logical_id, new_tagged, stack_name
)
else:
physical_id, attrs = _provision_resource(
- resource_type, logical_id, resolved_props, stack_name
+ resource_type, logical_id, new_tagged, stack_name
)
except Exception as exc:
logger.error("Failed to provision %s (%s): %s",
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 367ad515..bf58498b 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -121,6 +121,20 @@ def _stack_event_reasons(cfn, stack_name):
)
+def _template_tags(value):
+ """`value` without the ``aws:cloudformation:`` tags every stack resource
+ carries since stack tags propagate: what the template itself set. Tag
+ dicts, ``Key``/``Value`` lists and ``TagKey``/``TagValue`` lists are
+ filtered; anything else is returned as is."""
+ if isinstance(value, dict):
+ return {k: v for k, v in value.items() if not str(k).startswith("aws:")}
+ if isinstance(value, list) and value and all(
+ isinstance(t, dict) and ("Key" in t or "TagKey" in t) for t in value
+ ):
+ return [t for t in value if not str(t.get("Key", t.get("TagKey"))).startswith("aws:")]
+ return value
+
+
def test_cfn_region_scopes_stacks_change_sets_and_events():
suffix = _uuid_mod.uuid4().hex[:8]
stack_name = f"cfn-regional-{suffix}"
@@ -4266,7 +4280,7 @@ def test_cfn_ec2_vpc_endpoint_uses_ec2_state(cfn, ec2):
assert len(endpoints) == 1
assert endpoints[0]["VpcEndpointId"] == outputs["RefId"]
assert endpoints[0]["ServiceName"] == "com.amazonaws.us-east-1.s3"
- assert endpoints[0]["Tags"] == [{"Key": "source", "Value": "cloudformation"}]
+ assert _template_tags(endpoints[0]["Tags"]) == [{"Key": "source", "Value": "cloudformation"}]
cfn.delete_stack(StackName=stack_name)
_wait_stack(cfn, stack_name)
@@ -5811,6 +5825,770 @@ def test_cfn_eventbus_default_name_fails(cfn, eb):
assert bus["Name"] == "default"
+# --- Tags: the Tags property of the common types, stack-level tags ---
+
+def _cfn_tag_template(tags):
+ return {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Queue": {"Type": "AWS::SQS::Queue", "Properties": {"Tags": tags}},
+ "Topic": {"Type": "AWS::SNS::Topic", "Properties": {"Tags": tags}},
+ "Table": {
+ "Type": "AWS::DynamoDB::Table",
+ "Properties": {
+ "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
+ "BillingMode": "PAY_PER_REQUEST",
+ "Tags": tags,
+ },
+ },
+ "Fn": {
+ "Type": "AWS::Lambda::Function",
+ "Properties": {
+ "Runtime": "python3.12",
+ "Handler": "index.handler",
+ "Role": "arn:aws:iam::000000000000:role/cfn-tags-role",
+ "Code": {"ZipFile": "def handler(e, c): return {}"},
+ "Tags": tags,
+ },
+ },
+ "Logs": {"Type": "AWS::Logs::LogGroup", "Properties": {"Tags": tags}},
+ "Stream": {
+ "Type": "AWS::Kinesis::Stream",
+ "Properties": {"ShardCount": 1, "Tags": tags},
+ },
+ },
+ "Outputs": {
+ "QueueUrl": {"Value": {"Ref": "Queue"}},
+ "TopicArn": {"Value": {"Ref": "Topic"}},
+ "TableArn": {"Value": {"Fn::GetAtt": ["Table", "Arn"]}},
+ "FnArn": {"Value": {"Fn::GetAtt": ["Fn", "Arn"]}},
+ "LogGroup": {"Value": {"Ref": "Logs"}},
+ "StreamName": {"Value": {"Ref": "Stream"}},
+ },
+ }
+
+
+def _cfn_tag_readback(sqs, sns, ddb, lam, logs, kin, stack):
+ """The tags each service reports for the resources of `stack`, keyed by
+ logical id, as {key: value} maps."""
+ return {
+ "Queue": sqs.list_queue_tags(QueueUrl=_output(stack, "QueueUrl")).get("Tags", {}),
+ "Topic": {
+ t["Key"]: t["Value"]
+ for t in sns.list_tags_for_resource(ResourceArn=_output(stack, "TopicArn"))["Tags"]
+ },
+ "Table": {
+ t["Key"]: t["Value"]
+ for t in ddb.list_tags_of_resource(ResourceArn=_output(stack, "TableArn"))["Tags"]
+ },
+ "Fn": lam.list_tags(Resource=_output(stack, "FnArn"))["Tags"],
+ "Logs": logs.list_tags_log_group(logGroupName=_output(stack, "LogGroup"))["tags"],
+ "Stream": {
+ t["Key"]: t["Value"]
+ for t in kin.list_tags_for_stream(StreamName=_output(stack, "StreamName"))["Tags"]
+ },
+ }
+
+
+def test_cfn_resource_tags_reach_the_service(cfn, sqs, sns, ddb, lam, logs, kin):
+ """The Tags property of a queue, topic, table, function, log group and
+ stream is stored where the service's own tag API reads it, and a template
+ change to it is reconciled on update without touching tags added through
+ that API."""
+ name = f"cfn-res-tags-{_uuid_mod.uuid4().hex[:8]}"
+ first = [{"Key": "env", "Value": "test"}, {"Key": "team", "Value": "platform"}]
+ cfn.create_stack(StackName=name, TemplateBody=json.dumps(_cfn_tag_template(first)))
+ try:
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+ seen = _cfn_tag_readback(sqs, sns, ddb, lam, logs, kin, stack)
+ for logical_id, tags in seen.items():
+ assert _template_tags(tags) == {"env": "test", "team": "platform"}, logical_id
+
+ # A tag set through the service API is not CloudFormation's to remove.
+ sqs.tag_queue(QueueUrl=_output(stack, "QueueUrl"), Tags={"manual": "yes"})
+ lam.tag_resource(Resource=_output(stack, "FnArn"), Tags={"manual": "yes"})
+
+ second = [{"Key": "env", "Value": "prod"}, {"Key": "owner", "Value": "ops"}]
+ cfn.update_stack(StackName=name, TemplateBody=json.dumps(_cfn_tag_template(second)))
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE"
+ seen = _cfn_tag_readback(sqs, sns, ddb, lam, logs, kin, stack)
+ for logical_id in ("Topic", "Table", "Logs", "Stream"):
+ assert _template_tags(seen[logical_id]) == {"env": "prod", "owner": "ops"}, logical_id
+ assert _template_tags(seen["Queue"]) == {"env": "prod", "owner": "ops", "manual": "yes"}
+ assert _template_tags(seen["Fn"]) == {"env": "prod", "owner": "ops", "manual": "yes"}
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
+def _system_tags(stack, logical_id):
+ return {
+ "aws:cloudformation:stack-name": stack["StackName"],
+ "aws:cloudformation:stack-id": stack["StackId"],
+ "aws:cloudformation:logical-id": logical_id,
+ }
+
+
+def test_cfn_stack_tags_reach_the_resources(cfn, sqs, ssm):
+ """Stack-level tags and the three aws:cloudformation tags land on the
+ resources (a list-shaped Tags property and a map-shaped one), the
+ template's own tag wins on a shared key, and a stack-tag change on update
+ reaches the resources."""
+ name = f"cfn-stack-tags-{_uuid_mod.uuid4().hex[:8]}"
+ template = {
+ "Resources": {
+ "Q": {
+ "Type": "AWS::SQS::Queue",
+ "Properties": {"Tags": [{"Key": "env", "Value": "template"}]},
+ },
+ "P": {
+ "Type": "AWS::SSM::Parameter",
+ "Properties": {
+ "Name": f"/{name}/p",
+ "Type": "String",
+ "Value": "v",
+ "Tags": {"tier": "gold"},
+ },
+ },
+ },
+ "Outputs": {"QueueUrl": {"Value": {"Ref": "Q"}}},
+ }
+ cfn.create_stack(
+ StackName=name,
+ TemplateBody=json.dumps(template),
+ Tags=[{"Key": "owner", "Value": "team-a"}, {"Key": "env", "Value": "stack"}],
+ )
+ try:
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ queue_url = _output(stack, "QueueUrl")
+ assert sqs.list_queue_tags(QueueUrl=queue_url)["Tags"] == {
+ "env": "template",
+ "owner": "team-a",
+ **_system_tags(stack, "Q"),
+ }
+ param_tags = {
+ t["Key"]: t["Value"]
+ for t in ssm.list_tags_for_resource(
+ ResourceType="Parameter", ResourceId=f"/{name}/p"
+ )["TagList"]
+ }
+ assert param_tags == {
+ "tier": "gold",
+ "owner": "team-a",
+ "env": "stack",
+ **_system_tags(stack, "P"),
+ }
+ # An unchanged template with changed stack tags is an update (the tag
+ # change reaches the resources); the same tags again are refused.
+ with pytest.raises(ClientError, match="No updates are to be performed"):
+ cfn.update_stack(
+ StackName=name,
+ UsePreviousTemplate=True,
+ Tags=[{"Key": "owner", "Value": "team-a"}, {"Key": "env", "Value": "stack"}],
+ )
+
+ cfn.update_stack(
+ StackName=name,
+ UsePreviousTemplate=True,
+ Tags=[{"Key": "owner", "Value": "team-b"}, {"Key": "cost", "Value": "42"}],
+ )
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert sqs.list_queue_tags(QueueUrl=queue_url)["Tags"] == {
+ "env": "template",
+ "owner": "team-b",
+ "cost": "42",
+ **_system_tags(stack, "Q"),
+ }
+ param_tags = {
+ t["Key"]: t["Value"]
+ for t in ssm.list_tags_for_resource(
+ ResourceType="Parameter", ResourceId=f"/{name}/p"
+ )["TagList"]
+ }
+ assert param_tags == {
+ "tier": "gold",
+ "owner": "team-b",
+ "cost": "42",
+ **_system_tags(stack, "P"),
+ }
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
+def test_cfn_stack_tags_reach_a_nested_stack(cfn, s3, sqs):
+ """The parent's stack tags reach the resources of a nested stack; the
+ aws:cloudformation tags carry the nested stack's own name and id."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ templates_bucket = f"cfn-tags-templates-{suffix}"
+ child_template = {
+ "Resources": {"Q": {"Type": "AWS::SQS::Queue"}},
+ "Outputs": {"QueueUrl": {"Value": {"Ref": "Q"}}},
+ }
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")
+ parent_template = {
+ "Resources": {
+ "Nested": {
+ "Type": "AWS::CloudFormation::Stack",
+ "Properties": {"TemplateURL": f"{endpoint}/{templates_bucket}/child.json"},
+ },
+ },
+ "Outputs": {
+ "QueueUrl": {"Value": {"Fn::GetAtt": ["Nested", "Outputs.QueueUrl"]}},
+ "NestedId": {"Value": {"Ref": "Nested"}},
+ },
+ }
+ parent_name = f"cfn-tags-parent-{suffix}"
+ s3.create_bucket(Bucket=templates_bucket)
+ try:
+ s3.put_object(Bucket=templates_bucket, Key="child.json",
+ Body=json.dumps(child_template).encode())
+ cfn.create_stack(
+ StackName=parent_name,
+ TemplateBody=json.dumps(parent_template),
+ Tags=[{"Key": "owner", "Value": "team-a"}],
+ )
+ stack = _wait_stack(cfn, parent_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ nested = cfn.describe_stacks(StackName=_output(stack, "NestedId"))["Stacks"][0]
+ assert nested["Tags"] == [{"Key": "owner", "Value": "team-a"}]
+ tags = sqs.list_queue_tags(QueueUrl=_output(stack, "QueueUrl"))["Tags"]
+ assert tags == {"owner": "team-a", **_system_tags(nested, "Q")}
+ finally:
+ _delete_cfn_test_stack(cfn, parent_name)
+ s3.delete_object(Bucket=templates_bucket, Key="child.json")
+ s3.delete_bucket(Bucket=templates_bucket)
+
+
+def test_cfn_change_set_keeps_tagged_resources_without_update_handler(cfn, sqs):
+ """Executing an UPDATE change set on a tagged stack does not re-create the
+ tagged resources: the snapshot the execution compares against carries the
+ stack's tags, so a type without an update handler (an HTTP API) keeps its
+ physical id while the queue next to it changes."""
+ name = f"cfn-cs-tags-{_uuid_mod.uuid4().hex[:8]}"
+
+ def template(visibility):
+ return json.dumps({
+ "Resources": {
+ "Q": {
+ "Type": "AWS::SQS::Queue",
+ "Properties": {"VisibilityTimeout": visibility},
+ },
+ "Api": {
+ "Type": "AWS::ApiGatewayV2::Api",
+ "Properties": {"Name": f"{name}-api", "ProtocolType": "HTTP"},
+ },
+ },
+ "Outputs": {
+ "ApiId": {"Value": {"Ref": "Api"}},
+ "QueueUrl": {"Value": {"Ref": "Q"}},
+ },
+ })
+
+ cfn.create_stack(
+ StackName=name, TemplateBody=template(30),
+ Tags=[{"Key": "owner", "Value": "team-a"}],
+ )
+ try:
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ api_id = _output(stack, "ApiId")
+ queue_url = _output(stack, "QueueUrl")
+
+ cfn.create_change_set(
+ StackName=name, ChangeSetName="visibility", TemplateBody=template(60),
+ )
+ described = cfn.describe_change_set(ChangeSetName="visibility", StackName=name)
+ assert [c["ResourceChange"]["LogicalResourceId"] for c in described["Changes"]] == ["Q"]
+ cfn.execute_change_set(ChangeSetName="visibility", StackName=name)
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "ApiId") == api_id
+ attributes = sqs.get_queue_attributes(
+ QueueUrl=queue_url, AttributeNames=["VisibilityTimeout"]
+ )["Attributes"]
+ assert attributes["VisibilityTimeout"] == "60"
+ assert sqs.list_queue_tags(QueueUrl=queue_url)["Tags"] == {
+ "owner": "team-a", **_system_tags(stack, "Q")}
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
+def test_cfn_stack_tag_change_keeps_a_resource_without_update_handler(cfn):
+ """A stack-tag change is an update; a tagged type without an update
+ handler (a certificate) keeps its ARN 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"},
+ },
+ },
+ "Outputs": {"CertArn": {"Value": {"Ref": "Cert"}}},
+ })
+ cfn.create_stack(
+ StackName=name, TemplateBody=template, Tags=[{"Key": "owner", "Value": "team-a"}],
+ )
+ try:
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ arn = _output(stack, "CertArn")
+ 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 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")}
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
+def test_cfn_secret_and_parameter_manual_tags_survive_a_stack_update(cfn, sm, ssm):
+ """Tags added through TagResource / AddTagsToResource on a secret and a
+ parameter the template never tagged are kept by a stack update, next to
+ the stack tags and the aws:cloudformation tags."""
+ name = f"cfn-manual-tags-{_uuid_mod.uuid4().hex[:8]}"
+
+ def template(description, value):
+ return json.dumps({
+ "Resources": {
+ "Secret": {
+ "Type": "AWS::SecretsManager::Secret",
+ "Properties": {
+ "Name": f"{name}-secret",
+ "Description": description,
+ "SecretString": "s3cret",
+ },
+ },
+ "Param": {
+ "Type": "AWS::SSM::Parameter",
+ "Properties": {"Name": f"/{name}/p", "Type": "String", "Value": value},
+ },
+ },
+ "Outputs": {"SecretArn": {"Value": {"Ref": "Secret"}}},
+ })
+
+ cfn.create_stack(
+ StackName=name, TemplateBody=template("one", "v1"),
+ Tags=[{"Key": "owner", "Value": "team-a"}],
+ )
+ try:
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ secret_arn = _output(stack, "SecretArn")
+ sm.tag_resource(SecretId=secret_arn, Tags=[{"Key": "manual", "Value": "yes"}])
+ ssm.add_tags_to_resource(
+ ResourceType="Parameter", ResourceId=f"/{name}/p",
+ Tags=[{"Key": "manual", "Value": "yes"}],
+ )
+
+ cfn.update_stack(StackName=name, TemplateBody=template("two", "v2"))
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ secret = sm.describe_secret(SecretId=secret_arn)
+ assert secret["Description"] == "two"
+ assert {t["Key"]: t["Value"] for t in secret["Tags"]} == {
+ "manual": "yes", "owner": "team-a", **_system_tags(stack, "Secret")}
+ assert ssm.get_parameter(Name=f"/{name}/p")["Parameter"]["Value"] == "v2"
+ param_tags = ssm.list_tags_for_resource(
+ ResourceType="Parameter", ResourceId=f"/{name}/p")["TagList"]
+ assert {t["Key"]: t["Value"] for t in param_tags} == {
+ "manual": "yes", "owner": "team-a", **_system_tags(stack, "Param")}
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
+def test_cfn_stack_tag_change_reaches_an_event_bus_and_an_api_key(cfn, eb, apigw_v1):
+ """Types whose update handler used to ignore the tag property (an event
+ bus, an API key) receive a stack-tag change on update."""
+ name = f"cfn-tag-upd-{_uuid_mod.uuid4().hex[:8]}"
+ template = json.dumps({
+ "Resources": {
+ "Bus": {"Type": "AWS::Events::EventBus", "Properties": {"Name": f"{name}-bus"}},
+ "Key": {
+ "Type": "AWS::ApiGateway::ApiKey",
+ "Properties": {"Name": f"{name}-key", "Enabled": True},
+ },
+ },
+ "Outputs": {
+ "BusArn": {"Value": {"Fn::GetAtt": ["Bus", "Arn"]}},
+ "KeyId": {"Value": {"Ref": "Key"}},
+ },
+ })
+
+ def bus_tags(arn):
+ return {t["Key"]: t["Value"] for t in eb.list_tags_for_resource(ResourceARN=arn)["Tags"]}
+
+ cfn.create_stack(
+ StackName=name, TemplateBody=template, Tags=[{"Key": "owner", "Value": "team-a"}],
+ )
+ try:
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ bus_arn = _output(stack, "BusArn")
+ key_id = _output(stack, "KeyId")
+ assert bus_tags(bus_arn) == {"owner": "team-a", **_system_tags(stack, "Bus")}
+ assert apigw_v1.get_api_key(apiKey=key_id)["tags"] == {
+ "owner": "team-a", **_system_tags(stack, "Key")}
+
+ cfn.update_stack(
+ StackName=name, UsePreviousTemplate=True,
+ Tags=[{"Key": "owner", "Value": "team-b"}, {"Key": "cost", "Value": "42"}],
+ )
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "KeyId") == key_id
+ expected = {"owner": "team-b", "cost": "42"}
+ assert bus_tags(bus_arn) == {**expected, **_system_tags(stack, "Bus")}
+ assert apigw_v1.get_api_key(apiKey=key_id)["tags"] == {
+ **expected, **_system_tags(stack, "Key")}
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
+def test_cfn_stack_tags_reach_the_map_shaped_tag_properties(cfn, cognito_idp, cognito_identity):
+ """The map-shaped properties receive the stack tags too: UserPoolTags,
+ IdentityPoolTags, BackupVaultTags and BackupPlanTags, each read back
+ through the service's own tag API."""
+ name = f"cfn-map-tags-{_uuid_mod.uuid4().hex[:8]}"
+ template = json.dumps({
+ "Resources": {
+ "Pool": {
+ "Type": "AWS::Cognito::UserPool",
+ "Properties": {"UserPoolName": f"{name}-pool", "UserPoolTags": {"tier": "gold"}},
+ },
+ "IdPool": {
+ "Type": "AWS::Cognito::IdentityPool",
+ "Properties": {
+ "IdentityPoolName": f"{name}-idpool",
+ "AllowUnauthenticatedIdentities": True,
+ "IdentityPoolTags": {"tier": "silver"},
+ },
+ },
+ "Vault": {
+ "Type": "AWS::Backup::BackupVault",
+ "Properties": {"BackupVaultName": f"{name}-vault", "BackupVaultTags": {"tier": "bronze"}},
+ },
+ "Plan": {
+ "Type": "AWS::Backup::BackupPlan",
+ "Properties": {
+ "BackupPlan": {
+ "BackupPlanName": f"{name}-plan",
+ "BackupPlanRule": [{
+ "RuleName": "daily",
+ "TargetBackupVault": {"Ref": "Vault"},
+ "ScheduleExpression": "cron(0 5 ? * * *)",
+ }],
+ },
+ "BackupPlanTags": {"tier": "iron"},
+ },
+ },
+ },
+ "Outputs": {
+ "PoolArn": {"Value": {"Fn::GetAtt": ["Pool", "Arn"]}},
+ "IdPoolId": {"Value": {"Ref": "IdPool"}},
+ "VaultArn": {"Value": {"Fn::GetAtt": ["Vault", "BackupVaultArn"]}},
+ "PlanArn": {"Value": {"Fn::GetAtt": ["Plan", "BackupPlanArn"]}},
+ },
+ })
+ backup = _regional_cfn_test_client("backup", cfn.meta.region_name)
+ cfn.create_stack(
+ StackName=name, TemplateBody=template, Tags=[{"Key": "owner", "Value": "team-a"}],
+ )
+ try:
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ pool_tags = cognito_idp.list_tags_for_resource(ResourceArn=_output(stack, "PoolArn"))["Tags"]
+ assert pool_tags == {"tier": "gold", "owner": "team-a", **_system_tags(stack, "Pool")}
+ idpool_arn = (
+ f"arn:aws:cognito-identity:{cfn.meta.region_name}:000000000000:"
+ f"identitypool/{_output(stack, 'IdPoolId')}"
+ )
+ idpool_tags = cognito_identity.list_tags_for_resource(ResourceArn=idpool_arn)["Tags"]
+ assert idpool_tags == {"tier": "silver", "owner": "team-a", **_system_tags(stack, "IdPool")}
+ vault_tags = backup.list_tags(ResourceArn=_output(stack, "VaultArn"))["Tags"]
+ assert vault_tags == {"tier": "bronze", "owner": "team-a", **_system_tags(stack, "Vault")}
+ plan_tags = backup.list_tags(ResourceArn=_output(stack, "PlanArn"))["Tags"]
+ assert plan_tags == {"tier": "iron", "owner": "team-a", **_system_tags(stack, "Plan")}
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
+def test_cfn_stack_tags_map_valued_tags_and_eks_nodegroup(cfn, sqs, eks):
+ """An EKS node group's Tags is a map on AWS and is stored as one; a
+ map-valued Tags on a list-shaped type (a queue) is accepted as well."""
+ name = f"cfn-eks-tags-{_uuid_mod.uuid4().hex[:8]}"
+ template = json.dumps({
+ "Resources": {
+ "Cluster": {
+ "Type": "AWS::EKS::Cluster",
+ "Properties": {
+ "Name": f"{name}-cluster",
+ "RoleArn": "arn:aws:iam::000000000000:role/eks-role",
+ "ResourcesVpcConfig": {"SubnetIds": ["subnet-1", "subnet-2"]},
+ },
+ },
+ "Nodes": {
+ "Type": "AWS::EKS::Nodegroup",
+ "Properties": {
+ "ClusterName": {"Ref": "Cluster"},
+ "NodegroupName": f"{name}-nodes",
+ "NodeRole": "arn:aws:iam::000000000000:role/eks-node-role",
+ "Subnets": ["subnet-1"],
+ "Tags": {"tier": "gold"},
+ },
+ },
+ "Q": {"Type": "AWS::SQS::Queue", "Properties": {"Tags": {"env": "map"}}},
+ },
+ "Outputs": {
+ "NodesArn": {"Value": {"Fn::GetAtt": ["Nodes", "Arn"]}},
+ "QueueUrl": {"Value": {"Ref": "Q"}},
+ },
+ })
+ cfn.create_stack(
+ StackName=name, TemplateBody=template, Tags=[{"Key": "owner", "Value": "team-a"}],
+ )
+ try:
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ node_tags = eks.list_tags_for_resource(resourceArn=_output(stack, "NodesArn"))["tags"]
+ assert node_tags == {"tier": "gold", "owner": "team-a", **_system_tags(stack, "Nodes")}
+ assert sqs.list_queue_tags(QueueUrl=_output(stack, "QueueUrl"))["Tags"] == {
+ "env": "map", "owner": "team-a", **_system_tags(stack, "Q")}
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
+def test_cfn_change_set_tags_replace_the_previous_stack_tags(cfn, sqs):
+ """An UPDATE change set that carries new stack tags: after execute the
+ queue carries the new tag and no longer the old one. The execution
+ compares against a snapshot that holds the previous tags; without them
+ the old tag would survive on the queue."""
+ name = f"cfn-cs-retag-{_uuid_mod.uuid4().hex[:8]}"
+
+ def template(visibility):
+ return json.dumps({
+ "Resources": {
+ "Q": {"Type": "AWS::SQS::Queue", "Properties": {"VisibilityTimeout": visibility}},
+ },
+ "Outputs": {"QueueUrl": {"Value": {"Ref": "Q"}}},
+ })
+
+ cfn.create_stack(
+ StackName=name, TemplateBody=template(30), Tags=[{"Key": "phase", "Value": "a"}],
+ )
+ try:
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ queue_url = _output(stack, "QueueUrl")
+ assert sqs.list_queue_tags(QueueUrl=queue_url)["Tags"]["phase"] == "a"
+
+ cfn.create_change_set(
+ StackName=name, ChangeSetName="retag", TemplateBody=template(60),
+ Tags=[{"Key": "owner", "Value": "b"}],
+ )
+ cfn.execute_change_set(ChangeSetName="retag", StackName=name)
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert stack["Tags"] == [{"Key": "owner", "Value": "b"}]
+ assert sqs.list_queue_tags(QueueUrl=queue_url)["Tags"] == {
+ "owner": "b", **_system_tags(stack, "Q")}
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
+def test_cfn_stack_update_keeps_foreign_tags_on_table_and_project(cfn, ddb, codebuild, apigw_v1):
+ """Tags set outside the stack on a table (TagResource) and on a CodeBuild
+ project (UpdateProject) survive a stack-tag change, which also reaches a
+ usage plan through its update handler."""
+ name = f"cfn-foreign-tags-{_uuid_mod.uuid4().hex[:8]}"
+ template = json.dumps({
+ "Resources": {
+ "Table": {
+ "Type": "AWS::DynamoDB::Table",
+ "Properties": {
+ "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
+ "BillingMode": "PAY_PER_REQUEST",
+ },
+ },
+ "Project": {
+ "Type": "AWS::CodeBuild::Project",
+ "Properties": {
+ "Name": f"{name}-project",
+ "Source": {"Type": "NO_SOURCE"},
+ "Artifacts": {"Type": "NO_ARTIFACTS"},
+ "Environment": {
+ "Type": "LINUX_CONTAINER",
+ "Image": "aws/codebuild/standard:7.0",
+ "ComputeType": "BUILD_GENERAL1_SMALL",
+ },
+ "ServiceRole": "arn:aws:iam::000000000000:role/codebuild-role",
+ },
+ },
+ "Plan": {
+ "Type": "AWS::ApiGateway::UsagePlan",
+ "Properties": {"UsagePlanName": f"{name}-plan", "Description": "plan"},
+ },
+ },
+ "Outputs": {
+ "TableArn": {"Value": {"Fn::GetAtt": ["Table", "Arn"]}},
+ "PlanId": {"Value": {"Ref": "Plan"}},
+ },
+ })
+ cfn.create_stack(
+ StackName=name, TemplateBody=template, Tags=[{"Key": "owner", "Value": "team-a"}],
+ )
+ try:
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ table_arn = _output(stack, "TableArn")
+ plan_id = _output(stack, "PlanId")
+ ddb.tag_resource(ResourceArn=table_arn, Tags=[{"Key": "manual", "Value": "yes"}])
+ project = codebuild.batch_get_projects(names=[f"{name}-project"])["projects"][0]
+ codebuild.update_project(
+ name=f"{name}-project",
+ tags=project["tags"] + [{"key": "manual", "value": "yes"}],
+ )
+ assert apigw_v1.get_usage_plan(usagePlanId=plan_id)["tags"] == {
+ "owner": "team-a", **_system_tags(stack, "Plan")}
+
+ 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")
+ table_tags = {t["Key"]: t["Value"] for t in ddb.list_tags_of_resource(ResourceArn=table_arn)["Tags"]}
+ assert table_tags == {"manual": "yes", "owner": "team-b", **_system_tags(stack, "Table")}
+ project = codebuild.batch_get_projects(names=[f"{name}-project"])["projects"][0]
+ assert {t["key"]: t["value"] for t in project["tags"]} == {
+ "manual": "yes", "owner": "team-b", **_system_tags(stack, "Project")}
+ assert apigw_v1.get_usage_plan(usagePlanId=plan_id)["tags"] == {
+ "owner": "team-b", **_system_tags(stack, "Plan")}
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
+def test_cfn_stack_tags_update_reaches_a_nested_stack(cfn, s3, sqs):
+ """A stack-tag change on the parent reaches the resources of the nested
+ stack: the child's queue is updated against the tags it had before, and
+ the child's own Tags never carry the parent's aws: keys."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ templates_bucket = f"cfn-tags-upd-templates-{suffix}"
+ child_template = {
+ "Resources": {"Q": {"Type": "AWS::SQS::Queue"}},
+ "Outputs": {"QueueUrl": {"Value": {"Ref": "Q"}}},
+ }
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")
+ parent_template = json.dumps({
+ "Resources": {
+ "Nested": {
+ "Type": "AWS::CloudFormation::Stack",
+ "Properties": {"TemplateURL": f"{endpoint}/{templates_bucket}/child.json"},
+ },
+ },
+ "Outputs": {
+ "QueueUrl": {"Value": {"Fn::GetAtt": ["Nested", "Outputs.QueueUrl"]}},
+ "NestedId": {"Value": {"Ref": "Nested"}},
+ },
+ })
+ parent_name = f"cfn-tags-upd-parent-{suffix}"
+ s3.create_bucket(Bucket=templates_bucket)
+ try:
+ s3.put_object(Bucket=templates_bucket, Key="child.json",
+ Body=json.dumps(child_template).encode())
+ cfn.create_stack(
+ StackName=parent_name, TemplateBody=parent_template,
+ Tags=[{"Key": "owner", "Value": "team-a"}],
+ )
+ stack = _wait_stack(cfn, parent_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ queue_url = _output(stack, "QueueUrl")
+ nested_id = _output(stack, "NestedId")
+
+ cfn.update_stack(
+ StackName=parent_name, UsePreviousTemplate=True,
+ Tags=[{"Key": "owner", "Value": "team-b"}, {"Key": "cost", "Value": "42"}],
+ )
+ stack = _wait_stack(cfn, parent_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "NestedId") == nested_id
+ nested = cfn.describe_stacks(StackName=nested_id)["Stacks"][0]
+ assert nested["Tags"] == [{"Key": "owner", "Value": "team-b"}, {"Key": "cost", "Value": "42"}]
+ assert sqs.list_queue_tags(QueueUrl=queue_url)["Tags"] == {
+ "owner": "team-b", "cost": "42", **_system_tags(nested, "Q")}
+ finally:
+ _delete_cfn_test_stack(cfn, parent_name)
+ s3.delete_object(Bucket=templates_bucket, Key="child.json")
+ s3.delete_bucket(Bucket=templates_bucket)
+
+
+def test_cfn_stack_tags_are_validated_and_an_empty_list_clears_them(cfn, sqs):
+ """More than 50 tags and an aws: prefixed key are refused before a stack
+ exists; Tags=[] on UpdateStack removes the stack's tags, from the stack
+ and from the queue, as the API documents for an empty value."""
+ name = f"cfn-tag-rules-{_uuid_mod.uuid4().hex[:8]}"
+ template = json.dumps({
+ "Resources": {"Q": {"Type": "AWS::SQS::Queue"}},
+ "Outputs": {"QueueUrl": {"Value": {"Ref": "Q"}}},
+ })
+ with pytest.raises(ClientError, match="maximum number of 50 tags"):
+ cfn.create_stack(
+ StackName=name, TemplateBody=template,
+ Tags=[{"Key": f"k{i}", "Value": "v"} for i in range(51)],
+ )
+ with pytest.raises(ClientError, match="aws:"):
+ cfn.create_stack(
+ StackName=name, TemplateBody=template,
+ Tags=[{"Key": "aws:cloudformation:stack-name", "Value": "spoof"}],
+ )
+ with pytest.raises(ClientError):
+ cfn.describe_stacks(StackName=name)
+
+ cfn.create_stack(
+ StackName=name, TemplateBody=template, Tags=[{"Key": "owner", "Value": "team-a"}],
+ )
+ try:
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ queue_url = _output(stack, "QueueUrl")
+ with pytest.raises(ClientError, match="maximum number of 50 tags"):
+ cfn.update_stack(
+ StackName=name, UsePreviousTemplate=True,
+ Tags=[{"Key": f"k{i}", "Value": "v"} for i in range(51)],
+ )
+ with pytest.raises(ClientError, match="aws:"):
+ cfn.create_change_set(
+ StackName=name, ChangeSetName="spoof", UsePreviousTemplate=True,
+ Tags=[{"Key": "AWS:reserved", "Value": "spoof"}],
+ )
+
+ cfn.update_stack(StackName=name, UsePreviousTemplate=True, Tags=[])
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert stack.get("Tags", []) == []
+ assert sqs.list_queue_tags(QueueUrl=queue_url)["Tags"] == _system_tags(stack, "Q")
+ # The same empty list again is no update.
+ with pytest.raises(ClientError, match="No updates are to be performed"):
+ cfn.update_stack(StackName=name, UsePreviousTemplate=True, Tags=[])
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
def test_cfn_aws_region_pseudo_param_uses_caller_region():
"""CFN's AWS::Region pseudo-param must resolve to the caller's request region,
not MINISTACK_REGION (issue #398 — CDK bootstrap resources inheriting wrong region)."""
@@ -7877,7 +8655,7 @@ def test_cfn_apigateway_domain_name_lifecycle(cfn, apigw_v1):
regional = apigw_v1.get_domain_name(domainName=regional_name)
assert regional["endpointConfiguration"] == {"types": ["REGIONAL"]}
assert regional["regionalCertificateArn"] == regional_certificate_arn
- assert regional["tags"] == {"created-by": "cloudformation"}
+ assert _template_tags(regional["tags"]) == {"created-by": "cloudformation"}
edge = apigw_v1.get_domain_name(domainName=edge_name)
assert edge["endpointConfiguration"] == {"types": ["EDGE"]}
assert edge["certificateArn"] == edge_certificate_arn
@@ -9486,7 +10264,7 @@ def test_cfn_opensearch_domain_create_update_replace_and_idempotent_delete(
assert status["SoftwareUpdateOptions"]["AutoSoftwareUpdateEnabled"] is True
assert sentinel not in json.dumps(status, default=str)
tags = opensearch.list_tags(ARN=expected_arn)["TagList"]
- assert {t["Key"]: t["Value"] for t in tags} == {
+ assert _template_tags({t["Key"]: t["Value"] for t in tags}) == {
"Environment": "test", "Changing": "old"
}
assert domain_name in {
@@ -9517,7 +10295,7 @@ def test_cfn_opensearch_domain_create_update_replace_and_idempotent_delete(
assert status["AdvancedOptions"] == {}
assert status["OffPeakWindowOptions"] == {"Enabled": False}
tags = opensearch.list_tags(ARN=expected_arn)["TagList"]
- assert {t["Key"]: t["Value"] for t in tags} == {
+ assert _template_tags({t["Key"]: t["Value"] for t in tags}) == {
"Changing": "new", "Added": "yes"
}
progress = opensearch.describe_domain_change_progress(DomainName=domain_name)[
@@ -10138,7 +10916,7 @@ def test_cfn_kms_key_tags_rotation_and_enabled(cfn, kms_client):
assert rotation["RotationPeriodInDays"] == 180
tags = kms_client.list_resource_tags(KeyId=arn)["Tags"]
- assert tags == [{"TagKey": "env", "TagValue": "test"}]
+ assert _template_tags(tags) == [{"TagKey": "env", "TagValue": "test"}]
cfn.delete_stack(StackName=stack_name)
_wait_stack(cfn, stack_name)
@@ -13368,14 +14146,20 @@ def test_cfn_cognito_user_pool_property_changes_in_place(cfn, cognito_idp, prop,
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
pool_id = _output(stack, "PoolId")
- assert cognito_idp.describe_user_pool(UserPoolId=pool_id)["UserPool"][prop] == before
+ observed = cognito_idp.describe_user_pool(UserPoolId=pool_id)["UserPool"][prop]
+ if prop == "UserPoolTags":
+ observed = _template_tags(observed)
+ assert observed == before
cognito_idp.admin_create_user(UserPoolId=pool_id, Username="alice")
cfn.update_stack(StackName=stack_name, TemplateBody=template(after))
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
assert _output(stack, "PoolId") == pool_id
- assert cognito_idp.describe_user_pool(UserPoolId=pool_id)["UserPool"][prop] == after
+ observed = cognito_idp.describe_user_pool(UserPoolId=pool_id)["UserPool"][prop]
+ if prop == "UserPoolTags":
+ observed = _template_tags(observed)
+ assert observed == after
users = cognito_idp.list_users(UserPoolId=pool_id)["Users"]
assert [u["Username"] for u in users] == ["alice"]
finally:
@@ -13513,7 +14297,7 @@ def test_cfn_secret_update_publishes_a_new_version(cfn, sm):
assert previous["VersionId"] == first["VersionId"]
described = sm.describe_secret(SecretId=secret_name)
assert described["Description"] == "second"
- assert described["Tags"] == [{"Key": "stage", "Value": "second"}]
+ assert _template_tags(described["Tags"]) == [{"Key": "stage", "Value": "second"}]
assert set(described["VersionIdsToStages"]) == {first["VersionId"], current["VersionId"]}
_delete_cfn_test_stack(cfn, stack_name)
@@ -13912,14 +14696,14 @@ def test_cfn_events_rule_tags_apply_on_create_and_update(cfn, eb):
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
arn = _output(stack, "RuleArn")
- assert tags_of(arn) == {"env": "dev", "team": "a"}
+ assert _template_tags(tags_of(arn)) == {"env": "dev", "team": "a"}
eb.tag_resource(ResourceARN=arn, Tags=[{"Key": "foreign", "Value": "kept"}])
cfn.update_stack(StackName=stack_name, TemplateBody=template({"env": "prod", "owner": "b"}))
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
assert _output(stack, "RuleArn") == arn
- assert tags_of(arn) == {"env": "prod", "owner": "b", "foreign": "kept"}
+ assert _template_tags(tags_of(arn)) == {"env": "prod", "owner": "b", "foreign": "kept"}
finally:
_delete_cfn_test_stack(cfn, stack_name)
with pytest.raises(ClientError):
@@ -14387,13 +15171,13 @@ def test_cfn_state_machine_update_changes_tags_in_place(cfn, sfn):
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
arn = _output(stack, "Arn")
- assert tags_of(arn) == {"env": "dev", "team": "iot"}
+ assert _template_tags(tags_of(arn)) == {"env": "dev", "team": "iot"}
cfn.update_stack(StackName=stack_name, TemplateBody=template({"env": "prod", "owner": "ops"}))
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
assert _output(stack, "Arn") == arn
- assert tags_of(arn) == {"env": "prod", "owner": "ops"}
+ assert _template_tags(tags_of(arn)) == {"env": "prod", "owner": "ops"}
finally:
_delete_cfn_test_stack(cfn, stack_name)
@@ -14593,12 +15377,12 @@ def test_cfn_cloudwatch_alarm_tags_apply_on_create_and_update(cfn, cw):
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
arn = _output(stack, "Arn")
- assert tags_of(arn) == {"env": "dev", "team": "a"}
+ assert _template_tags(tags_of(arn)) == {"env": "dev", "team": "a"}
cfn.update_stack(StackName=stack_name, TemplateBody=template({"env": "prod"}))
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
- assert tags_of(arn) == {"env": "prod"}
+ assert _template_tags(tags_of(arn)) == {"env": "prod"}
_delete_cfn_test_stack(cfn, stack_name)
with pytest.raises(ClientError) as exc: