Skip to content

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

fix(cloudformation): reject unknown types, fail unknown GetAtt attribute (#1628)

iot-rocket6be91d42d01a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c9bc495f..a86c2bbe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Fixed
+- **CloudFormation — unrecognized resource types are rejected up front, `Fn::GetAtt` to a missing attribute fails the stack** — a template with a resource type the emulator does not know provisioned every resource ahead of it, failed on that one and rolled the stack back; `CreateStack`, `UpdateStack`, `CreateChangeSet` and `ValidateTemplate` now refuse it synchronously with CloudFormation's own `Template format error: Unrecognized resource types: [...]` and leave no stack (or `REVIEW_IN_PROGRESS` placeholder) behind. Dynamic references (`{{resolve:ssm:...}}`, `{{resolve:secretsmanager:...}}`), which the emulator does not resolve, are refused the same way instead of reaching the service as literal strings. `Fn::GetAtt` to an attribute a resource does not expose answered with the physical id, a silently wrong value; it now fails the operation with `Requested attribute X does not exist in schema for T` and the stack rolls back, matching what a real account does. Outputs are resolved before the success path commits, so a failing output rolls back too and registers no export. Contributed by @iot-rocket.
### Added
- **CloudFront — the policy, OAC and function types provision from CloudFormation** — `AWS::CloudFront::CachePolicy`, `OriginRequestPolicy`, `ResponseHeadersPolicy`, `OriginAccessControl` and `Function` had complete APIs and no CloudFormation provisioner, so a CDK app declaring any of them rolled the stack back with `Unsupported resource type` while the same objects were creatable over the API. Each type now provisions by converting its CFN properties to the element the service's own config parser accepts, so validation, defaults and the stored record are identical to the API path, and `Ref`/`Fn::GetAtt` return the documented values (policy `Id`, OAC `Id`, function `FunctionARN`). Deletes are wired; an update replaces rather than mutating in place. Contributed by @mm-salesqueze.
- **S3 — Multi-Region Access Points deploy and serve** — `AWS::S3::MultiRegionAccessPoint` rolled the stack back with `Unsupported resource type` and the MRAP hostname resolved nowhere, so a CDK app fronting regional buckets with one could not deploy. The type now provisions (minting the 13-character alias and remembering its member buckets) and `<alias>.mrap.accesspoint.s3-global.amazonaws.com` resolves onto the existing virtual-hosted S3 path, so path-style rewriting, IAM enforcement and the handler apply unchanged. The member carrying the request region is served, else the first. State is account-scoped, cleared by `/_ministack/reset` and persisted. SigV4A, which S3 requires for an MRAP, is not verified — consistent with the documented no-SigV4 stance: such a request has its presign parameters dropped and is served rather than refused for a signature that could never have matched, and because a SigV4A credential scope carries no region it falls back to the first member. The s3control control plane (`CreateMultiRegionAccessPoint` and the async request token, Get/List/Delete, policies) is not included. Contributed by @mm-salesqueze.
diff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.py
index 32db8501..fc7edff3 100644
--- a/ministack/services/cloudformation/changesets.py
+++ b/ministack/services/cloudformation/changesets.py
@@ -13,6 +13,7 @@ from .engine import (
_parse_template,
_resolve_parameters,
_resolve_refs,
+ validate_template_support,
)
from .helpers import _error, _esc, _extract_members, _p, _resolve_template, _xml
from .stacks import (
@@ -151,17 +152,31 @@ def _create_change_set(params):
if not template_body:
template_body = stack.get("_template_body", "{}")
+ def _rejected(message):
+ # A rejected CreateChangeSet leaves no stack behind on AWS; drop the
+ # REVIEW_IN_PROGRESS placeholder created above for CREATE sets.
+ if cs_type == "CREATE":
+ _stacks.pop(stack_name, None)
+ _stack_events.pop(stack_id, None)
+ return _error("ValidationError", message)
+
try:
template = _parse_template(template_body)
template = _apply_sam_transform_if_applicable(template)
except Exception as e:
- return _error("ValidationError", f"Template format error: {e}")
+ return _rejected(f"Template format error: {e}")
try:
param_values = _resolve_parameters(
template, provided_params, stack.get("_resolved_params", {}))
except ValueError as exc:
- return _error("ValidationError", str(exc))
+ return _rejected(str(exc))
+
+ try:
+ validate_template_support(
+ template, _evaluate_conditions(template, param_values))
+ except ValueError as exc:
+ return _rejected(str(exc))
# Compute changes — resolve parameters/intrinsics in BOTH templates first so
# parameter-driven changes (the `aws cloudformation deploy
diff --git a/ministack/services/cloudformation/engine.py b/ministack/services/cloudformation/engine.py
index 6851f1d8..2f2b2d92 100644
--- a/ministack/services/cloudformation/engine.py
+++ b/ministack/services/cloudformation/engine.py
@@ -108,6 +108,75 @@ def _parse_template(template_body: str) -> dict:
return result
+# ===========================================================================
+# Template pre-flight
+# ===========================================================================
+
+_DYNAMIC_REFERENCE = re.compile(r"\{\{resolve:([a-z-]+):[^}]*\}\}")
+
+
+def _find_dynamic_references(value, found: set) -> None:
+ if isinstance(value, str):
+ for m in _DYNAMIC_REFERENCE.finditer(value):
+ found.add(m.group(0))
+ elif isinstance(value, dict):
+ for v in value.values():
+ _find_dynamic_references(v, found)
+ elif isinstance(value, list):
+ for v in value:
+ _find_dynamic_references(v, found)
+
+
+def validate_template_support(template: dict, conditions: dict) -> None:
+ """Reject up front what provisioning could only fail on halfway through.
+
+ Real CloudFormation validates resource types before it touches anything:
+ CreateStack, UpdateStack, CreateChangeSet and ValidateTemplate all answer
+ ``Template format error: Unrecognized resource types: [...]`` and no stack
+ record is created. Doing the same here means an unsupported type no longer
+ 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.
+
+ Raises ``ValueError`` with the message the caller wraps as a
+ ``ValidationError``.
+ """
+ from .provisioners import _RESOURCE_HANDLERS
+
+ unrecognized: set[str] = set()
+ for res in (template.get("Resources") or {}).values():
+ if not isinstance(res, dict):
+ continue
+ cond = res.get("Condition")
+ if cond and not conditions.get(cond, True):
+ continue
+ rtype = res.get("Type", "AWS::CloudFormation::CustomResource")
+ if (
+ rtype in _RESOURCE_HANDLERS
+ or rtype.startswith("Custom::")
+ or rtype.startswith("AWS::CloudFormation::")
+ ):
+ continue
+ unrecognized.add(rtype)
+ if unrecognized:
+ raise ValueError(
+ "Template format error: Unrecognized resource types: ["
+ + ", ".join(sorted(unrecognized)) + "]"
+ )
+
+ refs: set[str] = set()
+ _find_dynamic_references(template.get("Resources"), refs)
+ _find_dynamic_references(template.get("Outputs"), refs)
+ if refs:
+ raise ValueError(
+ "Template format error: dynamic references are not supported by "
+ "ministack: " + ", ".join(sorted(refs))
+ )
+
+
# ===========================================================================
# Parameter Resolver
# ===========================================================================
@@ -302,6 +371,13 @@ def _evaluate_conditions(template: dict, params: dict) -> dict:
# Intrinsic Function Resolver
# ===========================================================================
+def _unknown_attribute_message(res: dict, logical_id: str, attr: str) -> str:
+ # Verbatim what CloudFormation reports in the stack event that starts the
+ # rollback (measured on a real account against AWS::SQS::Queue).
+ rtype = res.get("ResourceType") or logical_id
+ return f"Requested attribute {attr} does not exist in schema for {rtype}"
+
+
def _resolve_refs(value, resources, params, conditions, mappings,
stack_name, stack_id):
"""Recursively resolve CloudFormation intrinsic functions."""
@@ -356,8 +432,14 @@ def _resolve_refs(value, resources, params, conditions, mappings,
attrs = res.get("Attributes", {})
if attr in attrs:
return attrs[attr]
- # Fallback: try PhysicalResourceId
- return res.get("PhysicalResourceId", "")
+ if "PhysicalResourceId" in res:
+ # The resource exists and does not expose the attribute. Real
+ # CloudFormation fails the operation here (the stack rolls back);
+ # returning the physical id instead handed callers a silently wrong
+ # value.
+ raise ValueError(_unknown_attribute_message(res, logical_id, attr))
+ # Not provisioned yet (change-set diff): nothing to resolve against.
+ return ""
# --- Fn::Join ---
if "Fn::Join" in value:
@@ -412,7 +494,10 @@ def _resolve_refs(value, resources, params, conditions, mappings,
attrs = res.get("Attributes", {})
if parts[1] in attrs:
return str(attrs[parts[1]])
- return str(res.get("PhysicalResourceId", var))
+ if "PhysicalResourceId" in res:
+ raise ValueError(
+ _unknown_attribute_message(res, parts[0], parts[1]))
+ return var
# Resource physical ID
if var in resources and "PhysicalResourceId" in resources[var]:
return str(resources[var]["PhysicalResourceId"])
diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.py
index 74edba3b..91e76049 100644
--- a/ministack/services/cloudformation/handlers.py
+++ b/ministack/services/cloudformation/handlers.py
@@ -20,6 +20,7 @@ from .engine import (
_evaluate_conditions,
_parse_template,
_resolve_parameters,
+ validate_template_support,
)
from .helpers import _error, _esc, _extract_members, _extract_stack_status_filters, _p, _resolve_template, _xml
from .stacks import (
@@ -70,6 +71,12 @@ def _create_stack(params):
except ValueError as exc:
return _error("ValidationError", str(exc))
+ conditions = _evaluate_conditions(template, param_values)
+ try:
+ validate_template_support(template, conditions)
+ except ValueError as exc:
+ return _error("ValidationError", str(exc))
+
stack_id = (
f"arn:aws:cloudformation:{get_region()}:{get_account_id()}:"
f"stack/{stack_name}/{new_uuid()}"
@@ -99,7 +106,7 @@ def _create_stack(params):
"_template": template,
"_template_body": template_body,
"_resolved_params": param_values,
- "_conditions": _evaluate_conditions(template, param_values),
+ "_conditions": conditions,
}
_stacks[stack_name] = stack
_stack_events[stack_id] = []
@@ -534,6 +541,12 @@ def _update_stack(params):
except ValueError as exc:
return _error("ValidationError", str(exc))
+ try:
+ validate_template_support(
+ template, _evaluate_conditions(template, param_values))
+ except ValueError as exc:
+ return _error("ValidationError", str(exc))
+
# Save previous state for rollback
previous_stack = {
"_resources": copy.deepcopy(stack.get("_resources", {})),
@@ -595,6 +608,17 @@ def _validate_template(params):
if "Resources" not in template:
return _error("ValidationError",
"Template format error: At least one Resources member must be defined.")
+ try:
+ conditions = _evaluate_conditions(
+ template, _resolve_parameters(template, []))
+ except Exception:
+ # Parameters without defaults: validate every resource, conditions
+ # unknown.
+ conditions = {}
+ try:
+ validate_template_support(template, conditions)
+ except ValueError as exc:
+ return _error("ValidationError", str(exc))
description = template.get("Description", "")
param_defs = template.get("Parameters", {})
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 537086b1..b34ae943 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -328,7 +328,9 @@ def _provision_resource(resource_type: str, logical_id: str, props: dict,
return _custom_resource_create(logical_id, props, stack_name, resource_type)
# CloudFormation internal types are no-ops
if resource_type.startswith("AWS::CloudFormation::"):
- logger.info("CloudFormation internal type %s for %s -- noop", resource_type, logical_id)
+ logger.warning(
+ "CloudFormation type %s (%s) has no provisioner -- recorded as a "
+ "no-op placeholder, nothing is created", resource_type, logical_id)
noop_id = f"{stack_name}-{logical_id}-noop-{new_uuid()[:8]}"
return noop_id, {}
raise ValueError(f"Unsupported resource type: {resource_type}")
diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.py
index f1107e95..047c2b09 100644
--- a/ministack/services/cloudformation/stacks.py
+++ b/ministack/services/cloudformation/stacks.py
@@ -84,6 +84,46 @@ def _add_event(stack_id, stack_name, logical_id, resource_type, status,
# Stack Deploy / Delete / Update Logic
# ===========================================================================
+def _resolve_stack_outputs(outputs_defs, conditions, resources, param_values,
+ mappings, stack_name, stack_id):
+ """Resolve the Outputs section against the provisioned resources.
+
+ Returns ``(outputs, exports)``. Nothing is written to the export table here,
+ so an output that fails to resolve leaves no half-registered exports behind.
+ """
+ resolved_outputs = []
+ exports = {}
+ for out_name, out_def in outputs_defs.items():
+ cond = out_def.get("Condition")
+ if cond and not conditions.get(cond, True):
+ continue
+ out_value = _resolve_refs(
+ copy.deepcopy(out_def.get("Value", "")),
+ resources, param_values, conditions,
+ mappings, stack_name, stack_id
+ )
+ output = {
+ "OutputKey": out_name,
+ "OutputValue": str(out_value),
+ "Description": out_def.get("Description", ""),
+ }
+ export_def = out_def.get("Export", {})
+ if export_def:
+ export_name = _resolve_refs(
+ copy.deepcopy(export_def.get("Name", "")),
+ resources, param_values, conditions,
+ mappings, stack_name, stack_id
+ )
+ output["ExportName"] = str(export_name)
+ exports[str(export_name)] = {
+ "StackId": stack_id,
+ "Name": str(export_name),
+ "Value": str(out_value),
+ }
+ resolved_outputs.append(output)
+ return resolved_outputs, exports
+
+
async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
param_values: dict, disable_rollback: bool,
tags: list, is_update: bool = False,
@@ -229,6 +269,25 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
await asyncio.sleep(0)
+ resolved_outputs: list = []
+ new_exports: dict = {}
+ if not failed:
+ try:
+ resolved_outputs, new_exports = _resolve_stack_outputs(
+ outputs_defs, conditions, provisioned_resources, param_values,
+ mappings, stack_name, stack_id)
+ except Exception as exc:
+ # An output that cannot be resolved -- typically Fn::GetAtt to an
+ # attribute the resource does not expose -- fails the operation
+ # after every resource was created. Real CloudFormation rolls back
+ # at exactly this point, with the resolution error as the reason.
+ logger.error("Failed to resolve outputs of %s: %s", stack_name, exc)
+ failed = True
+ fail_reason = str(exc)
+ _add_event(stack_id, stack_name, stack_name,
+ "AWS::CloudFormation::Stack", f"{status_prefix}_FAILED",
+ fail_reason, stack_id)
+
if failed:
if disable_rollback:
stack["StackStatus"] = f"{status_prefix}_FAILED"
@@ -309,41 +368,11 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
"Rollback complete", stack_id)
return
- # Success: resolve outputs
+ # Success: publish outputs and exports
stack["_resources"] = provisioned_resources
stack["_template"] = template
stack["_resolved_params"] = param_values
-
- resolved_outputs = []
- for out_name, out_def in outputs_defs.items():
- cond = out_def.get("Condition")
- if cond and not conditions.get(cond, True):
- continue
- out_value = _resolve_refs(
- copy.deepcopy(out_def.get("Value", "")),
- provisioned_resources, param_values, conditions,
- mappings, stack_name, stack_id
- )
- output = {
- "OutputKey": out_name,
- "OutputValue": str(out_value),
- "Description": out_def.get("Description", ""),
- }
- export_def = out_def.get("Export", {})
- if export_def:
- export_name = _resolve_refs(
- copy.deepcopy(export_def.get("Name", "")),
- provisioned_resources, param_values, conditions,
- mappings, stack_name, stack_id
- )
- output["ExportName"] = str(export_name)
- _exports[str(export_name)] = {
- "StackId": stack_id,
- "Name": str(export_name),
- "Value": str(out_value),
- }
- resolved_outputs.append(output)
-
+ _exports.update(new_exports)
stack["Outputs"] = resolved_outputs
stack["StackStatus"] = f"{status_prefix}_COMPLETE"
_add_event(stack_id, stack_name, stack_name,
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 96f5641e..124189d7 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -37,6 +37,18 @@ def _cfn_iceberg_json(path):
return json.loads(resp.read().decode("utf-8") or "{}")
+# A resource that is accepted by the template pre-flight but fails when
+# provisioned: a custom resource whose Lambda does not exist. Tests that need a
+# runtime failure use this; unrecognized types are rejected before any
+# resource is touched (see test_cfn_unrecognized_resource_type_rejected_up_front).
+_FAILING_RESOURCE = {
+ "Type": "AWS::CloudFormation::CustomResource",
+ "Properties": {
+ "ServiceToken": "arn:aws:lambda:us-east-1:000000000000:function:cfn-does-not-exist",
+ },
+}
+
+
def _wait_stack(cfn, name, timeout=30):
"""Poll until stack reaches terminal status.
@@ -1294,8 +1306,10 @@ def test_cfn_change_set_status_execution_and_lifecycle(cfn):
does not outlive its stack (#1418)."""
S = "cfn-1418"
CS = "cdk-deploy-change-set"
- bad = json.dumps({"Resources": {"X": {
- "Type": "AWS::FakeService::Thing", "Properties": {}}}})
+ # Unrecognized types are rejected at CreateChangeSet time now (like AWS),
+ # so a custom resource whose Lambda does not exist provides the
+ # execution-time failure this test is about.
+ bad = json.dumps({"Resources": {"X": _FAILING_RESOURCE}})
ok = json.dumps({"Resources": {"P": {"Type": "AWS::SSM::Parameter",
"Properties": {"Name": "/cfn-1418/p", "Type": "String",
"Value": "v"}}}})
@@ -2028,10 +2042,7 @@ def test_cfn_rollback_on_failure(cfn, s3):
"Type": "AWS::S3::Bucket",
"Properties": {"BucketName": "cfn-t15-rollback"},
},
- "Bad": {
- "Type": "AWS::Fake::Nope",
- "Properties": {},
- },
+ "Bad": _FAILING_RESOURCE,
},
}
cfn.create_stack(
@@ -2121,10 +2132,7 @@ def test_cfn_update_rollback_on_failure(cfn, s3):
"Type": "AWS::S3::Bucket",
"Properties": {"BucketName": "cfn-t18-orig"},
},
- "Bad": {
- "Type": "AWS::Fake::Nope",
- "Properties": {},
- },
+ "Bad": _FAILING_RESOURCE,
},
}
cfn.update_stack(StackName="cfn-t18", TemplateBody=json.dumps(template_v2))
@@ -10272,13 +10280,10 @@ def test_cfn_create_rollback_delete_failure_lands_rollback_failed(cfn, lam):
"ServiceToken": f"arn:aws:lambda:us-east-1:000000000000:function:{fn}",
},
},
- # Provisioned after CR; its unsupported type fails the create and
- # triggers the rollback that has to delete CR again.
- "Bad": {
- "Type": "AWS::Unsupported::DoesNotExist",
- "DependsOn": "CR",
- "Properties": {},
- },
+ # Provisioned after CR; its create fails (custom resource whose
+ # Lambda does not exist) and triggers the rollback that has to
+ # delete CR again.
+ "Bad": {**_FAILING_RESOURCE, "DependsOn": "CR"},
},
}
try:
@@ -10342,9 +10347,8 @@ def test_cfn_update_rollback_delete_failure_lands_update_rollback_failed(cfn, la
},
}
updated["Resources"]["Bad"] = {
- "Type": "AWS::Unsupported::DoesNotExist",
+ **_FAILING_RESOURCE,
"DependsOn": "CR",
- "Properties": {},
}
try:
cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(base))
@@ -11148,6 +11152,157 @@ def test_cfn_cognito_user_pool_enabled_mfas(cfn, cognito_idp):
_wait_stack(cfn, "cfn-enabled-mfas")
+# -- Template pre-flight and Fn::GetAtt strictness ---------------------------
+# Measured on a real account (eu-central-1, 2026-09-02): CreateStack,
+# UpdateStack, CreateChangeSet and ValidateTemplate reject an unrecognized
+# resource type synchronously with the exact message below and create no stack;
+# a Fn::GetAtt to an attribute the type does not have passes validation, the
+# resource is created, then the stack rolls back with
+# "Requested attribute X does not exist in schema for T".
+
+_UNRECOGNIZED_MESSAGE = (
+ "Template format error: Unrecognized resource types: [AWS::Baz::Qux, AWS::Foo::Bar]"
+)
+
+
+def _bad_types_template():
+ return json.dumps({"Resources": {
+ "Queue": {"Type": "AWS::SQS::Queue"},
+ "Thing": {"Type": "AWS::Foo::Bar", "Properties": {}},
+ "Other": {"Type": "AWS::Baz::Qux", "Properties": {}},
+ }})
+
+
+def test_cfn_unrecognized_resource_type_rejected_up_front(cfn, sqs):
+ """No stack, no change set and no resource exist after the rejections."""
+ bad = _bad_types_template()
+ name = "cfn-preflight-types"
+ for call in (
+ lambda: cfn.validate_template(TemplateBody=bad),
+ lambda: cfn.create_stack(StackName=name, TemplateBody=bad),
+ lambda: cfn.create_change_set(StackName=name, ChangeSetName="cs",
+ ChangeSetType="CREATE", TemplateBody=bad),
+ ):
+ with pytest.raises(ClientError) as exc:
+ call()
+ assert exc.value.response["Error"]["Code"] == "ValidationError"
+ assert exc.value.response["Error"]["Message"] == _UNRECOGNIZED_MESSAGE
+
+ with pytest.raises(ClientError) as exc:
+ cfn.describe_stacks(StackName=name)
+ assert "does not exist" in str(exc.value)
+ assert not [s for s in cfn.list_stacks()["StackSummaries"]
+ if s["StackName"] == name]
+ # The valid sibling was never provisioned.
+ assert not [u for u in sqs.list_queues().get("QueueUrls", [])
+ if "cfn-preflight-types" in u]
+
+
+def test_cfn_unrecognized_resource_type_rejected_on_update(cfn, sqs):
+ """An update carrying an unrecognized type is refused without touching the
+ stack: status and resources stay as they were."""
+ name = "cfn-preflight-update"
+ good = json.dumps({"Resources": {"Queue": {"Type": "AWS::SQS::Queue"}}})
+ cfn.create_stack(StackName=name, TemplateBody=good)
+ try:
+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
+ with pytest.raises(ClientError) as exc:
+ cfn.update_stack(StackName=name, TemplateBody=_bad_types_template())
+ assert exc.value.response["Error"]["Message"] == _UNRECOGNIZED_MESSAGE
+ stack = cfn.describe_stacks(StackName=name)["Stacks"][0]
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+ assert [r["LogicalResourceId"] for r in
+ cfn.list_stack_resources(StackName=name)["StackResourceSummaries"]] == ["Queue"]
+ finally:
+ cfn.delete_stack(StackName=name)
+ _wait_stack(cfn, name)
+
+
+def test_cfn_unrecognized_type_behind_false_condition_is_fine(cfn):
+ """Condition-false resources are not provisioned, so their type is not
+ checked either (same rule as before)."""
+ name = "cfn-preflight-cond"
+ tpl = json.dumps({
+ "Conditions": {"Never": {"Fn::Equals": ["a", "b"]}},
+ "Resources": {
+ "Queue": {"Type": "AWS::SQS::Queue"},
+ "Thing": {"Type": "AWS::Foo::Bar", "Condition": "Never", "Properties": {}},
+ },
+ })
+ cfn.validate_template(TemplateBody=tpl)
+ cfn.create_stack(StackName=name, TemplateBody=tpl)
+ try:
+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
+ finally:
+ cfn.delete_stack(StackName=name)
+ _wait_stack(cfn, name)
+
+
+def test_cfn_getatt_unknown_attribute_fails_the_stack(cfn, sqs):
+ """Fn::GetAtt to an attribute the resource does not expose is no longer
+ answered with the physical id: the stack fails and rolls back with the
+ reason CloudFormation reports."""
+ name = "cfn-preflight-getatt"
+ tpl = json.dumps({
+ "Resources": {"Queue": {"Type": "AWS::SQS::Queue",
+ "Properties": {"QueueName": "cfn-preflight-getatt-q"}}},
+ "Outputs": {"X": {"Value": {"Fn::GetAtt": ["Queue", "NoSuchAttr"]}}},
+ })
+ cfn.validate_template(TemplateBody=tpl) # passes validation, as on AWS
+ cfn.create_stack(StackName=name, TemplateBody=tpl)
+ try:
+ assert _wait_stack(cfn, name)["StackStatus"] == "ROLLBACK_COMPLETE"
+ reasons = [e.get("ResourceStatusReason", "") for e in
+ cfn.describe_stack_events(StackName=name)["StackEvents"]]
+ assert any("Requested attribute NoSuchAttr does not exist in schema "
+ "for AWS::SQS::Queue" in r for r in reasons), reasons
+ with pytest.raises(ClientError):
+ sqs.get_queue_url(QueueName="cfn-preflight-getatt-q")
+ assert not cfn.list_exports()["Exports"] or all(
+ e["ExportingStackId"] != cfn.describe_stacks(StackName=name)["Stacks"][0]["StackId"]
+ for e in cfn.list_exports()["Exports"])
+ finally:
+ cfn.delete_stack(StackName=name)
+ _wait_stack(cfn, name)
+
+
+def test_cfn_getatt_unknown_attribute_in_properties_fails_the_resource(cfn, sqs):
+ """The same rule inside Properties: the consumer fails, the stack rolls back
+ and the producer created before it is removed again."""
+ name = "cfn-preflight-getatt-prop"
+ tpl = json.dumps({"Resources": {
+ "A": {"Type": "AWS::SQS::Queue", "Properties": {"QueueName": "cfn-preflight-gp-a"}},
+ "B": {"Type": "AWS::SNS::Topic",
+ "Properties": {"DisplayName": {"Fn::GetAtt": ["A", "Nope"]}}},
+ }})
+ cfn.create_stack(StackName=name, TemplateBody=tpl)
+ try:
+ assert _wait_stack(cfn, name)["StackStatus"] == "ROLLBACK_COMPLETE"
+ events = cfn.describe_stack_events(StackName=name)["StackEvents"]
+ b = [e for e in events if e["LogicalResourceId"] == "B"
+ and e["ResourceStatus"] == "CREATE_FAILED"]
+ assert b and "Requested attribute Nope does not exist in schema for AWS::SQS::Queue" in b[0]["ResourceStatusReason"]
+ with pytest.raises(ClientError):
+ sqs.get_queue_url(QueueName="cfn-preflight-gp-a")
+ finally:
+ cfn.delete_stack(StackName=name)
+ _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."""
+ tpl = json.dumps({"Resources": {"P": {
+ "Type": "AWS::SSM::Parameter",
+ "Properties": {"Type": "String", "Name": "/cfn-preflight/dyn",
+ "Value": "{{resolve:secretsmanager:my-secret:SecretString: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
+ 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