Skip to content

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

feat(cloudformation): resolve dynamic references (#1647)

iot-rocketb5f8034e13bb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 81f138af..eeb8c27f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Added
+- **CloudFormation — dynamic references resolve** — `{{resolve:ssm:...}}`, `{{resolve:ssm-secure:...}}` and `{{resolve:secretsmanager:...}}` were refused up front (before that, the literal reached the service). They now resolve at provisioning time against the in-process stores — a parameter by name and optional version, a secret by name or ARN with the optional `SecretString`, JSON key, version stage or version id segments — and `GetTemplate` keeps the literal. On update the two kinds follow what a real account does: an `ssm` reference re-resolves when the stack is updated with a changed template or parameters (an identical template is accepted and changes nothing; `UsePreviousTemplate` is still refused with "No updates are to be performed."), a `secretsmanager` reference only when the resource that carries it changes. A reference that cannot be resolved fails the resource; a reference to any other service is refused before a stack exists. Contributed by @iot-rocket.
### Fixed
- **CloudFormation — a change set sees `DeletionPolicy`, `UpdateReplacePolicy` and `Metadata` edits** — the diff compared `Properties` only, so a change set that only changed a resource's removal policy (a CDK `removalPolicy` edit) ended `FAILED` with "didn't contain changes" and the policy never reached the stack. Those attributes now count as a `Modify` with `Replacement: False` and are reported in `Scope` and `Details` with the target attribute, as the API reference defines them; a property change lists the property names. A `DependsOn`-only edit stays a no-change set, as on AWS. Contributed by @iot-rocket.
diff --git a/ministack/services/cloudformation/engine.py b/ministack/services/cloudformation/engine.py
index 8e85e154..320c4a37 100644
--- a/ministack/services/cloudformation/engine.py
+++ b/ministack/services/cloudformation/engine.py
@@ -114,7 +114,8 @@ def _parse_template(template_body: str) -> dict:
# Template pre-flight
# ===========================================================================
-_DYNAMIC_REFERENCE = re.compile(r"\{\{resolve:([a-z-]+):[^}]*\}\}")
+_DYNAMIC_REFERENCE = re.compile(r"\{\{resolve:([a-z-]+):([^}]*)\}\}")
+_DYNAMIC_SERVICES = ("ssm", "ssm-secure", "secretsmanager")
def _find_dynamic_references(value, found: set) -> None:
@@ -129,6 +130,107 @@ def _find_dynamic_references(value, found: set) -> None:
_find_dynamic_references(v, found)
+def _has_dynamic_references(template: dict) -> bool:
+ refs: set[str] = set()
+ _find_dynamic_references((template or {}).get("Resources"), refs)
+ return bool(refs)
+
+
+def _resolve_dynamic_reference(literal: str) -> str:
+ """Resolve one ``{{resolve:...}}`` literal against the in-process SSM /
+ Secrets Manager stores. Raises ``ValueError`` when it cannot be resolved,
+ which fails the resource the way an unresolvable reference does on AWS.
+ ``ssm`` / ``ssm-secure`` take ``name[:version]`` (no version = latest);
+ ``secretsmanager`` takes
+ ``secret-id[:SecretString[:json-key[:version-stage[:version-id]]]]``,
+ the secret id being a name or an ARN."""
+ from ministack.services import secretsmanager, ssm
+
+ m = _DYNAMIC_REFERENCE.fullmatch(literal)
+ service, body = m.group(1), m.group(2)
+ if service in ("ssm", "ssm-secure"):
+ name, _, version = body.partition(":")
+ value = ssm.resolve_parameter_value(name, version or None, decrypt=True)
+ if value is None:
+ raise ValueError(
+ f"Dynamic reference {literal} could not be resolved: parameter "
+ f"{name}" + (f" version {version}" if version else "") + " not found")
+ return value
+ if body.startswith("arn:"):
+ parts = body.split(":")
+ secret_id, rest = ":".join(parts[:7]), parts[7:]
+ else:
+ parts = body.split(":")
+ secret_id, rest = parts[0], parts[1:]
+ rest += [""] * (4 - len(rest))
+ secret_string, json_key, version_stage, version_id = rest[:4]
+ if secret_string and secret_string != "SecretString":
+ raise ValueError(
+ f"Dynamic reference {literal} is invalid: the secret-string segment "
+ "must be SecretString")
+ if version_stage and version_id:
+ raise ValueError(
+ f"Dynamic reference {literal} is invalid: specify either a version "
+ "stage or a version id, not both")
+ value = secretsmanager.resolve_secret_string(
+ secret_id, version_stage or "AWSCURRENT", version_id or None)
+ if value is None:
+ raise ValueError(
+ f"Dynamic reference {literal} could not be resolved: secret "
+ f"{secret_id} not found")
+ if json_key:
+ try:
+ value = json.loads(value)[json_key]
+ except (ValueError, KeyError, TypeError):
+ raise ValueError(
+ f"Dynamic reference {literal} could not be resolved: key "
+ f"{json_key} not found in the secret") from None
+ if not isinstance(value, str):
+ value = json.dumps(value)
+ return value
+
+
+def _resolve_dynamic_references(value, previous: dict | None = None,
+ reuse_ssm: bool = False,
+ reuse_secrets: bool = False):
+ """Substitute every ``{{resolve:...}}`` inside ``value`` (recursively).
+
+ Returns ``(resolved_value, {literal: value})``. ``previous`` is the map a
+ prior deployment of the same resource recorded; ``reuse_ssm`` /
+ ``reuse_secrets`` keep those values instead of resolving again, which is
+ how the two kinds differ on update: an ``ssm`` reference re-resolves
+ whenever the stack is updated with a changed template, a
+ ``secretsmanager`` reference only when the resource that carries it
+ changes.
+ """
+ previous = previous or {}
+ resolved: dict = {}
+
+ def one(literal):
+ if literal in resolved:
+ return resolved[literal]
+ service = _DYNAMIC_REFERENCE.fullmatch(literal).group(1)
+ reuse = reuse_secrets if service == "secretsmanager" else reuse_ssm
+ if reuse and literal in previous:
+ resolved[literal] = previous[literal]
+ else:
+ resolved[literal] = _resolve_dynamic_reference(literal)
+ return resolved[literal]
+
+ def walk(node):
+ if isinstance(node, str):
+ if "{{resolve:" not in node:
+ return node
+ return _DYNAMIC_REFERENCE.sub(lambda m: one(m.group(0)), node)
+ if isinstance(node, list):
+ return [walk(v) for v in node]
+ if isinstance(node, dict):
+ return {k: walk(v) for k, v in node.items()}
+ return node
+
+ return walk(value), resolved
+
+
def validate_template_support(template: dict, conditions: dict) -> None:
"""Reject up front what provisioning could only fail on halfway through.
@@ -139,9 +241,9 @@ def validate_template_support(template: dict, conditions: dict) -> None:
provisions its predecessors first and rolls them back. Condition-false
resources are exempt, as they are during provisioning.
- Dynamic references (``{{resolve:ssm:...}}`` and friends) are not resolved
- by this emulator; refusing them here replaces the old behaviour of passing
- the literal ``{{resolve:...}}`` string on to the service.
+ Dynamic references are resolved at provisioning time (``ssm``,
+ ``ssm-secure`` and ``secretsmanager``); a reference to any other service
+ is refused here, as is a malformed one.
Raises ``ValueError`` with the message the caller wraps as a
``ValidationError``.
@@ -181,10 +283,13 @@ def validate_template_support(template: dict, conditions: dict) -> None:
refs: set[str] = set()
_find_dynamic_references(template.get("Resources"), refs)
_find_dynamic_references(template.get("Outputs"), refs)
- if refs:
+ unsupported = sorted(
+ r for r in refs if _DYNAMIC_REFERENCE.fullmatch(r).group(1) not in _DYNAMIC_SERVICES)
+ if unsupported:
raise ValueError(
- "Template format error: dynamic references are not supported by "
- "ministack: " + ", ".join(sorted(refs))
+ "Template format error: unsupported dynamic reference(s): "
+ + ", ".join(unsupported)
+ + " (supported: ssm, ssm-secure, secretsmanager)"
)
diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.py
index 85681882..a38dc61c 100644
--- a/ministack/services/cloudformation/handlers.py
+++ b/ministack/services/cloudformation/handlers.py
@@ -20,6 +20,7 @@ from .changesets import (
from .engine import (
_apply_sam_transform_if_applicable,
_evaluate_conditions,
+ _has_dynamic_references,
_parse_template,
_resolve_parameters,
_resolve_refs,
@@ -553,16 +554,19 @@ def _delete_stack(params):
# --- UpdateStack ---
-def _stack_has_no_updates(stack, template, param_values, tags):
+def _stack_has_no_updates(stack, template, param_values, tags,
+ use_previous_template=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
CloudFormation refuses such a request with ``No updates are to be
- performed.`` instead of running an empty update (a template with a
- dynamic reference is the documented exception, and the emulator refuses
- dynamic references up front)."""
+ performed.`` instead of running an empty update. A template body that
+ carries a dynamic reference is the exception: the update is accepted
+ (with ``UsePreviousTemplate`` it is still refused) — measured on AWS."""
if template != stack.get("_template", {}):
return False
+ if not use_previous_template and _has_dynamic_references(template):
+ return False
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
@@ -600,10 +604,12 @@ def _update_stack(params):
template_body, resolve_err = _resolve_template(params)
if resolve_err:
return resolve_err
+ use_previous_template = False
if not template_body:
# Use previous template if UsePreviousTemplate
if _p(params, "UsePreviousTemplate", "false").lower() == "true":
template_body = stack.get("_template_body", "{}")
+ use_previous_template = True
else:
return _error("ValidationError", "TemplateBody or TemplateURL is required")
@@ -629,7 +635,8 @@ def _update_stack(params):
except ValueError as exc:
return _error("ValidationError", str(exc))
- if _stack_has_no_updates(stack, template, param_values, tags):
+ if _stack_has_no_updates(stack, template, param_values, tags,
+ use_previous_template):
return _error("ValidationError", "No updates are to be performed.")
# Save previous state for rollback
diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.py
index a2ab5e2a..904fa4c7 100644
--- a/ministack/services/cloudformation/stacks.py
+++ b/ministack/services/cloudformation/stacks.py
@@ -15,6 +15,7 @@ from ministack.core.responses import get_region, new_uuid, now_iso, set_request_
from .engine import (
_NO_VALUE,
_evaluate_conditions,
+ _resolve_dynamic_references,
_resolve_refs,
_topological_sort,
)
@@ -221,6 +222,30 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
resolved_props = {
k: v for k, v in resolved_props.items() if v is not _NO_VALUE
}
+ # Dynamic references, after the intrinsics: an `ssm` reference
+ # re-resolves on an update that changed the template or its
+ # parameters (an identical update keeps what the stack has), a
+ # `secretsmanager` reference only when this resource's definition
+ # changed. The per-resource map of resolved values is what the
+ # next update reuses. (measured on AWS 2026-09-02)
+ prev_for_dynamic = (
+ previous_stack.get("_resources", {}).get(logical_id)
+ if is_update and previous_stack else None
+ )
+ stack_unchanged = bool(
+ is_update and previous_stack
+ and template == previous_stack.get("_template")
+ and param_values == previous_stack.get("_resolved_params"))
+ resource_unchanged = bool(
+ prev_for_dynamic is not None and previous_stack
+ and (previous_stack.get("_template", {}).get("Resources", {})
+ .get(logical_id) == res_def))
+ resolved_props, dynamic_values = _resolve_dynamic_references(
+ resolved_props,
+ (prev_for_dynamic or {}).get("_dynamic"),
+ reuse_ssm=stack_unchanged,
+ reuse_secrets=resource_unchanged,
+ )
_add_event(stack_id, stack_name, logical_id, resource_type,
f"{status_prefix}_IN_PROGRESS")
@@ -291,6 +316,8 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
"Attributes": attrs,
"Timestamp": now_iso(),
}
+ if dynamic_values:
+ provisioned_resources[logical_id]["_dynamic"] = dynamic_values
created_in_this_run.append(logical_id)
_add_event(stack_id, stack_name, logical_id, resource_type,
diff --git a/ministack/services/secretsmanager.py b/ministack/services/secretsmanager.py
index 72efcca0..6210cc62 100644
--- a/ministack/services/secretsmanager.py
+++ b/ministack/services/secretsmanager.py
@@ -162,17 +162,22 @@ def _find_stage_version(secret, stage):
return None, None
-def resolve_secret_string(secret_id, version_stage="AWSCURRENT"):
- """Return the SecretString for *secret_id* at *version_stage*, or None.
-
- Used by other services (e.g. ECS) that need to read a secret value
- in-process without going through the HTTP API. Returns None if the secret
- does not exist, is scheduled for deletion, or has no value for the stage.
+def resolve_secret_string(secret_id, version_stage="AWSCURRENT", version_id=None):
+ """Return the SecretString for *secret_id* at *version_stage* (or the
+ version *version_id*), or None.
+
+ Used by other services (e.g. ECS, CloudFormation dynamic references) that
+ need to read a secret value in-process without going through the HTTP API.
+ Returns None if the secret does not exist, is scheduled for deletion, or
+ has no value for the stage / version.
"""
_, secret = _resolve(secret_id, use_arn_scope=True)
if not secret or secret.get("DeletedDate"):
return None
- _, ver = _find_stage_version(secret, version_stage)
+ if version_id:
+ ver = secret["Versions"].get(version_id)
+ else:
+ _, ver = _find_stage_version(secret, version_stage)
if not ver:
return None
return ver.get("SecretString")
diff --git a/ministack/services/ssm.py b/ministack/services/ssm.py
index a311993c..ac2fe77f 100644
--- a/ministack/services/ssm.py
+++ b/ministack/services/ssm.py
@@ -348,18 +348,30 @@ def _put_parameter(data):
return json_response({"Version": version, "Tier": record["Tier"]})
-def resolve_parameter_value(name_or_arn):
+def resolve_parameter_value(name_or_arn, version=None, decrypt=False):
"""Return an SSM parameter's value by name or ARN, or None.
- Used by other services (e.g. ECS `secrets[].valueFrom`) that need to read a
- parameter value in-process without going through the HTTP API. Accepts a
- bare name (``/path/name`` or ``name``) or a full ARN
- (``arn:aws:ssm:region:acct:parameter/path/name``).
+ Used by other services (e.g. ECS `secrets[].valueFrom`, CloudFormation
+ dynamic references) that need to read a parameter value in-process without
+ going through the HTTP API. Accepts a bare name (``/path/name`` or
+ ``name``) or a full ARN (``arn:aws:ssm:region:acct:parameter/path/name``).
+ ``version`` selects an earlier version from the parameter's history;
+ ``decrypt`` returns a SecureString's plaintext, as GetParameter with
+ WithDecryption does.
"""
if not name_or_arn:
return None
- _, param = _lookup_parameter(name_or_arn, allow_arn_region=True, flexible_name=True)
- return param.get("Value") if param else None
+ name, param = _lookup_parameter(name_or_arn, allow_arn_region=True, flexible_name=True)
+ if not param:
+ return None
+ if version is not None and str(version) != str(param.get("Version")):
+ history = _parameter_history.get(name) or []
+ param = next((h for h in history if str(h.get("Version")) == str(version)), None)
+ if not param:
+ return None
+ if decrypt:
+ return param.get("OriginalValue", param.get("Value"))
+ return param.get("Value")
def _get_parameter(data):
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 2772c35e..2631adc8 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -1578,6 +1578,156 @@ def test_cfn_ssm_parameter_value_type_missing_parameter_fails_stack(cfn):
assert exc_info.value.response["Error"]["Code"] == "ValidationError"
+def _ssm_value(ssm, name):
+ return ssm.get_parameter(Name=name, WithDecryption=True)["Parameter"]["Value"]
+
+
+def test_cfn_dynamic_references_resolve_and_follow_the_update_rules(cfn, ssm, sm):
+ """{{resolve:ssm}}, {{resolve:ssm-secure}} and {{resolve:secretsmanager}}
+ resolve at provisioning time; GetTemplate keeps the literal. On update an
+ identical template is accepted but changes nothing, UsePreviousTemplate is
+ refused, a changed template re-resolves the ssm references (a pinned
+ version stays), and a secretsmanager reference re-resolves only when its
+ resource changes (measured on AWS)."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-dynref-{uid}"
+ src, secure, secret, json_secret = (
+ f"/cfn-dynref/{uid}/in", f"/cfn-dynref/{uid}/secure",
+ f"cfn-dynref-{uid}-plain", f"cfn-dynref-{uid}-json")
+ ssm.put_parameter(Name=src, Value="v1", Type="String")
+ ssm.put_parameter(Name=secure, Value="hush", Type="SecureString")
+ sm.create_secret(Name=secret, SecretString="s1")
+ sm.create_secret(Name=json_secret, SecretString=json.dumps({"password": "p1"}))
+ outs = {k: f"/cfn-dynref/{uid}/out-{k}" for k in ("ssm", "pinned", "secure", "secret", "key")}
+
+ def param(name, value, description=None):
+ props = {"Name": name, "Type": "String", "Value": value}
+ if description:
+ props["Description"] = description
+ return {"Type": "AWS::SSM::Parameter", "Properties": props}
+
+ def template(description="one", secret_description=None):
+ return json.dumps({"Description": description, "Resources": {
+ "FromSsm": param(outs["ssm"], f"{{{{resolve:ssm:{src}}}}}"),
+ "Pinned": param(outs["pinned"], f"{{{{resolve:ssm:{src}:1}}}}"),
+ "Secure": param(outs["secure"], f"{{{{resolve:ssm-secure:{secure}}}}}"),
+ "FromSecret": param(outs["secret"], f"prefix-{{{{resolve:secretsmanager:{secret}}}}}",
+ secret_description),
+ "FromKey": param(outs["key"],
+ f"{{{{resolve:secretsmanager:{json_secret}:SecretString:password}}}}"),
+ }})
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template())
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ assert _ssm_value(ssm, outs["ssm"]) == "v1"
+ assert _ssm_value(ssm, outs["pinned"]) == "v1"
+ assert _ssm_value(ssm, outs["secure"]) == "hush"
+ assert _ssm_value(ssm, outs["secret"]) == "prefix-s1"
+ assert _ssm_value(ssm, outs["key"]) == "p1"
+ body = cfn.get_template(StackName=stack_name)["TemplateBody"]
+ body = json.dumps(body) if not isinstance(body, str) else body
+ assert f"{{{{resolve:ssm:{src}}}}}" in body
+
+ ssm.put_parameter(Name=src, Value="v2", Type="String", Overwrite=True)
+ sm.put_secret_value(SecretId=secret, SecretString="s2")
+
+ # identical template: accepted, nothing re-resolved
+ cfn.update_stack(StackName=stack_name, TemplateBody=template())
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _ssm_value(ssm, outs["ssm"]) == "v1"
+ assert _ssm_value(ssm, outs["secret"]) == "prefix-s1"
+
+ with pytest.raises(ClientError) as exc:
+ cfn.update_stack(StackName=stack_name, UsePreviousTemplate=True)
+ assert "No updates are to be performed" in exc.value.response["Error"]["Message"]
+
+ # a changed template: ssm re-resolves, the pinned version and the secret stay
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(description="two"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _ssm_value(ssm, outs["ssm"]) == "v2"
+ assert _ssm_value(ssm, outs["pinned"]) == "v1"
+ assert _ssm_value(ssm, outs["secret"]) == "prefix-s1"
+
+ # the resource carrying the secret changes: the secret re-resolves
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=template(description="two", secret_description="touched"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _ssm_value(ssm, outs["secret"]) == "prefix-s2"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ for name in (src, secure):
+ try:
+ ssm.delete_parameter(Name=name)
+ except ClientError:
+ pass
+ for name in (secret, json_secret):
+ try:
+ sm.delete_secret(SecretId=name, ForceDeleteWithoutRecovery=True)
+ except ClientError:
+ pass
+
+
+def test_cfn_secretsmanager_reference_by_arn_version_id_and_json_number(cfn, ssm, sm):
+ """The secret id may be an ARN (its colons do not split the segments), a
+ version-stage or a version-id selects an older version, and a JSON key
+ whose value is not a string comes back as its JSON text."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-dynref-arn-{uid}"
+ secret = f"cfn-dynref-arn-{uid}"
+ created = sm.create_secret(Name=secret, SecretString=json.dumps({"port": 5432, "host": "old"}))
+ arn, first_version = created["ARN"], created["VersionId"]
+ sm.put_secret_value(SecretId=secret, SecretString=json.dumps({"port": 5433, "host": "new"}))
+ outs = {k: f"/cfn-dynref-arn/{uid}/{k}" for k in ("arn", "previous", "version")}
+
+ def param(name, value):
+ return {"Type": "AWS::SSM::Parameter",
+ "Properties": {"Name": name, "Type": "String", "Value": value}}
+
+ template = json.dumps({"Resources": {
+ "ByArn": param(outs["arn"], f"{{{{resolve:secretsmanager:{arn}:SecretString:port}}}}"),
+ "Previous": param(outs["previous"],
+ f"{{{{resolve:secretsmanager:{secret}:SecretString:host:AWSPREVIOUS}}}}"),
+ "ByVersion": param(outs["version"],
+ f"{{{{resolve:secretsmanager:{secret}:SecretString:host::{first_version}}}}}"),
+ }})
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template)
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ assert _ssm_value(ssm, outs["arn"]) == "5433"
+ assert _ssm_value(ssm, outs["previous"]) == "old"
+ assert _ssm_value(ssm, outs["version"]) == "old"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ try:
+ sm.delete_secret(SecretId=secret, ForceDeleteWithoutRecovery=True)
+ except ClientError:
+ pass
+
+
+def test_cfn_dynamic_reference_that_cannot_resolve_fails_the_resource(cfn, ssm):
+ """A reference to a missing parameter fails the resource and rolls the
+ stack back with the reason."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-dynref-bad-{uid}"
+ template = json.dumps({"Resources": {"P": {
+ "Type": "AWS::SSM::Parameter",
+ "Properties": {"Name": f"/cfn-dynref-bad/{uid}", "Type": "String",
+ "Value": f"{{{{resolve:ssm:/cfn-dynref-bad/{uid}/missing}}}}"}}}})
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template)
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ assert f"/cfn-dynref-bad/{uid}/missing" in _stack_event_reasons(cfn, stack_name)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
def test_cfn_change_set_use_previous_value_updates_resource(cfn, ssm):
"""A change set created with UsePreviousValue (the `aws cloudformation deploy`
no-`--parameter-overrides` path) must resolve the parameter to its stored
@@ -11474,20 +11624,23 @@ def test_cfn_getatt_unknown_attribute_in_properties_fails_the_resource(cfn, sqs)
_wait_stack(cfn, name)
-def test_cfn_dynamic_reference_rejected(cfn):
- """{{resolve:...}} is not resolved by the emulator; refusing it up front
- beats handing the literal string to the service."""
+def test_cfn_dynamic_reference_to_an_unsupported_service_is_rejected(cfn):
+ """{{resolve:ssm}}, {{resolve:ssm-secure}} and {{resolve:secretsmanager}}
+ resolve at provisioning time; a reference to any other service is refused
+ up front, before a stack record exists."""
tpl = json.dumps({"Resources": {"P": {
"Type": "AWS::SSM::Parameter",
"Properties": {"Type": "String", "Name": "/cfn-preflight/dyn",
- "Value": "{{resolve:secretsmanager:my-secret:SecretString:key}}"}}}})
+ "Value": "{{resolve:vault:my-secret:key}}"}}}})
with pytest.raises(ClientError) as exc:
cfn.create_stack(StackName="cfn-preflight-dyn", TemplateBody=tpl)
msg = exc.value.response["Error"]["Message"]
- assert msg.startswith("Template format error: dynamic references are not supported")
- assert "{{resolve:secretsmanager:my-secret:SecretString:key}}" in msg
+ assert msg.startswith("Template format error: unsupported dynamic reference")
+ assert "{{resolve:vault:my-secret:key}}" in msg
with pytest.raises(ClientError):
cfn.describe_stacks(StackName="cfn-preflight-dyn")
+
+
def test_cfn_events_rule_arn_matches_the_service(cfn, eb):
"""GetAtt Arn on a rule is the ARN the EventBridge service reports for
it: no bus segment on the default bus, rule/<bus>/<name> on a custom