Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(cloudformation): apply the AWS::LanguageExtensions transform (#1739)
iot-rocket160372b0ca8f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bc99e04a..f56615b7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### 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.### Fixed- **IAM — a group policy document is validated, and an `AWS::IAM::Policy` naming a missing entity fails** — `PutGroupPolicy` stored a malformed document; all three inline handlers now answer `NoSuchEntity` before `MalformedPolicyDocument`, the order measured on AWS. An `AWS::IAM::Policy` skipped a Role, User or Group that was not there and reported `CREATE_COMPLETE`; the resource now fails with `The role with name <name> cannot be found.`, and an update checks names and document before it takes the old policy off. Contributed by @iot-rocket.- **IAM — a Secrets Manager request is authorized against the stored secret ARN** — the resource was built from the name in the request, `secret:<name>`, while AWS evaluates the stored ARN with the six random characters minted at `CreateSecret`. The grant shape the CDK writes for a secret looked up by name, `secret:<name>-??????` or `secret:<name>-*`, matched nothing under `AUTH=true`. The resource now comes from the store through the handlers' own lookup; a secret that does not exist keeps the name-derived ARN. Contributed by @iot-rocket.diff --git a/README.md b/README.mdindex 84906261..701a9480 100644--- a/README.md+++ b/README.md@@ -463,7 +463,7 @@ subnet = ec2.create_subnet(| **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 || **Rules** | The `Rules` section runs after the parameters resolve and before any resource is touched (CreateStack, UpdateStack, CreateChangeSet): `RuleCondition`, `Assertions` with `AssertDescription`, Fn::And/Or/Not/Equals/If/Contains/EachMemberEquals/EachMemberIn and Ref; Fn::RefAll, Fn::ValueOf and Fn::ValueOfAll read the EC2 store for VPC, subnet and security-group ids |-| **Transforms** | `AWS::Serverless-2016-10-31` (SAM, in the `full` image) and the embedded `AWS::Include` transform (`Fn::Transform` with an `s3://` `Location`, JSON or YAML snippets) |+| **Transforms** | `AWS::Serverless-2016-10-31` (SAM, in the `full` image), `AWS::LanguageExtensions` (`Fn::ForEach` over a literal list, a `CommaDelimitedList` parameter, `Fn::FindInMap` or `Fn::Split`, nested and inside `Properties`; `${Id}` / `&{Id}` in the fragment keys, `${Id}` in `Fn::Sub` and a `Ref` to the identifier; `Fn::Length`, `Fn::ToJsonString`) and the embedded `AWS::Include` transform (`Fn::Transform` with an `s3://` `Location`, JSON or YAML snippets) || **Rollback** | Configurable via `DisableRollback` — 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 || **Quotas** | The template and stack quotas of the CloudFormation quotas page are enforced before a stack exists: 51,200 bytes of `TemplateBody`, 1,000,000 bytes behind `TemplateURL`, 500 resources, 200 parameters / outputs / mappings, 200 attributes per mapping, 255-character names, a 1,024-byte description, 4,096-byte parameter values, and a stack name of up to 128 alphanumeric characters and hyphens starting with a letter |diff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.pyindex bcb826f1..0c37af7f 100644--- a/ministack/services/cloudformation/changesets.py+++ b/ministack/services/cloudformation/changesets.py@@ -10,7 +10,7 @@ import loggingfrom ministack.core.responses import get_account_id, get_region, new_uuid, now_isofrom .engine import (- _apply_sam_transform_if_applicable,+ _apply_transforms,_evaluate_conditions,_parse_template,_resolve_parameters,@@ -198,7 +198,8 @@ def _create_change_set(params):try:template = sent = _parse_template(template_body)- template = _apply_sam_transform_if_applicable(template)+ template = _apply_transforms(template, provided_params,+ stack.get("_resolved_params", {}))except Exception as e:return _rejected(f"Template format error: {e}")diff --git a/ministack/services/cloudformation/engine.py b/ministack/services/cloudformation/engine.pyindex 271b1186..1e61e657 100644--- a/ministack/services/cloudformation/engine.py+++ b/ministack/services/cloudformation/engine.py@@ -20,6 +20,8 @@ import yamlfrom ministack.core.responses import get_account_id, get_region+from . import language_extensions+logger = logging.getLogger("cloudformation")# Sentinel for AWS::NoValue@@ -267,7 +269,7 @@ def validate_template_support(template: dict, conditions: dict,"""from .provisioners import _RESOURCE_HANDLERS- if isinstance(template, _IncludeFailed):+ if isinstance(template, _TransformFailed):raise ValueError(template.error)_validate_template_limits(template)unrecognized: set[str] = set()@@ -1018,6 +1020,21 @@ def _unknown_attribute_message(res: dict, logical_id: str, attr: str) -> str:return f"Requested attribute {attr} does not exist in schema for {rtype}"+def find_in_map(args, mappings, resolve):+ """``Fn::FindInMap`` over ``mappings``, every argument read through+ ``resolve``. The optional fourth argument is {"DefaultValue": ...}; without+ it a missing key is a template error, as on AWS (measured: "Template error:+ Unable to get mapping for M::x::y")."""+ map_name, key1, key2 = resolve(args[0]), resolve(args[1]), resolve(args[2])+ top = mappings.get(str(map_name), {})+ if str(key1) in top and str(key2) in top[str(key1)]:+ return top[str(key1)][str(key2)]+ if len(args) > 3 and isinstance(args[3], dict) and "DefaultValue" in args[3]:+ return resolve(args[3]["DefaultValue"])+ raise ValueError(+ f"Template error: Unable to get mapping for {map_name}::{key1}::{key2}")++def _resolve_refs(value, resources, params, conditions, mappings,stack_name, stack_id):"""Recursively resolve CloudFormation intrinsic functions."""@@ -1182,26 +1199,18 @@ def _resolve_refs(value, resources, params, conditions, mappings,conditions, mappings, stack_name, stack_id)return base64.b64encode(str(inner).encode("utf-8")).decode("utf-8")+ # --- Fn::ToJsonString (AWS::LanguageExtensions) ---+ # The transform serialises what the template alone answers and leaves the+ # node here when a member needs the stack (Fn::GetAtt, a pseudo parameter).+ if "Fn::ToJsonString" in value:+ inner = _resolve_refs(value["Fn::ToJsonString"], resources, params,+ conditions, mappings, stack_name, stack_id)+ return json.dumps(inner, separators=(",", ":"))+# --- Fn::FindInMap ---if "Fn::FindInMap" in value:- args = value["Fn::FindInMap"]- map_name = _resolve_refs(args[0], resources, params, conditions,- mappings, stack_name, stack_id)- key1 = _resolve_refs(args[1], resources, params, conditions,- mappings, stack_name, stack_id)- key2 = _resolve_refs(args[2], resources, params, conditions,- mappings, stack_name, stack_id)- top = mappings.get(str(map_name), {})- if str(key1) in top and str(key2) in top[str(key1)]:- return top[str(key1)][str(key2)]- # The optional fourth argument is {"DefaultValue": ...}; without it a- # missing key is a template error, as on AWS (measured: "Template- # error: Unable to get mapping for M::x::y").- if len(args) > 3 and isinstance(args[3], dict) and "DefaultValue" in args[3]:- return _resolve_refs(args[3]["DefaultValue"], resources, params,- conditions, mappings, stack_name, stack_id)- raise ValueError(- f"Template error: Unable to get mapping for {map_name}::{key1}::{key2}")+ return find_in_map(value["Fn::FindInMap"], mappings, lambda node: _resolve_refs(+ node, resources, params, conditions, mappings, stack_name, stack_id))# --- Fn::ImportValue ---if "Fn::ImportValue" in value:@@ -1423,8 +1432,8 @@ class _IncludeError(ValueError):caller answers, unwrapped."""-class _IncludeFailed(dict):- """The template as sent, carrying the message of an include that failed.+class _TransformFailed(dict):+ """The template as sent, carrying the message of a transform that failed.The handlers apply the transforms in one step and wrap everything thatstep raises as ``Template format error: ...``; a real account answers@@ -1432,7 +1441,8 @@ class _IncludeFailed(dict):so the failure travels with the template to ``validate_template_support``,which raises it as is. UpdateStack with ``UsePreviousTemplate`` swaps inthe stored processed template before that point, so a snippet that went- missing since the deploy does not fail the update."""+ missing since the deploy does not fail the update. The+ ``AWS::LanguageExtensions`` transform reports the same way."""def __init__(self, template: dict, error: str):super().__init__(template)@@ -1513,7 +1523,7 @@ def _apply_include_transform(template: dict) -> dict:resource, a ``Properties`` map) takes the snippet's keys, the snippetwinning a duplicate key (unmeasured). The ``Parameters`` section and thetemplate version are not walked. An include that cannot be expanded- returns the template as ``_IncludeFailed``, which the validation step+ returns the template as ``_TransformFailed``, which the validation stepturns into the ``ValidationError``."""found: list = []for section, value in template.items():@@ -1542,7 +1552,7 @@ def _apply_include_transform(template: dict) -> dict:if section not in _INCLUDE_SKIPPED_SECTIONS:expanded[section] = walk(value)except _IncludeError as exc:- return _IncludeFailed(template, str(exc))+ return _TransformFailed(template, str(exc))return expanded@@ -1576,13 +1586,75 @@ def declared_transforms(template: dict) -> list[str]:return names-def _apply_sam_transform_if_applicable(template: dict) -> dict:+def _transform_parameters(template: dict, provided_params, previous_params) -> dict:+ """The parameter values ``AWS::LanguageExtensions`` resolves against ("The+ AWS::LanguageExtensions transform resolves parameters to literal values+ during processing"). The transforms run before the operation resolves its+ parameters; a template the resolution refuses gets the values that are+ there, and the operation raises for the rest right after."""+ provided = list(provided_params or [])+ try:+ resolved = _resolve_parameters(template, provided, previous_params)+ return {name: entry["Value"] for name, entry in resolved.items()}+ except ValueError:+ pass+ sent = {entry["Key"]: entry.get("Value", "") for entry in provided if "Key" in entry}+ values = {}+ for name, defn in (template.get("Parameters") or {}).items():+ if name in sent:+ values[name] = str(sent[name])+ elif isinstance(defn, dict) and "Default" in defn:+ values[name] = str(defn["Default"])+ return values+++def _without_transform(template: dict, name: str) -> dict:+ """The template with one transform dropped from ``Transform``: applied, it+ is no longer declared, and its output validates like any template."""+ declared = template.get("Transform")+ entries = declared if isinstance(declared, list) else [declared]+ kept = [entry for entry in entries+ if not (entry == name+ or (isinstance(entry, dict) and entry.get("Name") == name))]+ processed = dict(template)+ if not kept:+ processed.pop("Transform", None)+ elif isinstance(declared, list):+ processed["Transform"] = kept+ else:+ processed["Transform"] = kept[0]+ return processed+++def refuse_undeclared_language_extensions(template: dict) -> None:+ """Refuse a function of ``AWS::LanguageExtensions`` in a template that does+ not declare it. ValidateTemplate runs this alone: an account refuses the+ undeclared loop there as CreateStack does, and validates a declaring+ template without expanding it (both measured). Raises+ ``LanguageExtensionsError``, a ``ValueError``."""+ if language_extensions.TRANSFORM not in declared_transforms(template):+ language_extensions.refuse_undeclared(template)+++def _apply_transforms(template: dict, provided_params=None,+ previous_params=None) -> dict:"""The transforms a stack operation applies before validation: every- embedded ``AWS::Include`` first, then the SAM transform when the template- declares it."""+ embedded ``AWS::Include``, then ``AWS::LanguageExtensions``, then SAM, each+ when declared. "the AWS::LanguageExtensions transform must come before the+ AWS::Serverless transform in the list"."""template = _apply_include_transform(template)- if isinstance(template, _IncludeFailed):+ if isinstance(template, _TransformFailed):return template+ try:+ language_extensions.refuse_embedded(template)+ refuse_undeclared_language_extensions(template)+ if language_extensions.TRANSFORM in declared_transforms(template):+ parameters = _transform_parameters(template, provided_params, previous_params)+ template = _without_transform(+ language_extensions.apply(template, parameters),+ language_extensions.TRANSFORM)+ except language_extensions.LanguageExtensionsError as exc:+ return _TransformFailed(template, str(exc))if _SAM_TRANSFORM not in declared_transforms(template):return templatediff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.pyindex a4cb2260..15655630 100644--- a/ministack/services/cloudformation/handlers.py+++ b/ministack/services/cloudformation/handlers.py@@ -20,13 +20,14 @@ from .changesets import ()from .engine import (_NO_VALUE,- _apply_sam_transform_if_applicable,+ _apply_transforms,_evaluate_conditions,_has_dynamic_references,_parse_template,_resolve_parameters,_resolve_refs,declared_transforms,+ refuse_undeclared_language_extensions,validate_template_support,)from .helpers import (@@ -130,6 +131,11 @@ def _required_capabilities(template, strict=False):named_iam_ids = []unnamed_iam_ids = []for logical_id, res in resources.items():+ # A member of Resources that is not a resource definition: the+ # Fn::ForEach key of an unexpanded AWS::LanguageExtensions template,+ # which ValidateTemplate and GetTemplateSummary read as it was sent.+ if not isinstance(res, dict):+ continuertype = res.get("Type", "")if strict:if rtype not in _CAPABILITY_IAM_TYPES:@@ -262,12 +268,12 @@ def _create_stack(params):return _error("AlreadyExistsException",f"Stack [{stack_name}] already exists")+ provided_params = _extract_members(params, "Parameters")try:template = sent = _parse_template(template_body)- template = _apply_sam_transform_if_applicable(template)+ template = _apply_transforms(template, provided_params)except Exception as e:return _error("ValidationError", f"Template format error: {e}")- provided_params = _extract_members(params, "Parameters")tags = _extract_members(params, "Tags")disable_rollback = _p(params, "DisableRollback", "false").lower() == "true"retain_except_on_create = _p(params, "RetainExceptOnCreate", "false").lower() == "true"@@ -897,12 +903,13 @@ def _update_stack(params):else:return _error("ValidationError", "TemplateBody or TemplateURL is required")+ provided_params = _extract_members(params, "Parameters")try:template = sent = _parse_template(template_body)- template = _apply_sam_transform_if_applicable(template)+ template = _apply_transforms(template, provided_params,+ stack.get("_resolved_params", {}))except Exception as e:return _error("ValidationError", f"Template format error: {e}")- provided_params = _extract_members(params, "Parameters")tags = _extract_members(params, "Tags")disable_rollback = _p(params, "DisableRollback", "false").lower() == "true"retain_except_on_create = _p(params, "RetainExceptOnCreate", "false").lower() == "true"@@ -931,7 +938,8 @@ def _update_stack(params):# The stored template is the processed one: an AWS::Include snippet# edited or removed in S3 since the deploy is not picked up (the# transform reference: "your stack doesn't automatically pick up- # those changes").+ # those changes"), and an Fn::ForEach is not expanded again for a new+ # parameter value (measured).template = copy.deepcopy(stack["_template"])try:validate_template_support(@@ -1020,6 +1028,12 @@ def _validate_template(params):if "Resources" not in template:return _error("ValidationError","Template format error: At least one Resources member must be defined.")+ # An Fn::ForEach in a template that declares no transform is refused as+ # CreateStack refuses it; a declaring template is not expanded (measured).+ try:+ refuse_undeclared_language_extensions(template)+ except ValueError as exc:+ return _error("ValidationError", str(exc))try:conditions = _evaluate_conditions(template, _resolve_parameters(template, []))@@ -1111,11 +1125,16 @@ def _get_template_summary(params):resources = template.get("Resources", {})param_defs = template.get("Parameters", {})+ # A template declaring AWS::LanguageExtensions is not expanded here, and an+ # account answers no ResourceTypes and no Capabilities for one (measured).+ unexpanded = "AWS::LanguageExtensions" in declared_transforms(template)+# Resource types- resource_types = sorted(set(+ resource_types = [] if unexpanded else sorted(set(r.get("Type", "") for r in resources.values()))types_xml = "".join(f"<member>{_esc(t)}</member>" for t in resource_types)+ types_block = "" if unexpanded else f"<ResourceTypes>{types_xml}</ResourceTypes>"# Parametersparams_xml = ""@@ -1134,14 +1153,19 @@ def _get_template_summary(params):"</member>")- caps_block = _capabilities_xml(template)+ caps_block = "" if unexpanded else _capabilities_xml(template)+ transforms_xml = "".join(+ f"<member>{_esc(t)}</member>" for t in declared_transforms(template))+ declared_block = (f"<DeclaredTransforms>{transforms_xml}</DeclaredTransforms>"+ if transforms_xml else "")return _xml(200, "GetTemplateSummaryResponse",f"<GetTemplateSummaryResult>"f"<Description>{_esc(description)}</Description>"- f"<ResourceTypes>{types_xml}</ResourceTypes>"+ f"{types_block}"f"<Parameters>{params_xml}</Parameters>"f"{caps_block}"+ f"{declared_block}"f"</GetTemplateSummaryResult>")diff --git a/ministack/services/cloudformation/language_extensions.py b/ministack/services/cloudformation/language_extensions.pynew file mode 100644index 00000000..d50f738d--- /dev/null+++ b/ministack/services/cloudformation/language_extensions.py@@ -0,0 +1,567 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).+"""The ``AWS::LanguageExtensions`` transform.++Applied to the template before the stack operation sees it: ``Fn::ForEach``+expands into the members it repeats, ``Fn::Length`` and ``Fn::ToJsonString``+become the number and the string they answer. The result is a plain template.++Where the identifier of a loop is substituted, as measured on an account: in+the keys of the fragment (``Param${Item}`` is ``Paramalpha``, ``&{Item}``+drops the non-alphanumeric characters), in the string of an ``Fn::Sub``+(``${Item}`` only; ``&{Item}`` stays literal) and through a ``Ref`` to the+identifier. A plain string value and a key nested below the fragment's own+keys keep their placeholders.++An account creates the stack record and rolls it back with the transform's+message; this refuses the call and leaves no stack, the shape of every other+pre-flight refusal in this engine. The sentences are the account's where they+were measured.++References: transform-aws-languageextensions, intrinsic-function-reference-+foreach, -length, -ToJsonString, -findinmap-enhancements.+"""++import json+import re++TRANSFORM = "AWS::LanguageExtensions"++# The macro-failure prefix, as AWS::Include answers it (measured).+_ERROR = f"Transform {TRANSFORM} failed with: "++_FOREACH = "Fn::ForEach::"+_LENGTH = "Fn::Length"+_TO_JSON = "Fn::ToJsonString"++# Sentences an account answers after the prefix (measured).+_LAYOUT_ERROR = "Fn::ForEach layout is incorrect"+_NO_COLLECTION = "Could not find a collection or could not be resolved for Fn::ForEach"+_LENGTH_UNRESOLVED = "The Fn::Length value could not be resolved for properties"+# Answered without the prefix (measured for {"Fn::Sub": "${Param${Item}}"}).+_SUB_VARIABLE_ERROR = ("Template error: variable names in Fn::Sub syntax must contain "+ "only alphanumeric characters, underscores, periods, and colons")++_ALPHANUMERIC = re.compile(r"[A-Za-z0-9]+")+_SUB_VARIABLE = re.compile(r"\$\{([^}]*)\}")++# "only supported in the Resources, Conditions, and Outputs sections".+_SECTIONS = ("Conditions", "Resources", "Outputs")++# ${Identifier} and &{Identifier}; ${!Literal} is not a placeholder.+_PLACEHOLDER = re.compile(r"([$&])\{([^!}][^}]*)\}")++# Functions only the provisioned stack answers.+_DEFERRED = ("Fn::GetAtt", "Fn::ImportValue", "Fn::GetAZs", "Fn::Cidr",+ "Fn::GetStackOutput")++_LIST_PARAMETER_TYPES = ("AWS::SSM::Parameter::Value<List<String>>",+ "AWS::SSM::Parameter::Value<CommaDelimitedList>")+++class LanguageExtensionsError(ValueError):+ """A template the transform refuses; the message is answered as is."""+++class _Unresolved(Exception):+ """A value the transform cannot compute from the template alone."""+++_REMOVE = object() # a Ref to AWS::NoValue: the member is dropped+++def _fail(message):+ raise LanguageExtensionsError(_ERROR + message)+++class _Context:+ """The mappings, the parameter values as literals and the list parameters+ the transform resolves against."""++ def __init__(self, template, parameters):+ self.mappings = template.get("Mappings") or {}+ self.parameters = parameters+ self.declared = template.get("Parameters") or {}+ self.section = None+ self.lists = {+ name for name, defn in self.declared.items()+ if isinstance(defn, dict)+ and (str(defn.get("Type", "")).startswith(("CommaDelimitedList", "List<"))+ or defn.get("Type") in _LIST_PARAMETER_TYPES)+ }+++# ---------------------------------------------------------------------------+# Entry points+# ---------------------------------------------------------------------------++def apply(template, parameters):+ """The template with the transform applied, ``parameters`` being the+ ``{name: value}`` map of the operation. Raises ``LanguageExtensionsError``."""+ _refuse_outside_sections(template)+ _refuse_duplicate_loops(template)+ context = _Context(template, parameters)+ processed = dict(template)+ for section in _SECTIONS:+ if section in template:+ context.section = section+ processed[section] = _expand(template[section], {}, context, ids=True)+ _resolve_member_conditions(processed, context)+ return processed+++def _resolve_member_conditions(processed, context):+ """The ``Condition`` member of a resource or an output, which takes a+ condition name only. An intrinsic there resolves to the name (measured for+ ``{"Fn::Sub": "Is${Item}"}``); a name no condition carries is refused with+ the account's sentence (measured for a plain ``"Is${Item}"``), since the+ engine would read an unknown condition as true."""+ conditions = processed.get("Conditions") or {}+ for section in ("Resources", "Outputs"):+ for definition in (processed.get(section) or {}).values():+ if not isinstance(definition, dict) or "Condition" not in definition:+ continue+ name = definition["Condition"]+ if not isinstance(name, str):+ try:+ resolved = _value(name, {}, context)+ except _Unresolved:+ continue+ if not isinstance(resolved, str):+ continue+ definition["Condition"] = name = resolved+ if name not in conditions:+ _fail(f"Key {name} is missing in the map.")+++def refuse_undeclared(template):+ """Refuse a function of the transform in a template that does not declare+ it. An ``Fn::ForEach`` in ``Resources`` answers the account's sentence+ (measured from CreateStack and ValidateTemplate); the rest keep this+ emulator's wording."""+ for section in _SECTIONS:+ used, pointer = _first_function(template.get(section), f"/{section}")+ if not used:+ continue+ if used == "Fn::ForEach" and section == "Resources":+ raise LanguageExtensionsError(+ f"Template format error: [{pointer}] resource definition is malformed")+ _fail(f"{used} requires the {TRANSFORM} transform, which the template "+ "does not declare.")+++def refuse_embedded(template):+ """"You can't use AWS::LanguageExtensions as a transform embedded in any+ other template section"."""+ stack = [value for section, value in template.items() if section != "Transform"]+ while stack:+ node = stack.pop()+ if isinstance(node, dict):+ spec = node.get("Fn::Transform")+ if spec == TRANSFORM or (isinstance(spec, dict) and spec.get("Name") == TRANSFORM):+ _fail("the transform is declared at the top level of a template only.")+ stack.extend(node.values())+ elif isinstance(node, list):+ stack.extend(node)+++def _first_function(node, path=""):+ """The first function of the transform in ``node`` and its JSON pointer,+ or ``(None, path)``."""+ if isinstance(node, dict):+ for key, value in node.items():+ if key.startswith(_FOREACH):+ return "Fn::ForEach", f"{path}/{key}"+ if key in (_LENGTH, _TO_JSON):+ return key, f"{path}/{key}"+ found = _first_function(value, f"{path}/{key}")+ if found[0]:+ return found+ elif isinstance(node, list):+ for index, value in enumerate(node):+ found = _first_function(value, f"{path}/{index}")+ if found[0]:+ return found+ return None, path+++def _refuse_outside_sections(template):+ for section, value in template.items():+ if section in _SECTIONS or section == "Transform":+ continue+ used, _pointer = _first_function(value, f"/{section}")+ if used:+ _fail(f"{used} is not supported in the {section} section. The functions of "+ f"{TRANSFORM} are supported in the Resources, Conditions and Outputs "+ "sections.")+++def _refuse_duplicate_loops(template):+ """A loop name "must be unique within the template and can't conflict with+ any logical ID values in the Resources section". It is read off the+ template as written, so a nested loop is one declaration however often the+ outer loop repeats it."""+ resources = template.get("Resources") or {}+ seen = set()++ def walk(node):+ if isinstance(node, list):+ for item in node:+ walk(item)+ elif isinstance(node, dict):+ for key, value in node.items():+ name = key[len(_FOREACH):] if key.startswith(_FOREACH) else ""+ if name:+ if name in seen:+ _fail(f"The loop name {name} is used more than once. A loop name "+ "must be unique within the template.")+ if name in resources:+ _fail(f"The loop name {name} is the logical id of a resource. A "+ "loop name cannot conflict with a logical id in the "+ "Resources section.")+ seen.add(name)+ walk(value)++ for section in _SECTIONS:+ walk(template.get(section))+++# ---------------------------------------------------------------------------+# The structural pass+# ---------------------------------------------------------------------------++def _expand(node, bindings, context, ids=False):+ """``node`` with its loops expanded, the identifiers substituted where they+ are and the transform's functions resolved. ``ids`` marks a mapping whose+ keys are logical ids or output keys (a section, or the fragment of a loop+ directly in one)."""+ if isinstance(node, str):+ return node+ if isinstance(node, list):+ expanded = [_expand(item, bindings, context) for item in node]+ return [item for item in expanded if item is not _REMOVE]+ if not isinstance(node, dict):+ return node++ if len(node) == 1:+ key, argument = next(iter(node.items()))+ if key in (_LENGTH, _TO_JSON):+ try:+ return _value(node, bindings, context)+ except _Unresolved:+ if key == _LENGTH:+ _fail(_LENGTH_UNRESOLVED)+ # Documented for Fn::GetAtt, Fn::If, Ref to a pseudo parameter+ # (measured for the first and the last): left to the engine.+ return {_TO_JSON: _partial(argument, bindings, context)}+ if key == "Fn::FindInMap":+ return _find_in_map_node(argument, bindings, context)+ if key == "Fn::Sub":+ return {"Fn::Sub": _expand_sub(argument, bindings, context)}+ if key == "Ref":+ if isinstance(argument, str) and argument in bindings:+ return bindings[argument]+ return _reference(_expand(argument, bindings, context))+ if key == "Fn::GetAtt":+ return {"Fn::GetAtt": _get_att(_expand(argument, bindings, context))}++ expanded = {}+ for key, value in node.items():+ if key.startswith(_FOREACH):+ for produced_key, produced_value in _for_each(key, value, bindings, context, ids):+ if produced_key in expanded:+ _fail(f"{key} produces {produced_key}, which the template already "+ "declares.")+ if produced_value is not _REMOVE:+ expanded[produced_key] = produced_value+ continue+ resolved = _expand(value, bindings, context)+ if resolved is not _REMOVE:+ expanded[key] = resolved+ return expanded+++def _substitute(text, bindings, forms="$&"):+ """The placeholders of ``text`` in ``forms`` that a loop in scope binds,+ replaced by the item; ``&`` drops its non-alphanumeric characters."""+ if not bindings:+ return text++ def replace(match):+ form, name = match.group(1), match.group(2)+ if form not in forms or name not in bindings:+ return match.group(0)+ item = bindings[name]+ return re.sub(r"[^0-9A-Za-z]", "", item) if form == "&" else item++ return _PLACEHOLDER.sub(replace, text)+++def _sub_text(text, bindings):+ """The string of an ``Fn::Sub`` with ``${Id}`` filled in (``&{Id}`` stays,+ measured), refused for a variable nested in a variable name (measured);+ every other name is the engine's."""+ substituted = _substitute(text, bindings, "$")+ if any("${" in match.group(1) for match in _SUB_VARIABLE.finditer(substituted)):+ raise LanguageExtensionsError(_SUB_VARIABLE_ERROR)+ return substituted+++def _reference(name):+ if isinstance(name, str):+ return {"Ref": name}+ literal = _literal_sub(name)+ if literal is None:+ _fail("Ref takes the name of a parameter or a resource here. An intrinsic "+ "function inside Ref is supported by the transform, but not by this "+ "implementation, unless a loop resolves it to a name.")+ return {"Ref": literal}+++def _get_att(arguments):+ if isinstance(arguments, str):+ return arguments+ if not isinstance(arguments, list):+ _fail("Fn::GetAtt takes the logical id of a resource and the name of an "+ "attribute.")+ resolved = []+ for argument in arguments:+ literal = argument if isinstance(argument, str) else _literal_sub(argument)+ if literal is None:+ _fail("Fn::GetAtt takes the logical id of a resource and the name of an "+ "attribute here. An intrinsic function inside Fn::GetAtt is supported "+ "by the transform, but not by this implementation, unless a loop "+ "resolves it to a name.")+ resolved.append(literal)+ return resolved+++def _literal_sub(node):+ """The constant string of an ``Fn::Sub`` a loop filled in, or None: the+ reference names a copy as ``{"Ref": {"Fn::Sub": "Subnet${Id}"}}``."""+ if not isinstance(node, dict) or len(node) != 1:+ return None+ value = node.get("Fn::Sub")+ if isinstance(value, str) and "${" not in value:+ return value+ return None+++# ---------------------------------------------------------------------------+# Fn::ForEach+# ---------------------------------------------------------------------------++def _for_each(key, spec, bindings, context, ids):+ """The members one ``Fn::ForEach`` produces, in collection order."""+ if not key[len(_FOREACH):]:+ _fail(f"{key} has no loop name.")+ if not isinstance(spec, list) or len(spec) != 3:+ _fail(f"{key} takes an identifier, a collection and a fragment.")+ identifier, collection, fragment = spec+ if not isinstance(identifier, str) or not identifier:+ _fail(f"The identifier of {key} must be a string.")+ if not isinstance(fragment, dict) or not fragment:+ _fail(f"The fragment of {key} must be an object.")+ for output_key in fragment:+ if output_key.startswith(_FOREACH):+ continue+ if identifier not in [match.group(2) for match in _PLACEHOLDER.finditer(output_key)]:+ _fail(f"The key {output_key} of {key} does not contain ${{{identifier}}} or "+ f"&{{{identifier}}}. Every key a loop produces has to carry its "+ "identifier, or the iterations would collide.")++ produced = []+ for item in _collection(collection, key, bindings, context):+ scoped = dict(bindings, **{identifier: item})+ for fragment_key, value in fragment.items():+ if fragment_key.startswith(_FOREACH):+ produced.extend(_for_each(fragment_key, value, scoped, context, ids))+ continue+ produced_key = _substitute(fragment_key, scoped)+ if ids and not _ALPHANUMERIC.fullmatch(produced_key):+ # Measured for an output key; the logical id wording is ours.+ noun = "OutputKey" if context.section == "Outputs" else "LogicalId"+ _fail(f"{noun} '{produced_key}' should be alphanumeric")+ produced.append((produced_key, _expand(value, scoped, context)))+ return produced+++def _collection(collection, key, bindings, context):+ """The items of a loop: an array, or an intrinsic that answers one. A+ string answers the layout error, anything else that is not an array the+ missing collection (both measured)."""+ if isinstance(collection, str):+ _fail(_LAYOUT_ERROR)+ try:+ items = _value(collection, bindings, context)+ except _Unresolved:+ _fail(_NO_COLLECTION)+ if not isinstance(items, list):+ _fail(_NO_COLLECTION)+ for item in items:+ if isinstance(item, bool) or not isinstance(item, (str, int, float)):+ _fail(f"The collection of {key} holds a value that is not a string.")+ return [str(item) for item in items]+++# ---------------------------------------------------------------------------+# Transform-time values+# ---------------------------------------------------------------------------++def _is_function(key):+ """A one-member object is a call only when the member names a function,+ so ``{"config": {...}}`` is an object Fn::ToJsonString serialises."""+ return isinstance(key, str) and (key.startswith("Fn::") or key in ("Ref", "Condition"))+++def _value(node, bindings, context):+ """``node`` as a value computed from the template alone; ``_Unresolved``+ for anything that needs the provisioned stack."""+ if isinstance(node, str):+ return node+ if isinstance(node, list):+ values = [_value(item, bindings, context) for item in node]+ return [value for value in values if value is not _REMOVE]+ if not isinstance(node, dict):+ return node+ if len(node) != 1 or not _is_function(next(iter(node))):+ members = ((key, _value(value, bindings, context)) for key, value in node.items())+ return {key: value for key, value in members if value is not _REMOVE}++ function, argument = next(iter(node.items()))+ if function in _DEFERRED or function.startswith(_FOREACH):+ raise _Unresolved(function)+ if function == "Ref":+ return _ref_value(argument, bindings, context)+ if function == "Fn::FindInMap":+ return _find_in_map(argument, bindings, context)+ if function == _LENGTH:+ items = _value(argument, bindings, context)+ if not isinstance(items, list):+ raise _Unresolved(function)+ return len(items)+ if function == _TO_JSON:+ # Compact separators, a list parameter as an array (measured).+ return json.dumps(_value(argument, bindings, context), separators=(",", ":"))+ if function in ("Fn::Split", "Fn::Select", "Fn::Join"):+ if not isinstance(argument, list) or len(argument) != 2:+ raise _Unresolved(function)+ return _two_argument_value(function, argument, bindings, context)+ if function == "Fn::Sub":+ return _sub_value(argument, bindings, context)+ raise _Unresolved(function)+++def _partial(node, bindings, context):+ """As much of ``node`` as the transform resolves, the rest expanded for+ the engine."""+ try:+ return _value(node, bindings, context)+ except _Unresolved:+ pass+ if isinstance(node, list):+ return [_partial(item, bindings, context) for item in node]+ if isinstance(node, dict) and not (len(node) == 1 and _is_function(next(iter(node)))):+ return {key: _partial(value, bindings, context) for key, value in node.items()}+ return _expand(node, bindings, context)+++def _expand_sub(argument, bindings, context):+ """The argument of an ``Fn::Sub`` left for the stack, with the loop+ identifiers filled in and the variables of the map form expanded."""+ if isinstance(argument, str):+ return _sub_text(argument, bindings)+ if (isinstance(argument, list) and len(argument) == 2+ and isinstance(argument[0], str) and isinstance(argument[1], dict)):+ return [_sub_text(argument[0], bindings),+ {key: _expand(value, bindings, context)+ for key, value in argument[1].items()}]+ return _expand(argument, bindings, context)+++def _sub_value(argument, bindings, context):+ """``Fn::Sub`` as a transform-time value. An account resolves the map form+ during the transform, so one can be a member of a collection (measured).+ A variable left over is the stack's, so the value is unresolved."""+ if isinstance(argument, str):+ text, variables = argument, {}+ elif (isinstance(argument, list) and len(argument) == 2+ and isinstance(argument[0], str) and isinstance(argument[1], dict)):+ text, variables = argument+ else:+ raise _Unresolved("Fn::Sub")+ substituted = _sub_text(text, bindings)+ for name, value in variables.items():+ resolved = _value(value, bindings, context)+ if resolved is _REMOVE or isinstance(resolved, (list, dict)):+ raise _Unresolved("Fn::Sub")+ substituted = substituted.replace("${" + name + "}", str(resolved))+ if "${" in substituted.replace("${!", ""):+ raise _Unresolved("Fn::Sub")+ return substituted.replace("${!", "${")+++def _two_argument_value(function, argument, bindings, context):+ first, second = argument+ if function == "Fn::Split":+ source = _value(second, bindings, context)+ if not isinstance(first, str) or not isinstance(source, str):+ raise _Unresolved(function)+ return source.split(first)+ items = _value(second, bindings, context)+ if not isinstance(items, list):+ raise _Unresolved(function)+ if function == "Fn::Join":+ return str(first).join(str(item) for item in items)+ index = _value(first, bindings, context)+ try:+ index = int(index)+ except (TypeError, ValueError):+ raise _Unresolved(function) from None+ if not 0 <= index < len(items):+ # Measured for index -1.+ _fail(f"Fn::Select cannot select nonexistent value at index {index}")+ return items[index]+++def _ref_value(name, bindings, context):+ """A ``Ref`` as a value: a loop identifier or a parameter; a list parameter+ answers its members."""+ if not isinstance(name, str):+ name = _value(name, bindings, context)+ if name in bindings:+ return bindings[name]+ if name == "AWS::NoValue":+ return _REMOVE+ if name in context.parameters:+ value = context.parameters[name]+ if name in context.lists:+ return [part.strip() for part in str(value).split(",")]+ return value+ raise _Unresolved(f"Ref {name}")+++def _find_in_map(arguments, bindings, context):+ """``Fn::FindInMap`` with its ``DefaultValue``, through the engine's lookup.+ Resolving it here is what puts a per-item value into a place no intrinsic+ is resolved in, such as the ``Condition`` of a copy."""+ from .engine import find_in_map # the engine imports this module++ if not isinstance(arguments, list) or len(arguments) < 3:+ raise _Unresolved("Fn::FindInMap")+ try:+ return find_in_map(arguments, context.mappings,+ lambda node: _value(node, bindings, context))+ except LanguageExtensionsError:+ raise+ except ValueError:+ raise _Unresolved("Fn::FindInMap") from None+++def _find_in_map_node(arguments, bindings, context):+ """The value when the transform can compute it, otherwise the node with+ its loops expanded, which ``engine.find_in_map`` resolves later."""+ try:+ return _find_in_map(arguments, bindings, context)+ except _Unresolved:+ return {"Fn::FindInMap": _expand(arguments, bindings, context)}diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex dcdbc3f3..e31a42d8 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -2557,7 +2557,7 @@ def test_cfn_declared_transforms_drive_the_sam_transform(monkeypatch):(Transform: {Name: ...}) is the form that used to be reported and notapplied."""from ministack.services.cloudformation.engine import (- _apply_sam_transform_if_applicable,+ _apply_transforms,declared_transforms,)@@ -2571,7 +2571,7 @@ def test_cfn_declared_transforms_drive_the_sam_transform(monkeypatch):["AWS::Serverless-2016-10-31"]):template = json.loads(json.dumps(dict(sam, Transform=declared)))assert declared_transforms(template) == ["AWS::Serverless-2016-10-31"]- out = _apply_sam_transform_if_applicable(template)+ out = _apply_transforms(template)types = {res.get("Type") for res in out["Resources"].values()}assert "AWS::Serverless::Function" not in typesassert "AWS::Lambda::Function" in types@@ -2580,6 +2580,31 @@ def test_cfn_declared_transforms_drive_the_sam_transform(monkeypatch):assert declared_transforms({}) == []+def test_cfn_language_extensions_runs_before_the_sam_transform():+ """"If you're using both the AWS::LanguageExtensions and AWS::Serverless+ transforms, the AWS::LanguageExtensions transform must come before the+ AWS::Serverless transform in the list" (transform-aws-languageextensions).+ A loop over AWS::Serverless::Function resources therefore reaches SAM+ expanded: in the other order SAM is handed an Fn::ForEach key it does not+ know, and the copies the loop produces are never translated."""+ from ministack.services.cloudformation.engine import _apply_transforms++ template = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Transform": ["AWS::LanguageExtensions", "AWS::Serverless-2016-10-31"],+ "Resources": {"Fn::ForEach::Functions": ["Id", ["A", "B"], {+ "Fn${Id}": {"Type": "AWS::Serverless::Function", "Properties": {+ "Runtime": "python3.12", "Handler": "index.handler",+ "CodeUri": "s3://b/k"}}}]},+ }+ out = _apply_transforms(json.loads(json.dumps(template)))+ types = {name: res.get("Type") for name, res in out["Resources"].items()}+ assert types["FnA"] == "AWS::Lambda::Function"+ assert types["FnB"] == "AWS::Lambda::Function"+ # Both transforms are spent, so the processed template declares neither.+ assert "Transform" not in out++def test_cfn_validate_template_reports_capabilities_and_transforms(cfn):"""ValidateTemplate answers Capabilities, CapabilitiesReason andDeclaredTransforms, the three response elements the API documents next to@@ -13306,7 +13331,7 @@ def test_cfn_sam_transform_missing_translator_falls_back(monkeypatch):import sysfrom ministack.services.cloudformation.engine import (- _apply_sam_transform_if_applicable,+ _apply_transforms,)# Simulate the package being absent: a None entry makes `from ... import`@@ -13324,14 +13349,14 @@ def test_cfn_sam_transform_missing_translator_falls_back(monkeypatch):},}with pytest.raises(ValueError) as exc:- _apply_sam_transform_if_applicable(template)+ _apply_transforms(template)msg = str(exc.value)assert "AWS::Serverless-2016-10-31" in msgassert "docs/iac#sam" in msg# Templates that don't use the SAM transform are unaffected.plain = {"Resources": {"B": {"Type": "AWS::S3::Bucket", "Properties": {}}}}- assert _apply_sam_transform_if_applicable(plain) is plain+ assert _apply_transforms(plain) is plain# AWS::OpenSearchService::Domain@@ -22262,3 +22287,436 @@ def _include_transform(cfn, s3, ssm, uid, bucket, name):== "second"assert ssm.get_parameter(Name=f"/cfn-include/{uid}/merged")["Parameter"]["Value"] \== "edited"++++# ---------------------------------------------------------------------------+# AWS::LanguageExtensions transform+# ---------------------------------------------------------------------------++_LANGEXT_ERROR = "Transform AWS::LanguageExtensions failed with: "++# An Fn::ForEach in a template that declares no transform, from CreateStack and+# ValidateTemplate alike (measured).+_LANGEXT_UNDECLARED_LOOP = ("Template format error: [/Resources/Fn::ForEach::Loop] "+ "resource definition is malformed")+++def test_cfn_language_extensions_transform(cfn, ssm):+ """Fn::ForEach over a literal list, a CommaDelimitedList parameter, nested+ and inside Properties; the identifier in a fragment key, an Fn::Sub and a+ Ref to it, literal everywhere else; Fn::Length, Fn::ToJsonString (one+ member left to the stack), FindInMap deciding a Condition, a Conditions+ loop, a DeletionPolicy from Fn::If. Then a change set, a failed update that+ rolls back, the update, UsePreviousTemplate (no re-expansion, measured) and+ the delete."""+ uid = _uuid_mod.uuid4().hex[:8]+ name = f"cfn-langext-{uid}"+ prefix = f"/cfn-langext/{uid}"+ try:+ _language_extensions(cfn, ssm, prefix, name)+ finally:+ _delete_cfn_test_stack(cfn, name)+ for suffix in ("/kept-x", "/address-10.3"):+ try:+ ssm.delete_parameter(Name=prefix + suffix)+ except ClientError:+ pass+++def _langext_template(prefix):+ def parameter(suffix, value, tags=None, **extra):+ properties = {"Name": {"Fn::Sub": prefix + suffix}, "Type": "String", "Value": value}+ if tags:+ properties["Tags"] = tags+ return dict({"Type": "AWS::SSM::Parameter", "Properties": properties}, **extra)++ return {+ "Transform": "AWS::LanguageExtensions",+ "Parameters": {+ "Addresses": {"Type": "CommaDelimitedList", "Default": "10.1,10.2"},+ "Stage": {"Type": "String", "Default": "dev"},+ },+ "Mappings": {"Gate": {"Condition": {"A": "Never"}},+ "Values": {"Only": {"A": "from-map"}}},+ "Conditions": {+ "Always": {"Fn::Equals": [{"Ref": "Stage"}, "dev"]},+ "Never": {"Fn::Equals": [{"Ref": "Stage"}, "prod"]},+ "Fn::ForEach::Tiers": ["Tier", ["dev", "prod"], {+ "Is${Tier}": {"Fn::Equals": [{"Ref": "Stage"}, {"Ref": "Tier"}]},+ }],+ },+ "Resources": {+ # GatedA's condition is false; GatedB's default is AWS::NoValue.+ "Fn::ForEach::Gated": ["Id", ["A", "B"], {+ "Gated${Id}": parameter(+ "/gated-${Id}",+ {"Fn::FindInMap": ["Values", "Only", {"Ref": "Id"},+ {"DefaultValue": "default"}]},+ Condition={"Fn::FindInMap": ["Gate", "Condition", {"Ref": "Id"},+ {"DefaultValue": {"Ref": "AWS::NoValue"}}]}),+ }],+ "Fn::ForEach::Addresses": ["Address", {"Ref": "Addresses"}, {+ "Address&{Address}": parameter("/address-${Address}", {"Ref": "Address"}),+ }],+ "Fn::ForEach::Outer": ["Outer", ["x", "y"], {+ "Pair${Outer}": parameter("/pair-${Outer}", "pair"),+ "Fn::ForEach::Inner": ["Inner", ["1", "2"], {+ "Pair${Outer}${Inner}": parameter(+ "/pair-${Outer}-${Inner}",+ {"Fn::GetAtt": [{"Fn::Sub": "Pair${Outer}"}, "Value"]}),+ }],+ }],+ "Counted": parameter("/counted", {"Fn::Sub": [+ "${Count}", {"Count": {"Fn::Length": {"Ref": "Addresses"}}}]}),+ "TierDev": parameter("/tier-dev", "dev", Condition="Isdev"),+ "TierProd": parameter("/tier-prod", "prod", Condition="Isprod"),+ # A plain value, &{Id} in an Fn::Sub and a nested key stay literal+ # (measured); a loop inside Properties produces its keys, which+ # need not be alphanumeric (measured).+ "Fn::ForEach::Literal": ["Id", ["x"], {+ "Literal${Id}": parameter("/literal-${Id}", "${Id}", tags={+ "Fn::ForEach::Tags": ["Tag", ["a", "b"], {"VAR_${Tag}": {"Ref": "Tag"}}]}),+ "Sub${Id}": parameter("/sub-${Id}", {"Fn::Sub": "&{Id}|${Id}"}),+ "Nested${Id}": parameter("/nested-${Id}", {"Fn::ToJsonString": {+ "k${Id}": {"Ref": "Id"}}}),+ }],+ "Json": parameter("/json", {"Fn::ToJsonString": {"config": {+ "stage": {"Ref": "Stage"}, "addresses": {"Ref": "Addresses"},+ "region": {"Ref": "AWS::Region"}}}}),+ "Fn::ForEach::Kept": ["Id", ["x"], {+ "Kept${Id}": parameter("/kept-${Id}", "kept",+ DeletionPolicy={"Fn::If": ["Always", "Retain", "Delete"]}),+ }],+ },+ "Outputs": {"Fn::ForEach::Names": ["Id", ["x"], {+ "Pair${Id}Name": {"Value": {"Ref": {"Fn::Sub": "Pair${Id}"}}},+ "Pair${Id}Literal": {"Value": {"Fn::Join": ["", ["&{Id}", "-", "${Id}"]]}},+ }]},+ }+++def _language_extensions(cfn, ssm, prefix, name):+ template = json.dumps(_langext_template(prefix))++ def value(suffix):+ return ssm.get_parameter(Name=prefix + suffix)["Parameter"]["Value"]++ def logical_ids():+ return sorted(r["LogicalResourceId"] for r in+ cfn.describe_stack_resources(StackName=name)["StackResources"])++ def update(expected, addresses, **kwargs):+ cfn.update_stack(StackName=name, **kwargs, Parameters=[+ {"ParameterKey": "Addresses", "ParameterValue": addresses}])+ stack = _wait_stack(cfn, name)+ assert stack["StackStatus"] == expected, stack.get("StackStatusReason")++ cfn.create_stack(StackName=name, TemplateBody=template)+ stack = _wait_stack(cfn, name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ created = ["Address101", "Address102", "Counted", "GatedB", "Json", "Keptx", "Literalx",+ "Nestedx", "Pairx", "Pairx1", "Pairx2", "Pairy", "Pairy1", "Pairy2", "Subx",+ "TierDev"]+ assert logical_ids() == created+ assert value("/gated-B") == "default"+ assert value("/tier-dev") == "dev"+ for missing in ("/gated-A", "/tier-prod"):+ with pytest.raises(ClientError):+ ssm.get_parameter(Name=prefix + missing)+ assert value("/address-10.2") == "10.2"+ assert value("/literal-x") == "${Id}"+ assert value("/sub-x") == "&{Id}|x"+ assert value("/nested-x") == '{"k${Id}":"x"}'+ tags = ssm.list_tags_for_resource(ResourceType="Parameter", ResourceId=prefix + "/literal-x")+ assert {t["Key"]: t["Value"] for t in tags["TagList"]+ if not t["Key"].startswith("aws:")} == {"VAR_a": "a", "VAR_b": "b"}+ assert value("/pair-y-2") == "pair"+ assert value("/counted") == "2"+ assert value("/json") == ('{"config":{"stage":"dev","addresses":["10.1","10.2"],'+ f'"region":"{cfn.meta.region_name}"}}}}')+ assert _output(stack, "PairxName") == prefix + "/pair-x"+ assert _output(stack, "PairxLiteral") == "&{Id}-${Id}"++ stored = cfn.get_template(StackName=name)["TemplateBody"]+ assert "Fn::ForEach::Addresses" in stored["Resources"]++ parameters = [{"ParameterKey": "Addresses", "ParameterValue": "10.1,10.2,10.3"}]+ cfn.create_change_set(StackName=name, ChangeSetName="third",+ TemplateBody=template, Parameters=parameters)+ for _ in range(40):+ described = cfn.describe_change_set(StackName=name, ChangeSetName="third")+ if described["Status"] in ("CREATE_COMPLETE", "FAILED"):+ break+ time.sleep(0.25)+ assert described["Status"] == "CREATE_COMPLETE", described.get("StatusReason")+ assert [c["ResourceChange"]["LogicalResourceId"] for c in described["Changes"]+ if c["ResourceChange"]["Action"] == "Add"] == ["Address103"]+ cfn.delete_change_set(StackName=name, ChangeSetName="third")++ # The third copy collides with a parameter outside the stack: the update+ # rolls back to the two-address expansion.+ ssm.put_parameter(Name=prefix + "/address-10.3", Value="outside", Type="String")+ update("UPDATE_ROLLBACK_COMPLETE", "10.1,10.2,10.3", TemplateBody=template)+ assert logical_ids() == created+ assert value("/counted") == "2"+ ssm.delete_parameter(Name=prefix + "/address-10.3")++ update("UPDATE_COMPLETE", "10.1,10.2,10.3", TemplateBody=template)+ assert value("/address-10.3") == "10.3"+ assert value("/counted") == "3"++ # UsePreviousTemplate reuses the processed template: a new list value does+ # not expand the loop again (measured).+ update("UPDATE_COMPLETE", "10.1", UsePreviousTemplate=True)+ assert "Address103" in logical_ids()+ assert value("/counted") == "3"++ cfn.delete_stack(StackName=name)+ assert _wait_stack(cfn, name)["StackStatus"] == "DELETE_COMPLETE"+ assert value("/kept-x") == "kept"+ with pytest.raises(ClientError):+ ssm.get_parameter(Name=prefix + "/counted")+++def test_cfn_language_extensions_refusals(cfn):+ """Every refusal answers before a stack exists; an account rolls back a+ created stack instead. Sentences marked measured are the account's."""+ name = f"cfn-langext-refused-{_uuid_mod.uuid4().hex[:8]}"+ topic = {"Type": "AWS::SNS::Topic", "Properties": {"TopicName": {"Fn::Sub": "t-${Id}"}}}++ def loop(spec, **sections):+ return dict({"Transform": "AWS::LanguageExtensions",+ "Resources": {"Fn::ForEach::Loop": spec}}, **sections)++ def declared(resources, **sections):+ return dict({"Transform": "AWS::LanguageExtensions", "Resources": resources},+ **sections)++ def undeclared_function(function, argument):+ return {"Resources": {"T": {"Type": "AWS::SNS::Topic", "Properties": {+ "DisplayName": {function: argument}}}}}++ cases = [+ ({"Resources": {"Fn::ForEach::Loop": ["Id", ["a"], {"T${Id}": topic}]}},+ _LANGEXT_UNDECLARED_LOOP), # measured+ (undeclared_function("Fn::Length", ["a", "b"]),+ _LANGEXT_ERROR + "Fn::Length requires the AWS::LanguageExtensions transform, "+ "which the template does not declare."),+ (undeclared_function("Fn::ToJsonString", {"a": "b"}),+ _LANGEXT_ERROR + "Fn::ToJsonString requires the AWS::LanguageExtensions "+ "transform, which the template does not declare."),+ (declared({"T": topic}, Mappings={"M": {"Fn::ForEach::Loop": ["Id", ["a"], {"${Id}": {}}]}}),+ _LANGEXT_ERROR + "Fn::ForEach is not supported in the Mappings section. The "+ "functions of AWS::LanguageExtensions are supported in the Resources, "+ "Conditions and Outputs sections."),+ (loop(["Id", ["a"]]),+ _LANGEXT_ERROR + "Fn::ForEach::Loop takes an identifier, a collection and a "+ "fragment."),+ (loop(["Id", ["a"], {"Topic": topic}]),+ _LANGEXT_ERROR + "The key Topic of Fn::ForEach::Loop does not contain ${Id} "+ "or &{Id}. Every key a loop produces has to carry its identifier, or the "+ "iterations would collide."),+ (loop(["Id", "a,b,c", {"T${Id}": topic}]),+ _LANGEXT_ERROR + "Fn::ForEach layout is incorrect"), # measured+ (loop(["Id", {"Ref": "Plain"}, {"T${Id}": topic}],+ Parameters={"Plain": {"Type": "String", "Default": "a,b"}}),+ _LANGEXT_ERROR + "Could not find a collection or could not be resolved for "+ "Fn::ForEach"), # measured+ (loop(["Id", {"Fn::GetAtt": ["T", "TopicName"]}, {"T${Id}": topic}]),+ _LANGEXT_ERROR + "Could not find a collection or could not be resolved for "+ "Fn::ForEach"),+ (loop(["Id", {"Fn::Split": [",", {"Fn::Select": ["-1", ["z", "a,b"]]}]},+ {"T${Id}": topic}]),+ _LANGEXT_ERROR + "Fn::Select cannot select nonexistent value at index -1"), # measured+ (loop(["Id", ["10.1"], {"T${Id}": topic}]),+ _LANGEXT_ERROR + "LogicalId 'T10.1' should be alphanumeric"),+ (declared({"T": topic}, Outputs={"Fn::ForEach::Loop": ["Id", ["1-x"], {+ "Param${Id}": {"Value": "v"}}]}),+ _LANGEXT_ERROR + "OutputKey 'Param1-x' should be alphanumeric"), # measured+ (declared({"Loop": {"Type": "AWS::SNS::Topic"},+ "Fn::ForEach::Loop": ["Id", ["a"], {"T${Id}": topic}]}),+ _LANGEXT_ERROR + "The loop name Loop is the logical id of a resource. A loop "+ "name cannot conflict with a logical id in the Resources section."),+ (loop(["Id", ["a"], {"T${Id}": topic}],+ Outputs={"Fn::ForEach::Loop": ["Id", ["a"], {"O${Id}": {"Value": "v"}}]}),+ _LANGEXT_ERROR + "The loop name Loop is used more than once. A loop name must be "+ "unique within the template."),+ (declared({"T": dict(topic, Properties={+ "DisplayName": {"Fn::Length": {"Fn::GetAtt": ["T", "TopicName"]}}})}),+ _LANGEXT_ERROR + "The Fn::Length value could not be resolved for properties"), # measured+ # An account resolves this one (measured); not implemented here.+ (declared({"T": dict(topic, Properties={+ "DisplayName": {"Ref": {"Fn::Join": ["", ["a", "b"]]}}})}),+ _LANGEXT_ERROR + "Ref takes the name of a parameter or a resource here. An "+ "intrinsic function inside Ref is supported by the transform, but not by this "+ "implementation, unless a loop resolves it to a name."),+ (loop(["Id", ["a"], {"T${Id}": dict(topic, Condition="Is${Id}")}],+ Conditions={"Isa": {"Fn::Equals": [{"Ref": "AWS::Region"}, "nowhere"]}}),+ _LANGEXT_ERROR + "Key Is${Id} is missing in the map."), # measured+ (loop(["Id", ["a"], {"T${Id}": topic}],+ Outputs={"Fn::ForEach::Names": ["Id", ["a"], {+ "O${Id}": {"Value": {"Fn::Sub": "${T${Id}}"}}}]}),+ "Template error: variable names in Fn::Sub syntax must contain only alphanumeric "+ "characters, underscores, periods, and colons"), # measured+ ({"Resources": {"T": {"Type": "AWS::SNS::Topic",+ "Fn::Transform": {"Name": "AWS::LanguageExtensions"}}}},+ _LANGEXT_ERROR + "the transform is declared at the top level of a template only."),+ # "the quotas ... apply to the resultant template".+ (loop(["Id", [str(i) for i in range(501)], {"T${Id}": topic}]),+ "Template format error: Number of resources, 501, is greater than maximum "+ "allowed, 500"),+ ]+ try:+ for template, expected in cases:+ with pytest.raises(ClientError) as exc:+ cfn.create_stack(StackName=name, TemplateBody=json.dumps(template))+ assert exc.value.response["Error"]["Code"] == "ValidationError"+ assert exc.value.response["Error"]["Message"] == expected+ with pytest.raises(ClientError):+ cfn.describe_stacks(StackName=name)+ finally:+ _delete_cfn_test_stack(cfn, name)+++def test_cfn_language_extensions_validate_template_and_summary(cfn):+ """ValidateTemplate refuses an undeclared loop with CreateStack's sentence;+ neither it nor GetTemplateSummary expands a declaring template. The+ summary then carries no ResourceTypes and no Capabilities (measured)."""+ undeclared = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {"Fn::ForEach::Loop": ["Id", ["a", "b"], {+ "T${Id}": {"Type": "AWS::SNS::Topic"}}]},+ }+ with pytest.raises(ClientError) as exc:+ cfn.validate_template(TemplateBody=json.dumps(undeclared))+ assert exc.value.response["Error"]["Message"] == _LANGEXT_UNDECLARED_LOOP++ declared = dict(undeclared, Transform="AWS::LanguageExtensions",+ Parameters={"Topics": {"Type": "CommaDelimitedList", "Default": "a,b"}})+ declared["Resources"] = dict(declared["Resources"], Bucket={"Type": "AWS::S3::Bucket"})+ result = cfn.validate_template(TemplateBody=json.dumps(declared))+ assert [p["ParameterKey"] for p in result["Parameters"]] == ["Topics"]+ assert result["Capabilities"] == ["CAPABILITY_AUTO_EXPAND"]++ summary = cfn.get_template_summary(TemplateBody=json.dumps(declared))+ assert "ResourceTypes" not in summary+ assert "Capabilities" not in summary+ assert summary["DeclaredTransforms"] == ["AWS::LanguageExtensions"]+ assert [p["ParameterKey"] for p in summary["Parameters"]] == ["Topics"]+++def test_cfn_language_extensions_collections(cfn, ssm):+ """Collections an intrinsic answers, all measured: Fn::Sub members with a+ variable map, Fn::Split over Fn::Select, Fn::FindInMap answering a list."""+ uid = _uuid_mod.uuid4().hex[:8]+ name = f"cfn-langext-coll-{uid}"+ prefix = f"/cfn-langext-coll/{uid}"++ def copies(loop, identifier, collection):+ return {f"Fn::ForEach::{loop}": [identifier, collection, {+ f"{loop}${{{identifier}}}": {"Type": "AWS::SSM::Parameter", "Properties": {+ "Name": {"Fn::Sub": f"{prefix}/{loop}-${{{identifier}}}"},+ "Type": "String", "Value": {"Ref": identifier}}}}]}++ template = {+ "Transform": "AWS::LanguageExtensions",+ "Parameters": {"Stage": {"Type": "String", "Default": "dev"}},+ "Mappings": {"M": {"k": {"list": ["m1", "m2"]}}},+ "Resources": dict(+ copies("Sub", "Item", [{"Fn::Sub": ["${Stage}one", {"Stage": {"Ref": "Stage"}}]},+ {"Fn::Sub": ["${Stage}two", {"Stage": {"Ref": "Stage"}}]}]),+ **copies("Split", "Part", {"Fn::Split": [",", {"Fn::Select": [1, ["z", "s1,s2"]]}]}),+ **copies("Map", "Entry", {"Fn::FindInMap": ["M", "k", "list"]})),+ # Only a variable nested in a name is refused; any other name is the engine's.+ "Outputs": {"Odd": {"Value": {"Fn::Sub": "${Not-Alnum}"}}},+ }+ try:+ cfn.create_stack(StackName=name, TemplateBody=json.dumps(template))+ stack = _wait_stack(cfn, name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ assert sorted(r["LogicalResourceId"] for r in+ cfn.describe_stack_resources(StackName=name)["StackResources"]) \+ == ["Mapm1", "Mapm2", "Splits1", "Splits2", "Subdevone", "Subdevtwo"]+ assert ssm.get_parameter(Name=prefix + "/Sub-devtwo")["Parameter"]["Value"] == "devtwo"+ assert _output(stack, "Odd") == "Not-Alnum"+ finally:+ _delete_cfn_test_stack(cfn, name)+++def test_cfn_language_extensions_reference_to_a_plain_string_target(cfn, ssm):+ """A Ref, Fn::GetAtt or DependsOn naming the plain string ``Param${Item}``+ names nothing. An account fails the stack over each (measured); this+ engine resolves an unknown Ref to its name, an unknown Fn::GetAtt to ""+ and ignores an unknown DependsOn for every template. Pinned here."""+ uid = _uuid_mod.uuid4().hex[:8]+ name = f"cfn-langext-plain-{uid}"+ prefix = f"/cfn-langext-plain/{uid}"+ template = {+ "Transform": "AWS::LanguageExtensions",+ "Resources": {"Fn::ForEach::Items": ["Item", ["alpha"], {+ "Param${Item}": {+ "Type": "AWS::SSM::Parameter",+ "Properties": {"Name": {"Fn::Sub": prefix + "/${Item}"},+ "Type": "String", "Value": {"Ref": "Item"}},+ },+ "Dep${Item}": {+ "Type": "AWS::SSM::Parameter",+ "DependsOn": "Param${Item}",+ "Properties": {"Name": {"Fn::Sub": prefix + "/dep-${Item}"},+ "Type": "String", "Value": {"Ref": "Item"}},+ },+ }]},+ "Outputs": {"Fn::ForEach::Names": ["Item", ["alpha"], {+ "Good${Item}": {"Value": {"Ref": {"Fn::Sub": "Param${Item}"}}},+ "Bad${Item}": {"Value": {"Ref": "Param${Item}"}},+ "BadAtt${Item}": {"Value": {"Fn::GetAtt": ["Param${Item}", "Value"]}},+ }]},+ }+ try:+ cfn.create_stack(StackName=name, TemplateBody=json.dumps(template))+ stack = _wait_stack(cfn, name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ assert _output(stack, "Goodalpha") == prefix + "/alpha"+ assert _output(stack, "Badalpha") == "Param${Item}"+ assert _output(stack, "BadAttalpha") == ""+ assert sorted(r["LogicalResourceId"] for r in+ cfn.describe_stack_resources(StackName=name)["StackResources"]) \+ == ["Depalpha", "Paramalpha"]+ finally:+ _delete_cfn_test_stack(cfn, name)+++def test_cfn_language_extensions_condition_from_an_intrinsic(cfn, ssm):+ """An Fn::Sub in the Condition of a copy resolves to the condition name,+ so only the copy whose condition is true is created (measured). The+ transform is declared in the {"Name": ...} form (measured)."""+ uid = _uuid_mod.uuid4().hex[:8]+ name = f"cfn-langext-cond-{uid}"+ prefix = f"/cfn-langext-cond/{uid}"+ template = {+ "Transform": {"Name": "AWS::LanguageExtensions"},+ "Parameters": {"Stage": {"Type": "String", "Default": "alpha"}},+ "Conditions": {"Fn::ForEach::Flags": ["Item", ["alpha", "beta"], {+ "Is${Item}": {"Fn::Equals": [{"Ref": "Stage"}, {"Ref": "Item"}]},+ }]},+ "Resources": {"Fn::ForEach::Params": ["Item", ["alpha", "beta"], {+ "Param${Item}": {+ "Type": "AWS::SSM::Parameter",+ "Condition": {"Fn::Sub": "Is${Item}"},+ "Properties": {"Name": {"Fn::Sub": prefix + "/${Item}"},+ "Type": "String", "Value": {"Ref": "Item"}},+ },+ }]},+ }+ try:+ cfn.create_stack(StackName=name, TemplateBody=json.dumps(template))+ stack = _wait_stack(cfn, name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ assert [r["LogicalResourceId"] for r in+ cfn.describe_stack_resources(StackName=name)["StackResources"]] \+ == ["Paramalpha"]+ with pytest.raises(ClientError):+ ssm.get_parameter(Name=prefix + "/beta")+ finally:+ _delete_cfn_test_stack(cfn, name)