Skip to content

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

feat: CloudFormation service — full stack lifecycle, 10 resource types, 35 tests (#48)

Sam Fakhreddine2c09c7a8aa61
diff --git a/.gitignore b/.gitignore
index ce335615..bb3be9bf 100644
--- a/.gitignore
+++ b/.gitignore
@@ -50,3 +50,14 @@ data/
# Logs
*.log
+
+# Research artifacts
+localstack/
+
+# Lock files
+uv.lock
+
+# WFC plans (local)
+plans/
+.hypothesis/
+.claude/
diff --git a/Dockerfile b/Dockerfile
index fcb6a37f..8736cc3d 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -13,7 +13,8 @@ RUN pip install --no-cache-dir --upgrade pip && \
pip install --no-cache-dir \
uvicorn==0.30.6 \
"cbor2>=5.4.0" \
- "docker>=7.0.0"
+ "docker>=7.0.0" \
+ "pyyaml>=6.0"
COPY ministack/ ministack/
diff --git a/README.md b/README.md
index d001b3ac..4af64ddf 100644
--- a/README.md
+++ b/README.md
@@ -21,7 +21,7 @@
LocalStack recently moved its core services behind a paid plan. If you relied on LocalStack Community for local development and CI/CD pipelines, MiniStack is your free alternative.
-- **30 AWS services** emulated on a single port (4566)
+- **31 AWS services** emulated on a single port (4566)
- **Drop-in compatible** — works with `boto3`, AWS CLI, Terraform, CDK, Pulumi, any SDK
- **Real infrastructure** — RDS spins up actual Postgres/MySQL containers, ElastiCache spins up real Redis, Athena runs real SQL via DuckDB, ECS runs real Docker containers
- **Tiny footprint** — ~150MB image, ~30MB RAM at idle vs LocalStack's ~1GB image and ~500MB RAM
@@ -225,6 +225,40 @@ subnet = ec2.create_subnet(
| **API Gateway v1** | CreateRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi, CreateResource, GetResource, GetResources, UpdateResource, DeleteResource, PutMethod, GetMethod, DeleteMethod, UpdateMethod, PutMethodResponse, GetMethodResponse, DeleteMethodResponse, PutIntegration, GetIntegration, DeleteIntegration, UpdateIntegration, PutIntegrationResponse, GetIntegrationResponse, DeleteIntegrationResponse, CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, CreateModel, GetModel, GetModels, DeleteModel, CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey, CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, CreateUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey, CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName, CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping, TagResource, UntagResource, GetTags | REST API (v1) protocol; Lambda proxy format 1.0 (AWS_PROXY), HTTP proxy (HTTP_PROXY), MOCK integration; data plane via `{apiId}.execute-api.localhost`; resource tree with `{param}` and `{proxy+}` path matching; JSON Patch for all PATCH operations; state persistence |
| **ELBv2 / ALB** | CreateLoadBalancer, DescribeLoadBalancers, DeleteLoadBalancer, DescribeLoadBalancerAttributes, ModifyLoadBalancerAttributes, CreateTargetGroup, DescribeTargetGroups, ModifyTargetGroup, DeleteTargetGroup, DescribeTargetGroupAttributes, ModifyTargetGroupAttributes, CreateListener, DescribeListeners, ModifyListener, DeleteListener, CreateRule, DescribeRules, ModifyRule, DeleteRule, SetRulePriorities, RegisterTargets, DeregisterTargets, DescribeTargetHealth, AddTags, RemoveTags, DescribeTags | Control plane + data plane; ALB→Lambda live traffic routing; `path-pattern`, `host-header`, `http-method`, `query-string`, `http-header` rule conditions; `forward`, `redirect`, `fixed-response` actions; data plane via `{lb-name}.alb.localhost` Host header or `/_alb/{lb-name}/` path prefix |
+### CloudFormation
+
+| Feature | Details |
+|---------|---------|
+| **Stack Operations** | CreateStack, UpdateStack, DeleteStack, DescribeStacks, ListStacks, DescribeStackEvents, DescribeStackResource, DescribeStackResources, GetTemplate, ValidateTemplate, GetTemplateSummary |
+| **Change Sets** | CreateChangeSet, DescribeChangeSet, ExecuteChangeSet, DeleteChangeSet, ListChangeSets |
+| **Exports** | ListExports — cross-stack references via `Fn::ImportValue` |
+| **Template Formats** | JSON and YAML (including `!Ref`, `!Sub`, `!GetAtt` shorthand tags) |
+| **Intrinsic Functions** | Ref, Fn::GetAtt, Fn::Join, Fn::Sub (both forms), Fn::Select, Fn::Split, Fn::If, Fn::Equals, Fn::And, Fn::Or, Fn::Not, Fn::Base64, Fn::FindInMap, Fn::ImportValue, Fn::GetAZs, Fn::Cidr |
+| **Pseudo-Parameters** | AWS::StackName, AWS::StackId, AWS::Region, AWS::AccountId, AWS::URLSuffix, AWS::Partition, AWS::NoValue |
+| **Parameters** | Default values, AllowedValues validation, NoEcho masking, String/Number/CommaDelimitedList types |
+| **Conditions** | Fn::Equals, Fn::And, Fn::Or, Fn::Not — conditional resource creation |
+| **Rollback** | Configurable via `DisableRollback` — on failure, previously created resources are cleaned up in reverse dependency order |
+| **Async Status** | Stacks deploy asynchronously (`CREATE_IN_PROGRESS` → `CREATE_COMPLETE`) — poll with DescribeStacks |
+
+**Supported Resource Types:**
+
+| Resource Type | Ref Returns | GetAtt |
+|---------------|-------------|--------|
+| `AWS::S3::Bucket` | Bucket name | Arn, DomainName, RegionalDomainName, WebsiteURL |
+| `AWS::SQS::Queue` | Queue URL | Arn, QueueName, QueueUrl |
+| `AWS::SNS::Topic` | Topic ARN | TopicArn, TopicName |
+| `AWS::SNS::Subscription` | Subscription ARN | — |
+| `AWS::DynamoDB::Table` | Table name | Arn, StreamArn |
+| `AWS::Lambda::Function` | Function name | Arn |
+| `AWS::IAM::Role` | Role name | Arn, RoleId |
+| `AWS::IAM::Policy` | Policy ARN | — |
+| `AWS::IAM::InstanceProfile` | Profile name | Arn |
+| `AWS::SSM::Parameter` | Parameter name | Type, Value |
+| `AWS::Logs::LogGroup` | Log group name | Arn |
+| `AWS::Events::Rule` | Rule name | Arn |
+
+Unsupported resource types fail with `CREATE_FAILED` (or `ROLLBACK_COMPLETE` if rollback is enabled), so templates with unsupported types won't silently succeed.
+
### Infrastructure Services (with real Docker execution)
| Service | Operations | Real Execution |
@@ -588,7 +622,7 @@ config:
| **ACM** | ✅ | ✅ | ✅ |
| **SES v2** | ✅ | ✅ | ✅ |
| **WAF v2** | ✅ | Paid | ✅ |
-| CloudFormation | ❌ | partial | ✅ |
+| **CloudFormation** | **partial** | partial | ✅ |
| Cost | **Free** | Was free, now paid | $35+/mo |
| Docker image size | ~150MB | ~1GB | ~1GB |
| Memory at idle | ~30MB | ~500MB | ~500MB |
diff --git a/ministack/app.py b/ministack/app.py
index 2c2795aa..8e3f9db4 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -31,6 +31,7 @@ from ministack.services import (
apigateway,
apigateway_v1,
athena,
+ cloudformation,
cloudwatch,
cloudwatch_logs,
cognito,
@@ -70,6 +71,7 @@ logger = logging.getLogger("ministack")
SERVICE_HANDLERS = {
"s3": s3.handle_request,
"sqs": sqs.handle_request,
+ "cloudformation": cloudformation.handle_request,
"sns": sns.handle_request,
"dynamodb": dynamodb.handle_request,
"lambda": lambda_svc.handle_request,
@@ -151,7 +153,7 @@ BANNER = r"""
Services: S3, SQS, SNS, DynamoDB, Lambda, IAM, STS, SecretsManager, CloudWatch Logs,
SSM, EventBridge, Kinesis, CloudWatch, SES, SES v2, ACM, WAF v2, Step Functions,
ECS, RDS, ElastiCache, Glue, Athena, API Gateway, Firehose, Route53,
- Cognito, EC2, EMR, EBS, EFS, ALB/ELBv2
+ Cognito, EC2, EMR, EBS, EFS, ALB/ELBv2, CloudFormation
"""
@@ -327,7 +329,7 @@ async def app(scope, receive, send):
_non_s3_hosts = {"s3", "sqs", "sns", "dynamodb", "lambda", "iam", "sts",
"secretsmanager", "logs", "ssm", "events", "kinesis",
"monitoring", "ses", "states", "ecs", "rds", "elasticache",
- "glue", "athena", "apigateway"}
+ "glue", "athena", "apigateway", "cloudformation"}
if bucket not in _non_s3_hosts:
vhost_path = "/" + bucket + path if path != "/" else "/" + bucket + "/"
try:
@@ -501,6 +503,7 @@ def _reset_all_state():
(ses_v2, ses_v2.reset),
(waf, waf.reset),
(efs, efs.reset),
+ (cloudformation, cloudformation.reset),
]:
try:
fn()
diff --git a/ministack/core/router.py b/ministack/core/router.py
index fa3982d7..aca87a0b 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -145,6 +145,9 @@ SERVICE_PATTERNS = {
"host_patterns": [r"wafv2\."],
"credential_scope": "wafv2",
},
+ "cloudformation": {
+ "host_patterns": [r"cloudformation\."],
+ },
}
@@ -192,6 +195,7 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
"elasticmapreduce": "elasticmapreduce",
"elasticloadbalancing": "elasticloadbalancing",
"elasticfilesystem": "elasticfilesystem",
+ "cloudformation": "cloudformation",
}
if svc_name in scope_map:
return scope_map[svc_name]
@@ -361,6 +365,21 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
"ModifyVolume": "ec2", "DescribeVolumesModifications": "ec2",
"EnableVolumeIO": "ec2", "ModifyVolumeAttribute": "ec2",
"DescribeVolumeAttribute": "ec2",
+ # CloudFormation actions
+ "CreateStack": "cloudformation", "DescribeStacks": "cloudformation",
+ "UpdateStack": "cloudformation", "DeleteStack": "cloudformation",
+ "ListStacks": "cloudformation",
+ "DescribeStackEvents": "cloudformation",
+ "DescribeStackResource": "cloudformation", "DescribeStackResources": "cloudformation",
+ "ListStackResources": "cloudformation",
+ "GetTemplate": "cloudformation", "GetTemplateSummary": "cloudformation",
+ "ValidateTemplate": "cloudformation",
+ "CreateChangeSet": "cloudformation", "DescribeChangeSet": "cloudformation",
+ "ExecuteChangeSet": "cloudformation", "DeleteChangeSet": "cloudformation",
+ "ListChangeSets": "cloudformation",
+ "ListExports": "cloudformation", "ListImports": "cloudformation",
+ "UpdateTerminationProtection": "cloudformation",
+ "SetStackPolicy": "cloudformation", "GetStackPolicy": "cloudformation",
# EBS Snapshots
"CreateSnapshot": "ec2", "DeleteSnapshot": "ec2", "DescribeSnapshots": "ec2",
"CopySnapshot": "ec2", "ModifySnapshotAttribute": "ec2",
diff --git a/ministack/services/cloudformation/__init__.py b/ministack/services/cloudformation/__init__.py
new file mode 100644
index 00000000..789e20f2
--- /dev/null
+++ b/ministack/services/cloudformation/__init__.py
@@ -0,0 +1,64 @@
+"""
+CloudFormation Service Emulator -- AWS-compatible.
+Supports: CreateStack, UpdateStack, DeleteStack, DescribeStacks, ListStacks,
+ DescribeStackEvents, DescribeStackResource, DescribeStackResources,
+ GetTemplate, ValidateTemplate, ListExports,
+ CreateChangeSet, DescribeChangeSet, ExecuteChangeSet,
+ DeleteChangeSet, ListChangeSets,
+ GetTemplateSummary.
+Uses Query API (Action=...) with form-encoded body.
+"""
+
+import logging
+from urllib.parse import parse_qs
+
+logger = logging.getLogger("cloudformation")
+
+ACCOUNT_ID = "000000000000"
+REGION = "us-east-1"
+
+# In-memory state (shared across all submodules)
+_stacks: dict = {} # stack_name -> stack dict
+_stack_events: dict = {} # stack_id -> [event list]
+_exports: dict = {} # export_name -> {StackId, Name, Value}
+_change_sets: dict = {} # cs_id -> change set dict
+
+# Re-exports for compatibility
+from .engine import ( # noqa: E402
+ _parse_template,
+ _resolve_parameters,
+ _evaluate_conditions,
+ _resolve_refs,
+ _extract_deps,
+ _topological_sort,
+ _NO_VALUE,
+)
+
+from .helpers import _p # noqa: E402
+
+
+async def handle_request(method: str, path: str, headers: dict,
+ body: bytes, query_params: dict) -> tuple:
+ params = dict(query_params)
+ if method == "POST" and body:
+ form_params = parse_qs(body.decode("utf-8", errors="replace"))
+ for k, v in form_params.items():
+ params[k] = v
+
+ action = _p(params, "Action")
+ handler = _ACTION_HANDLERS.get(action)
+ if not handler:
+ from .helpers import _error
+ return _error("InvalidAction", f"Unknown action: {action}", 400)
+ return handler(params)
+
+
+def reset():
+ _stacks.clear()
+ _stack_events.clear()
+ _exports.clear()
+ _change_sets.clear()
+
+
+# Must be last — handlers imports from this module
+from .handlers import _ACTION_HANDLERS, _validate_template # noqa: E402
diff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.py
new file mode 100644
index 00000000..878dc2f6
--- /dev/null
+++ b/ministack/services/cloudformation/changesets.py
@@ -0,0 +1,324 @@
+"""
+CloudFormation change set handlers — Create, Describe, Execute, Delete, List change sets.
+"""
+
+import asyncio
+import copy
+import json
+import logging
+
+from ministack.core.responses import new_uuid, now_iso
+
+from .engine import (
+ _evaluate_conditions, _parse_template, _resolve_parameters,
+ _resolve_refs, _NO_VALUE,
+)
+from .stacks import _add_event, _deploy_stack_async, _diff_resources
+from .provisioners import ACCOUNT_ID, REGION
+from .helpers import _xml, _error, _p, _esc, _extract_members, CFN_NS
+
+logger = logging.getLogger("cloudformation")
+
+
+def _find_change_set(cs_name, stack_name=""):
+ """Look up a change set by ID or by name+stack. Returns (cs_id, cs_dict) or (None, None)."""
+ from ministack.services.cloudformation import _change_sets
+ if cs_name in _change_sets:
+ return cs_name, _change_sets[cs_name]
+ for cid, c in _change_sets.items():
+ if c["ChangeSetName"] == cs_name:
+ if not stack_name or c["StackName"] == stack_name:
+ return cid, c
+ return None, None
+
+
+# --- CreateChangeSet ---
+
+def _create_change_set(params):
+ from ministack.services.cloudformation import _stacks, _stack_events, _change_sets
+ stack_name = _p(params, "StackName")
+ cs_name = _p(params, "ChangeSetName")
+ cs_type = _p(params, "ChangeSetType", "UPDATE")
+
+ if not stack_name:
+ return _error("ValidationError", "StackName is required")
+ if not cs_name:
+ return _error("ValidationError", "ChangeSetName is required")
+
+ template_body = _p(params, "TemplateBody")
+ if _p(params, "TemplateURL"):
+ return _error("ValidationError",
+ "TemplateURL is not supported; use TemplateBody")
+
+ provided_params = _extract_members(params, "Parameters")
+ tags = _extract_members(params, "Tags")
+
+ stack = _stacks.get(stack_name)
+
+ if cs_type == "CREATE":
+ if stack and stack.get("StackStatus") not in (
+ "DELETE_COMPLETE", "ROLLBACK_COMPLETE", "REVIEW_IN_PROGRESS"
+ ):
+ return _error("AlreadyExistsException",
+ f"Stack [{stack_name}] already exists")
+ if not template_body:
+ return _error("ValidationError", "TemplateBody is required")
+
+ # Create a placeholder stack in REVIEW_IN_PROGRESS
+ stack_id = (
+ f"arn:aws:cloudformation:{REGION}:{ACCOUNT_ID}:"
+ f"stack/{stack_name}/{new_uuid()}"
+ )
+ stack = {
+ "StackName": stack_name,
+ "StackId": stack_id,
+ "StackStatus": "REVIEW_IN_PROGRESS",
+ "StackStatusReason": "",
+ "CreationTime": now_iso(),
+ "LastUpdatedTime": now_iso(),
+ "Description": "",
+ "Parameters": [],
+ "Tags": tags,
+ "Outputs": [],
+ "DisableRollback": False,
+ "_resources": {},
+ "_template": {},
+ "_template_body": "",
+ "_resolved_params": {},
+ "_conditions": {},
+ }
+ _stacks[stack_name] = stack
+ _stack_events[stack_id] = []
+ else:
+ if not stack:
+ return _error("ValidationError",
+ f"Stack [{stack_name}] does not exist")
+ stack_id = stack["StackId"]
+ if not template_body:
+ template_body = stack.get("_template_body", "{}")
+
+ try:
+ template = _parse_template(template_body)
+ except Exception as e:
+ return _error("ValidationError", f"Template format error: {e}")
+
+ try:
+ param_values = _resolve_parameters(template, provided_params)
+ except ValueError as exc:
+ return _error("ValidationError", str(exc))
+
+ # Compute changes
+ old_template = stack.get("_template", {}) if cs_type == "UPDATE" else {}
+ changes = _diff_resources(old_template, template)
+
+ cs_id = (
+ f"arn:aws:cloudformation:{REGION}:{ACCOUNT_ID}:"
+ f"changeSet/{cs_name}/{new_uuid()}"
+ )
+
+ change_set = {
+ "ChangeSetId": cs_id,
+ "ChangeSetName": cs_name,
+ "StackId": stack_id,
+ "StackName": stack_name,
+ "Status": "CREATE_COMPLETE",
+ "ExecutionStatus": "AVAILABLE",
+ "CreationTime": now_iso(),
+ "Description": _p(params, "Description", ""),
+ "ChangeSetType": cs_type,
+ "Changes": changes,
+ "Parameters": [
+ {"ParameterKey": k, "ParameterValue": v["Value"]}
+ for k, v in param_values.items()
+ ],
+ "Tags": tags,
+ "_template": template,
+ "_template_body": template_body,
+ "_resolved_params": param_values,
+ }
+ _change_sets[cs_id] = change_set
+
+ return _xml(200, "CreateChangeSetResponse",
+ f"<CreateChangeSetResult>"
+ f"<Id>{cs_id}</Id>"
+ f"<StackId>{stack_id}</StackId>"
+ f"</CreateChangeSetResult>")
+
+
+# --- DescribeChangeSet ---
+
+def _describe_change_set(params):
+ cs_name = _p(params, "ChangeSetName")
+ stack_name = _p(params, "StackName")
+ _, cs = _find_change_set(cs_name, stack_name)
+ if not cs:
+ return _error("ChangeSetNotFoundException",
+ f"ChangeSet [{cs_name}] does not exist")
+
+ params_xml = ""
+ for p in cs.get("Parameters", []):
+ params_xml += (
+ "<member>"
+ f"<ParameterKey>{_esc(p['ParameterKey'])}</ParameterKey>"
+ f"<ParameterValue>{_esc(str(p['ParameterValue']))}</ParameterValue>"
+ "</member>"
+ )
+
+ changes_xml = ""
+ for ch in cs.get("Changes", []):
+ rc = ch.get("ResourceChange", {})
+ changes_xml += (
+ "<member><ResourceChange>"
+ f"<Action>{rc.get('Action', '')}</Action>"
+ f"<LogicalResourceId>{_esc(rc.get('LogicalResourceId', ''))}</LogicalResourceId>"
+ f"<ResourceType>{_esc(rc.get('ResourceType', ''))}</ResourceType>"
+ f"<Replacement>{rc.get('Replacement', '')}</Replacement>"
+ "</ResourceChange></member>"
+ )
+
+ tags_xml = ""
+ for t in cs.get("Tags", []):
+ tags_xml += (
+ "<member>"
+ f"<Key>{_esc(t.get('Key', ''))}</Key>"
+ f"<Value>{_esc(t.get('Value', ''))}</Value>"
+ "</member>"
+ )
+
+ inner = (
+ f"<ChangeSetId>{_esc(cs['ChangeSetId'])}</ChangeSetId>"
+ f"<ChangeSetName>{_esc(cs['ChangeSetName'])}</ChangeSetName>"
+ f"<StackId>{_esc(cs['StackId'])}</StackId>"
+ f"<StackName>{_esc(cs['StackName'])}</StackName>"
+ f"<Status>{cs['Status']}</Status>"
+ f"<ExecutionStatus>{cs['ExecutionStatus']}</ExecutionStatus>"
+ f"<CreationTime>{cs['CreationTime']}</CreationTime>"
+ f"<Description>{_esc(cs.get('Description', ''))}</Description>"
+ f"<ChangeSetType>{cs.get('ChangeSetType', '')}</ChangeSetType>"
+ f"<Parameters>{params_xml}</Parameters>"
+ f"<Changes>{changes_xml}</Changes>"
+ f"<Tags>{tags_xml}</Tags>"
+ )
+
+ return _xml(200, "DescribeChangeSetResponse",
+ f"<DescribeChangeSetResult>{inner}</DescribeChangeSetResult>")
+
+
+# --- ExecuteChangeSet ---
+
+def _execute_change_set(params):
+ from ministack.services.cloudformation import _stacks
+ cs_name = _p(params, "ChangeSetName")
+ stack_name = _p(params, "StackName")
+ _, cs = _find_change_set(cs_name, stack_name)
+ if not cs:
+ return _error("ChangeSetNotFoundException",
+ f"ChangeSet [{cs_name}] does not exist")
+
+ if cs["ExecutionStatus"] != "AVAILABLE":
+ return _error("InvalidChangeSetStatusException",
+ f"ChangeSet [{cs_name}] is in {cs['ExecutionStatus']} status")
+
+ cs["ExecutionStatus"] = "EXECUTE_IN_PROGRESS"
+ real_stack_name = cs["StackName"]
+ stack = _stacks.get(real_stack_name)
+ if not stack:
+ return _error("ValidationError",
+ f"Stack [{real_stack_name}] does not exist")
+
+ stack_id = stack["StackId"]
+ template = cs["_template"]
+ template_body = cs["_template_body"]
+ param_values = cs["_resolved_params"]
+ tags = cs.get("Tags", [])
+ cs_type = cs.get("ChangeSetType", "UPDATE")
+ is_update = cs_type == "UPDATE"
+
+ if is_update:
+ previous_stack = {
+ "_resources": copy.deepcopy(stack.get("_resources", {})),
+ "_template": copy.deepcopy(stack.get("_template", {})),
+ "_template_body": stack.get("_template_body", ""),
+ "_resolved_params": copy.deepcopy(stack.get("_resolved_params", {})),
+ "Outputs": copy.deepcopy(stack.get("Outputs", [])),
+ }
+ else:
+ previous_stack = None
+
+ status_prefix = "UPDATE" if is_update else "CREATE"
+ stack["StackStatus"] = f"{status_prefix}_IN_PROGRESS"
+ stack["LastUpdatedTime"] = now_iso()
+ stack["_template_body"] = template_body
+ if tags:
+ stack["Tags"] = tags
+ stack["Parameters"] = [
+ {"ParameterKey": k, "ParameterValue": v["Value"], "NoEcho": v["NoEcho"]}
+ for k, v in param_values.items()
+ ]
+ stack["_conditions"] = _evaluate_conditions(template, param_values)
+
+ _add_event(stack_id, real_stack_name, real_stack_name,
+ "AWS::CloudFormation::Stack", f"{status_prefix}_IN_PROGRESS",
+ physical_id=stack_id)
+
+ asyncio.ensure_future(
+ _deploy_stack_async(real_stack_name, stack_id, template,
+ param_values, False, tags,
+ is_update=is_update,
+ previous_stack=previous_stack)
+ )
+
+ cs["ExecutionStatus"] = "EXECUTE_COMPLETE"
+ cs["Status"] = "EXECUTE_COMPLETE"
+
+ return _xml(200, "ExecuteChangeSetResponse",
+ "<ExecuteChangeSetResult></ExecuteChangeSetResult>")
+
+
+# --- DeleteChangeSet ---
+
+def _delete_change_set(params):
+ from ministack.services.cloudformation import _change_sets
+ cs_name = _p(params, "ChangeSetName")
+ stack_name = _p(params, "StackName")
+ cs_id, cs = _find_change_set(cs_name, stack_name)
+ if not cs_id:
+ return _error("ChangeSetNotFoundException",
+ f"ChangeSet [{cs_name}] does not exist")
+ _change_sets.pop(cs_id, None)
+ return _xml(200, "DeleteChangeSetResponse", "")
+
+
+# --- ListChangeSets ---
+
+def _list_change_sets(params):
+ from ministack.services.cloudformation import _stacks, _change_sets
+ stack_name = _p(params, "StackName")
+ if not stack_name:
+ return _error("ValidationError", "StackName is required")
+
+ members = ""
+ for cs in _change_sets.values():
+ if cs["StackName"] != stack_name:
+ continue
+ members += (
+ "<member>"
+ f"<ChangeSetId>{_esc(cs['ChangeSetId'])}</ChangeSetId>"
+ f"<ChangeSetName>{_esc(cs['ChangeSetName'])}</ChangeSetName>"
+ f"<StackId>{_esc(cs['StackId'])}</StackId>"
+ f"<StackName>{_esc(cs['StackName'])}</StackName>"
+ f"<Status>{cs['Status']}</Status>"
+ f"<ExecutionStatus>{cs['ExecutionStatus']}</ExecutionStatus>"
+ f"<CreationTime>{cs['CreationTime']}</CreationTime>"
+ f"<Description>{_esc(cs.get('Description', ''))}</Description>"
+ "</member>"
+ )
+
+ return _xml(200, "ListChangeSetsResponse",
+ f"<ListChangeSetsResult>"
+ f"<Summaries>{members}</Summaries>"
+ f"</ListChangeSetsResult>")
+
+
+# --- GetTemplateSummary ---
+
diff --git a/ministack/services/cloudformation/engine.py b/ministack/services/cloudformation/engine.py
new file mode 100644
index 00000000..deaf1d2b
--- /dev/null
+++ b/ministack/services/cloudformation/engine.py
@@ -0,0 +1,544 @@
+"""
+CloudFormation engine — pure functions for template parsing, parameter resolution,
+condition evaluation, intrinsic function resolution, and topological sorting.
+"""
+
+import base64
+import heapq
+import json
+import re
+from collections import defaultdict
+
+import yaml
+
+from ministack.core.responses import new_uuid
+
+# Sentinel for AWS::NoValue
+_NO_VALUE = object()
+
+ACCOUNT_ID = "000000000000"
+REGION = "us-east-1"
+# Note: ACCOUNT_ID/REGION duplicated here to keep engine.py free of __init__ imports (avoids circular deps)
+
+
+# ===========================================================================
+# YAML Parser -- CloudFormation tag support
+# ===========================================================================
+
+class CfnLoader(yaml.SafeLoader):
+ """YAML loader that handles CloudFormation intrinsic function tags."""
+ pass
+
+
+def _construct_cfn_tag(tag_name):
+ """Build a constructor that wraps the value in {tag_name: value}."""
+ def constructor(loader, node):
+ if isinstance(node, yaml.ScalarNode):
+ val = loader.construct_scalar(node)
+ elif isinstance(node, yaml.SequenceNode):
+ val = loader.construct_sequence(node, deep=True)
+ elif isinstance(node, yaml.MappingNode):
+ val = loader.construct_mapping(node, deep=True)
+ else:
+ val = loader.construct_scalar(node)
+ return {tag_name: val}
+ return constructor
+
+
+def _construct_getatt(loader, node):
+ """!GetAtt -- scalar 'A.B' splits on first dot; sequence passes through."""
+ if isinstance(node, yaml.ScalarNode):
+ val = loader.construct_scalar(node)
+ parts = val.split(".", 1)
+ if len(parts) == 2:
+ return {"Fn::GetAtt": [parts[0], parts[1]]}
+ return {"Fn::GetAtt": [val, ""]}
+ if isinstance(node, yaml.SequenceNode):
+ val = loader.construct_sequence(node, deep=True)
+ return {"Fn::GetAtt": val}
+ val = loader.construct_scalar(node)
+ return {"Fn::GetAtt": [val, ""]}
+
+
+def _construct_timestamp(loader, node):
+ """Override timestamp to preserve date strings as plain strings."""
+ return loader.construct_scalar(node)
+
+
+# Register all CFN tags
+_SIMPLE_TAGS = {
+ "!Ref": "Ref",
+ "!Sub": "Fn::Sub",
+ "!Join": "Fn::Join",
+ "!Split": "Fn::Split",
+ "!Select": "Fn::Select",
+ "!If": "Fn::If",
+ "!Equals": "Fn::Equals",
+ "!And": "Fn::And",
+ "!Or": "Fn::Or",
+ "!Not": "Fn::Not",
+ "!Base64": "Fn::Base64",
+ "!FindInMap": "Fn::FindInMap",
+ "!ImportValue": "Fn::ImportValue",
+ "!GetAZs": "Fn::GetAZs",
+ "!Condition": "Condition",
+ "!Cidr": "Fn::Cidr",
+}
+
+for _tag, _fn_name in _SIMPLE_TAGS.items():
+ CfnLoader.add_constructor(_tag, _construct_cfn_tag(_fn_name))
+
+CfnLoader.add_constructor("!GetAtt", _construct_getatt)
+# Preserve date strings -- override the implicit timestamp resolver
+CfnLoader.add_constructor("tag:yaml.org,2002:timestamp", _construct_timestamp)
+
+
+def _parse_template(template_body: str) -> dict:
+ """Parse a CFN template from JSON or YAML."""
+ template_body = template_body.strip()
+ if template_body.startswith("{"):
+ result = json.loads(template_body)
+ else:
+ result = yaml.load(template_body, Loader=CfnLoader)
+ if not isinstance(result, dict):
+ raise ValueError("Template must be a JSON or YAML mapping")
+ return result
+
+
+# ===========================================================================
+# Parameter Resolver
+# ===========================================================================
+
+_AWS_SPECIFIC_TYPES = {
+ "AWS::SSM::Parameter::Type",
+ "AWS::SSM::Parameter::Value<String>",
+ "AWS::SSM::Parameter::Value<List<String>>",
+ "AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>",
+ "AWS::EC2::AvailabilityZone::Name",
+ "AWS::EC2::Image::Id",
+ "AWS::EC2::Instance::Id",
+ "AWS::EC2::KeyPair::KeyName",
+ "AWS::EC2::SecurityGroup::GroupName",
+ "AWS::EC2::SecurityGroup::Id",
+ "AWS::EC2::Subnet::Id",
+ "AWS::EC2::Volume::Id",
+ "AWS::EC2::VPC::Id",
+ "AWS::Route53::HostedZone::Id",
+}
+
+
+def _resolve_parameters(template: dict, provided_params: list[dict]) -> dict:
+ """Resolve template parameters with provided values and defaults.
+
+ Returns dict of param_name -> {Value, NoEcho}.
+ """
+ param_defs = template.get("Parameters", {})
+ provided_map = {p["Key"]: p["Value"] for p in provided_params if "Key" in p}
+ resolved = {}
+
+ for name, defn in param_defs.items():
+ ptype = defn.get("Type", "String")
+ no_echo = str(defn.get("NoEcho", "false")).lower() == "true"
+
+ if name in provided_map:
+ value = provided_map[name]
+ elif "Default" in defn:
+ value = defn["Default"]
+ else:
+ raise ValueError(f"Parameter '{name}' has no Default and was not provided")
+
+ value = str(value) if value is not None else ""
+
+ # Validate AllowedValues
+ allowed = defn.get("AllowedValues")
+ if allowed and value not in [str(a) for a in allowed]:
+ raise ValueError(
+ f"Parameter '{name}' value '{value}' is not in AllowedValues: {allowed}"
+ )
+
+ # Type coercion
+ if ptype == "Number":
+ # Validate it's numeric but keep as string for consistency
+ try:
+ float(value)
+ except ValueError:
+ raise ValueError(f"Parameter '{name}' value '{value}' is not a valid Number")
+ elif ptype == "CommaDelimitedList":
+ # Keep as string; Fn::Select will split
+ pass
+ # AWS-specific types treated as String -- no extra validation
+
+ resolved[name] = {"Value": value, "NoEcho": no_echo}
+
+ return resolved
+
+
+# ===========================================================================
+# Condition Evaluator
+# ===========================================================================
+
+def _evaluate_conditions(template: dict, params: dict) -> dict:
+ """Evaluate all conditions in the template. Returns {name: bool}."""
+ cond_defs = template.get("Conditions", {})
+ evaluated: dict[str, bool] = {}
+
+ def _eval(expr):
+ if isinstance(expr, dict):
+ if "Fn::Equals" in expr:
+ args = expr["Fn::Equals"]
+ left = _resolve_cond_value(args[0])
+ right = _resolve_cond_value(args[1])
+ return str(left) == str(right)
+ if "Fn::And" in expr:
+ return all(_eval(c) for c in expr["Fn::And"])
+ if "Fn::Or" in expr:
+ return any(_eval(c) for c in expr["Fn::Or"])
+ if "Fn::Not" in expr:
+ return not _eval(expr["Fn::Not"][0])
+ if "Condition" in expr:
+ cname = expr["Condition"]
+ if cname not in evaluated:
+ evaluated[cname] = _eval(cond_defs[cname])
+ return evaluated[cname]
+ if "Ref" in expr:
+ return _resolve_cond_value(expr)
+ return bool(expr)
+
+ def _resolve_cond_value(val):
+ if isinstance(val, dict):
+ if "Ref" in val:
+ pname = val["Ref"]
+ if pname in params:
+ return params[pname]["Value"]
+ return pname
+ if "Fn::Equals" in val:
+ return _eval(val)
+ if "Condition" in val:
+ return _eval(val)
+ return val
+
+ for name, defn in cond_defs.items():
+ if name not in evaluated:
+ evaluated[name] = _eval(defn)
+
+ return evaluated
+
+
+# ===========================================================================
+# Intrinsic Function Resolver
+# ===========================================================================
+
+def _resolve_refs(value, resources, params, conditions, mappings,
+ stack_name, stack_id):
+ """Recursively resolve CloudFormation intrinsic functions."""
+ if isinstance(value, str):
+ return value
+
+ if isinstance(value, list):
+ resolved = [
+ _resolve_refs(item, resources, params, conditions, mappings,
+ stack_name, stack_id)
+ for item in value
+ ]
+ return [r for r in resolved if r is not _NO_VALUE]
+
+ if not isinstance(value, dict):
+ return value
+
+ # --- Ref ---
+ if "Ref" in value:
+ ref = value["Ref"]
+ # Pseudo-parameters
+ pseudo = {
+ "AWS::StackName": stack_name,
+ "AWS::StackId": stack_id,
+ "AWS::Region": REGION,
+ "AWS::AccountId": ACCOUNT_ID,
+ "AWS::NoValue": _NO_VALUE,
+ "AWS::URLSuffix": "amazonaws.com",
+ "AWS::Partition": "aws",
+ "AWS::NotificationARNs": [],
+ }
+ if ref in pseudo:
+ return pseudo[ref]
+ if ref in params:
+ return params[ref]["Value"]
+ # Resource physical ID
+ if ref in resources and "PhysicalResourceId" in resources[ref]:
+ return resources[ref]["PhysicalResourceId"]
+ return ref
+
+ # --- Fn::GetAtt ---
+ if "Fn::GetAtt" in value:
+ args = value["Fn::GetAtt"]
+ if isinstance(args, str):
+ parts = args.split(".", 1)
+ logical_id = parts[0]
+ attr = parts[1] if len(parts) > 1 else ""
+ else:
+ logical_id = args[0]
+ attr = args[1] if len(args) > 1 else ""
+ res = resources.get(logical_id, {})
+ attrs = res.get("Attributes", {})
+ if attr in attrs:
+ return attrs[attr]
+ # Fallback: try PhysicalResourceId
+ return res.get("PhysicalResourceId", "")
+
+ # --- Fn::Join ---
+ if "Fn::Join" in value:
+ args = value["Fn::Join"]
+ delimiter = args[0]
+ items = _resolve_refs(args[1], resources, params, conditions,
+ mappings, stack_name, stack_id)
+ return delimiter.join(str(i) for i in items if i is not _NO_VALUE)
+
+ # --- Fn::Sub ---
+ if "Fn::Sub" in value:
+ sub_val = value["Fn::Sub"]
+ if isinstance(sub_val, list):
+ template_str = sub_val[0]
+ var_map = sub_val[1] if len(sub_val) > 1 else {}
+ # Resolve values in the var_map first
+ resolved_map = {}
+ for k, v in var_map.items():
+ resolved_map[k] = _resolve_refs(v, resources, params,
+ conditions, mappings,
+ stack_name, stack_id)
+ else:
+ template_str = sub_val
+ resolved_map = {}
+
+ def _sub_replace(match):
+ var = match.group(1)
+ # Check explicit var map first
+ if var in resolved_map:
+ return str(resolved_map[var])
+ # Pseudo-params
+ pseudo = {
+ "AWS::StackName": stack_name,
+ "AWS::StackId": stack_id,
+ "AWS::Region": REGION,
+ "AWS::AccountId": ACCOUNT_ID,
+ "AWS::URLSuffix": "amazonaws.com",
+ "AWS::Partition": "aws",
+ }
+ if var in pseudo:
+ return str(pseudo[var])
+ # Param
+ if var in params:
+ return str(params[var]["Value"])
+ # Resource.Attr
+ if "." in var:
+ parts = var.split(".", 1)
+ res = resources.get(parts[0], {})
+ attrs = res.get("Attributes", {})
+ if parts[1] in attrs:
+ return str(attrs[parts[1]])
+ return str(res.get("PhysicalResourceId", var))
+ # Resource physical ID
+ if var in resources and "PhysicalResourceId" in resources[var]:
+ return str(resources[var]["PhysicalResourceId"])
+ return var
+
+ return re.sub(r"\$\{([^}]+)\}", _sub_replace, str(template_str))
+
+ # --- Fn::Select ---
+ if "Fn::Select" in value:
+ args = value["Fn::Select"]
+ index = int(_resolve_refs(args[0], resources, params, conditions,
+ mappings, stack_name, stack_id))
+ items = _resolve_refs(args[1], resources, params, conditions,
+ mappings, stack_name, stack_id)
+ if isinstance(items, str):
+ items = [s.strip() for s in items.split(",")]
+ if 0 <= index < len(items):
+ return items[index]
+ return ""
+
+ # --- Fn::Split ---
+ if "Fn::Split" in value:
+ args = value["Fn::Split"]
+ delimiter = args[0]
+ source = _resolve_refs(args[1], resources, params, conditions,
+ mappings, stack_name, stack_id)
+ return str(source).split(delimiter)
+
+ # --- Fn::If ---
+ if "Fn::If" in value:
+ args = value["Fn::If"]
+ cond_name = args[0]
+ cond_val = conditions.get(cond_name, False)
+ branch = args[1] if cond_val else args[2]
+ result = _resolve_refs(branch, resources, params, conditions,
+ mappings, stack_name, stack_id)
+ return result
+
+ # --- Fn::Base64 ---
+ if "Fn::Base64" in value:
+ inner = _resolve_refs(value["Fn::Base64"], resources, params,
+ conditions, mappings, stack_name, stack_id)
+ return base64.b64encode(str(inner).encode("utf-8")).decode("utf-8")
+
+ # --- 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)
+ return mappings.get(str(map_name), {}).get(str(key1), {}).get(str(key2), "")
+
+ # --- Fn::ImportValue ---
+ if "Fn::ImportValue" in value:
+ from ministack.services.cloudformation import _exports
+ export_name = _resolve_refs(value["Fn::ImportValue"], resources,
+ params, conditions, mappings,
+ stack_name, stack_id)
+ export = _exports.get(str(export_name))
+ if export:
+ return export["Value"]
+ raise ValueError(f"Export '{export_name}' not found")
+
+ # --- Fn::GetAZs ---
+ if "Fn::GetAZs" in value:
+ region = _resolve_refs(value["Fn::GetAZs"], resources, params,
+ conditions, mappings, stack_name, stack_id)
+ if not region:
+ region = REGION
+ return [f"{region}a", f"{region}b", f"{region}c"]
+
+ # --- Fn::Cidr ---
+ if "Fn::Cidr" in value:
+ args = value["Fn::Cidr"]
+ ip_block = _resolve_refs(args[0], resources, params, conditions,
+ mappings, stack_name, stack_id)
+ count = int(_resolve_refs(args[1], resources, params, conditions,
+ mappings, stack_name, stack_id))
+ cidr_bits = int(_resolve_refs(args[2], resources, params, conditions,
+ mappings, stack_name, stack_id))
+ # Simplified CIDR generation
+ return [f"10.0.{i}.0/{32 - cidr_bits}" for i in range(count)]
+
+ # --- Fn::Equals (condition-like in non-condition context) ---
+ if "Fn::Equals" in value:
+ args = value["Fn::Equals"]
+ left = _resolve_refs(args[0], resources, params, conditions,
+ mappings, stack_name, stack_id)
+ right = _resolve_refs(args[1], resources, params, conditions,
+ mappings, stack_name, stack_id)
+ return str(left) == str(right)
+
+ # --- Condition (reference) ---
+ if "Condition" in value and len(value) == 1:
+ return conditions.get(value["Condition"], False)
+
+ # Recurse into plain dicts
+ result = {}
+ for k, v in value.items():
+ resolved = _resolve_refs(v, resources, params, conditions,
+ mappings, stack_name, stack_id)
+ if resolved is not _NO_VALUE:
+ result[k] = resolved
+ return result
+
+
+# ===========================================================================
+# Dependency Extractor + Topological Sort
+# ===========================================================================
+
+def _extract_deps(resource_def: dict, all_resource_names: set) -> set:
+ """Walk a resource definition and extract dependency logical IDs."""
+ deps = set()
+
+ def _walk(obj):
+ if isinstance(obj, dict):
+ if "Ref" in obj:
+ ref = obj["Ref"]
+ if ref in all_resource_names:
+ deps.add(ref)
+ if "Fn::GetAtt" in obj:
+ args = obj["Fn::GetAtt"]
+ if isinstance(args, list) and args:
+ if args[0] in all_resource_names:
+ deps.add(args[0])
+ elif isinstance(args, str):
+ logical = args.split(".")[0]
+ if logical in all_resource_names:
+ deps.add(logical)
+ if "Fn::Sub" in obj:
+ sub_val = obj["Fn::Sub"]
+ template_str = sub_val[0] if isinstance(sub_val, list) else sub_val
+ for match in re.finditer(r"\$\{([^}]+)\}", str(template_str)):
+ var = match.group(1)
+ base = var.split(".")[0]
+ if base in all_resource_names:
+ deps.add(base)
+ # Walk ALL branches of Fn::If
+ if "Fn::If" in obj:
+ args = obj["Fn::If"]
+ for branch in args[1:]:
+ _walk(branch)
+ for k, v in obj.items():
+ if k not in ("Ref", "Fn::GetAtt", "Fn::Sub", "Fn::If"):
+ _walk(v)
+ elif isinstance(obj, list):
+ for item in obj:
+ _walk(item)
+
+ # DependsOn
+ depends_on = resource_def.get("DependsOn", [])
+ if isinstance(depends_on, str):
+ depends_on = [depends_on]
+ for d in depends_on:
+ if d in all_resource_names:
+ deps.add(d)
+
+ # Walk Properties
+ _walk(resource_def.get("Properties", {}))
+
+ return deps
+
+
+def _topological_sort(resources: dict, conditions: dict) -> list:
+ """Kahn's algorithm for topological sort of resources."""
+ all_names = set(resources.keys())
+ # Filter out resources whose condition evaluates to false
+ active = set()
+ for name, defn in resources.items():
+ cond = defn.get("Condition")
+ if cond and not conditions.get(cond, True):
+ continue
+ active.add(name)
+
+ in_degree = {name: 0 for name in active}
+ adj: dict[str, list[str]] = {name: [] for name in active}
+
+ for name in active:
+ deps = _extract_deps(resources[name], active)
+ for dep in deps:
+ if dep in active and dep != name:
+ adj[dep].append(name)
+ in_degree[name] += 1
+
+ queue = sorted(n for n in active if in_degree[n] == 0)
+ heapq.heapify(queue)
+ result = []
+
+ while queue:
+ node = heapq.heappop(queue)
+ result.append(node)
+ for neighbor in adj[node]:
+ in_degree[neighbor] -= 1
+ if in_degree[neighbor] == 0:
+ heapq.heappush(queue, neighbor)
+
+ if len(result) != len(active):
+ remaining = active - set(result)
+ raise ValueError(
+ f"Circular dependency detected among resources: {', '.join(sorted(remaining))}"
+ )
+
+ return result
diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.py
new file mode 100644
index 00000000..2ed29f13
--- /dev/null
+++ b/ministack/services/cloudformation/handlers.py
@@ -0,0 +1,609 @@
+"""
+CloudFormation handlers — API action handlers for all supported CloudFormation actions.
+"""
+
+import asyncio
+import copy
+import json
+import logging
+
+from ministack.core.responses import new_uuid, now_iso
+
+from .engine import (
+ _evaluate_conditions, _parse_template, _resolve_parameters,
+ _resolve_refs, _NO_VALUE,
+)
+from .stacks import _add_event, _deploy_stack_async, _delete_stack_async, _diff_resources
+from .provisioners import _provision_resource, ACCOUNT_ID, REGION
+from .helpers import _xml, _error, _p, _esc, _extract_members, _extract_stack_status_filters, CFN_NS
+from .changesets import (
+ _create_change_set, _describe_change_set, _execute_change_set,
+ _delete_change_set, _list_change_sets,
+)
+
+logger = logging.getLogger("cloudformation")
+
+
+# --- CreateStack ---
+
+def _create_stack(params):
+ from ministack.services.cloudformation import _stacks, _stack_events, _exports, _change_sets
+ stack_name = _p(params, "StackName")
+ if not stack_name:
+ return _error("ValidationError", "StackName is required")
+
+ # Check TemplateURL (not supported)
+ if _p(params, "TemplateURL"):
+ return _error("ValidationError",
+ "TemplateURL is not supported; use TemplateBody")
+
+ template_body = _p(params, "TemplateBody")
+ if not template_body:
+ return _error("ValidationError", "TemplateBody is required")
+
+ # Check stack name uniqueness (active stacks)
+ existing = _stacks.get(stack_name)
+ if existing and existing.get("StackStatus", "") not in (
+ "DELETE_COMPLETE", "ROLLBACK_COMPLETE"
+ ):
+ return _error("AlreadyExistsException",
+ f"Stack [{stack_name}] already exists")
+
+ try:
+ template = _parse_template(template_body)
+ 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"
+
+ # Resolve parameters
+ try:
+ param_values = _resolve_parameters(template, provided_params)
+ except ValueError as exc:
+ return _error("ValidationError", str(exc))
+
+ stack_id = (
+ f"arn:aws:cloudformation:{REGION}:{ACCOUNT_ID}:"
+ f"stack/{stack_name}/{new_uuid()}"
+ )
+
+ stack = {
+ "StackName": stack_name,
+ "StackId": stack_id,
+ "StackStatus": "CREATE_IN_PROGRESS",
+ "StackStatusReason": "",
+ "CreationTime": now_iso(),
+ "LastUpdatedTime": now_iso(),
+ "Description": template.get("Description", ""),
+ "Parameters": [
+ {
+ "ParameterKey": k,
+ "ParameterValue": v["Value"],
+ "NoEcho": v["NoEcho"],
+ }
+ for k, v in param_values.items()
+ ],
+ "Tags": tags,
+ "Outputs": [],
+ "DisableRollback": disable_rollback,
+ "_resources": {},
+ "_template": template,
+ "_template_body": template_body,
+ "_resolved_params": param_values,
+ "_conditions": _evaluate_conditions(template, param_values),
+ }
+ _stacks[stack_name] = stack
+ _stack_events[stack_id] = []
+
+ _add_event(stack_id, stack_name, stack_name,
+ "AWS::CloudFormation::Stack", "CREATE_IN_PROGRESS",
+ physical_id=stack_id)
+
+ asyncio.ensure_future(
+ _deploy_stack_async(stack_name, stack_id, template,
+ param_values, disable_rollback, tags)
+ )
+
+ return _xml(200, "CreateStackResponse",
+ f"<CreateStackResult><StackId>{stack_id}</StackId></CreateStackResult>")
+
+
+# --- DescribeStacks ---
+
+def _describe_stacks(params):
+ from ministack.services.cloudformation import _stacks
+ stack_name = _p(params, "StackName")
+
+ if stack_name:
+ stack = _stacks.get(stack_name)
+ # Also try matching by stack ID
+ if not stack:
+ for s in _stacks.values():
+ if s.get("StackId") == stack_name:
+ stack = s
+ break
+ if not stack:
+ return _error("ValidationError",
+ f"Stack with id {stack_name} does not exist")
+ stacks_to_describe = [stack]
+ else:
+ # Return all stacks except DELETE_COMPLETE
+ stacks_to_describe = [
+ s for s in _stacks.values()
+ if s.get("StackStatus") != "DELETE_COMPLETE"
+ ]
+
+ members = ""
+ for s in stacks_to_describe:
+ params_xml = ""
+ for p in s.get("Parameters", []):
+ val = "****" if p.get("NoEcho") else _esc(str(p.get("ParameterValue", "")))
+ params_xml += (
+ "<member>"
+ f"<ParameterKey>{_esc(p['ParameterKey'])}</ParameterKey>"
+ f"<ParameterValue>{val}</ParameterValue>"
+ "</member>"
+ )
+
+ outputs_xml = ""
+ for o in s.get("Outputs", []):
+ export_xml = ""
+ if o.get("ExportName"):
+ export_xml = f"<ExportName>{_esc(o['ExportName'])}</ExportName>"
+ outputs_xml += (
+ "<member>"
+ f"<OutputKey>{_esc(o['OutputKey'])}</OutputKey>"
+ f"<OutputValue>{_esc(str(o['OutputValue']))}</OutputValue>"
+ f"<Description>{_esc(o.get('Description', ''))}</Description>"
+ f"{export_xml}"
+ "</member>"
+ )
+
+ tags_xml = ""
+ for t in s.get("Tags", []):
+ tags_xml += (
+ "<member>"
+ f"<Key>{_esc(t.get('Key', ''))}</Key>"
+ f"<Value>{_esc(t.get('Value', ''))}</Value>"
+ "</member>"
+ )
+
+ members += (
+ "<member>"
+ f"<StackName>{_esc(s['StackName'])}</StackName>"
+ f"<StackId>{_esc(s['StackId'])}</StackId>"
+ f"<StackStatus>{s['StackStatus']}</StackStatus>"
+ f"<StackStatusReason>{_esc(s.get('StackStatusReason', ''))}</StackStatusReason>"
+ f"<CreationTime>{s.get('CreationTime', '')}</CreationTime>"
+ f"<LastUpdatedTime>{s.get('LastUpdatedTime', '')}</LastUpdatedTime>"
+ f"<Description>{_esc(s.get('Description', ''))}</Description>"
+ f"<DisableRollback>{str(s.get('DisableRollback', False)).lower()}</DisableRollback>"
+ f"<Parameters>{params_xml}</Parameters>"
+ f"<Outputs>{outputs_xml}</Outputs>"
+ f"<Tags>{tags_xml}</Tags>"
+ "</member>"
+ )
+
+ return _xml(200, "DescribeStacksResponse",
+ f"<DescribeStacksResult><Stacks>{members}</Stacks></DescribeStacksResult>")
+
+
+# --- ListStacks ---
+
+def _list_stacks(params):
+ from ministack.services.cloudformation import _stacks
+ status_filters = _extract_stack_status_filters(params)
+
+ summaries = ""
+ for s in _stacks.values():
+ status = s.get("StackStatus", "")
+ if status_filters and status not in status_filters:
+ continue
+ entry = (
+ "<member>"
+ f"<StackName>{_esc(s['StackName'])}</StackName>"
+ f"<StackId>{_esc(s['StackId'])}</StackId>"
+ f"<StackStatus>{status}</StackStatus>"
+ f"<CreationTime>{s.get('CreationTime', '')}</CreationTime>"
+ )
+ if s.get("LastUpdatedTime"):
+ entry += f"<LastUpdatedTime>{s['LastUpdatedTime']}</LastUpdatedTime>"
+ if s.get("StackStatusReason"):
+ entry += f"<StackStatusReason>{_esc(s['StackStatusReason'])}</StackStatusReason>"
+ if s.get("DeletionTime"):
+ entry += f"<DeletionTime>{s['DeletionTime']}</DeletionTime>"
+ entry += "</member>"
+ summaries += entry
+
+ return _xml(200, "ListStacksResponse",
+ f"<ListStacksResult><StackSummaries>{summaries}</StackSummaries></ListStacksResult>")
+
+
+# --- DescribeStackEvents ---
+
+def _describe_stack_events(params):
+ from ministack.services.cloudformation import _stacks, _stack_events
+ stack_name = _p(params, "StackName")
+ if not stack_name:
+ return _error("ValidationError", "StackName is required")
+
+ stack = _stacks.get(stack_name)
+ if not stack:
+ # Try by stack ID
+ for s in _stacks.values():
+ if s.get("StackId") == stack_name:
+ stack = s
+ break
+ if not stack:
+ return _error("ValidationError",
+ f"Stack [{stack_name}] does not exist")
+
+ stack_id = stack["StackId"]
+ events = _stack_events.get(stack_id, [])
+ # Newest first
+ events_sorted = sorted(events, key=lambda e: e.get("Timestamp", ""),
+ reverse=True)
+
+ members = ""
+ for e in events_sorted:
+ members += (
+ "<member>"
+ f"<StackId>{_esc(e.get('StackId', ''))}</StackId>"
+ f"<StackName>{_esc(e.get('StackName', ''))}</StackName>"
+ f"<EventId>{_esc(e.get('EventId', ''))}</EventId>"
+ f"<LogicalResourceId>{_esc(e.get('LogicalResourceId', ''))}</LogicalResourceId>"
+ f"<PhysicalResourceId>{_esc(e.get('PhysicalResourceId', ''))}</PhysicalResourceId>"
+ f"<ResourceType>{_esc(e.get('ResourceType', ''))}</ResourceType>"
+ f"<ResourceStatus>{e.get('ResourceStatus', '')}</ResourceStatus>"
+ f"<ResourceStatusReason>{_esc(e.get('ResourceStatusReason', ''))}</ResourceStatusReason>"
+ f"<Timestamp>{e.get('Timestamp', '')}</Timestamp>"
+ "</member>"
+ )
+
+ return _xml(200, "DescribeStackEventsResponse",
+ f"<DescribeStackEventsResult><StackEvents>{members}</StackEvents></DescribeStackEventsResult>")
+
+
+# --- DescribeStackResource ---
+
+def _describe_stack_resource(params):
+ from ministack.services.cloudformation import _stacks
+ stack_name = _p(params, "StackName")
+ logical_id = _p(params, "LogicalResourceId")
+
+ stack = _stacks.get(stack_name)
+ if not stack:
+ return _error("ValidationError",
+ f"Stack [{stack_name}] does not exist")
+
+ resources = stack.get("_resources", {})
+ res = resources.get(logical_id)
+ if not res:
+ return _error("ValidationError",
+ f"Resource [{logical_id}] does not exist in stack [{stack_name}]")
+
+ detail = (
+ f"<LogicalResourceId>{_esc(logical_id)}</LogicalResourceId>"
+ f"<PhysicalResourceId>{_esc(res.get('PhysicalResourceId', ''))}</PhysicalResourceId>"
+ f"<ResourceType>{_esc(res.get('ResourceType', ''))}</ResourceType>"
+ f"<ResourceStatus>{res.get('ResourceStatus', '')}</ResourceStatus>"
+ f"<Timestamp>{res.get('Timestamp', '')}</Timestamp>"
+ f"<StackName>{_esc(stack_name)}</StackName>"
+ f"<StackId>{_esc(stack['StackId'])}</StackId>"
+ )
+
+ return _xml(200, "DescribeStackResourceResponse",
+ f"<DescribeStackResourceResult>"
+ f"<StackResourceDetail>{detail}</StackResourceDetail>"
+ f"</DescribeStackResourceResult>")
+
+
+# --- DescribeStackResources ---
+
+def _describe_stack_resources(params):
+ from ministack.services.cloudformation import _stacks
+ stack_name = _p(params, "StackName")
+
+ stack = _stacks.get(stack_name)
+ if not stack:
+ return _error("ValidationError",
+ f"Stack [{stack_name}] does not exist")
+
+ resources = stack.get("_resources", {})
+ members = ""
+ for logical_id, res in resources.items():
+ members += (
+ "<member>"
+ f"<LogicalResourceId>{_esc(logical_id)}</LogicalResourceId>"
+ f"<PhysicalResourceId>{_esc(res.get('PhysicalResourceId', ''))}</PhysicalResourceId>"
+ f"<ResourceType>{_esc(res.get('ResourceType', ''))}</ResourceType>"
+ f"<ResourceStatus>{res.get('ResourceStatus', '')}</ResourceStatus>"
+ f"<Timestamp>{res.get('Timestamp', '')}</Timestamp>"
+ f"<StackName>{_esc(stack_name)}</StackName>"
+ f"<StackId>{_esc(stack['StackId'])}</StackId>"
+ "</member>"
+ )
+
+ return _xml(200, "DescribeStackResourcesResponse",
+ f"<DescribeStackResourcesResult>"
+ f"<StackResources>{members}</StackResources>"
+ f"</DescribeStackResourcesResult>")
+
+
+# --- GetTemplate ---
+
+def _get_template(params):
+ from ministack.services.cloudformation import _stacks
+ stack_name = _p(params, "StackName")
+
+ stack = _stacks.get(stack_name)
+ if not stack:
+ for s in _stacks.values():
+ if s.get("StackId") == stack_name:
+ stack = s
+ break
+ if not stack:
+ return _error("ValidationError",
+ f"Stack [{stack_name}] does not exist")
+
+ template_body = stack.get("_template_body", "{}")
+ return _xml(200, "GetTemplateResponse",
+ f"<GetTemplateResult>"
+ f"<TemplateBody>{_esc(template_body)}</TemplateBody>"
+ f"</GetTemplateResult>")
+
+
+# --- DeleteStack ---
+
+def _delete_stack(params):
+ from ministack.services.cloudformation import _stacks
+ stack_name = _p(params, "StackName")
+ if not stack_name:
+ return _error("ValidationError", "StackName is required")
+
+ stack = _stacks.get(stack_name)
+ if not stack:
+ # AWS returns success for deleting non-existent stacks
+ return _xml(200, "DeleteStackResponse", "")
+
+ if stack.get("StackStatus") == "DELETE_COMPLETE":
+ return _xml(200, "DeleteStackResponse", "")
+
+ # Check for active imports before deleting
+ stack_exports = [
+ out.get("ExportName") for out in stack.get("Outputs", [])
+ if out.get("ExportName")
+ ]
+ for export_name in stack_exports:
+ for other_name, other_stack in _stacks.items():
+ if other_name == stack_name:
+ continue
+ other_status = other_stack.get("StackStatus", "")
+ if other_status.endswith("_COMPLETE") and "DELETE" not in other_status:
+ other_template = other_stack.get("_template", {})
+ if export_name in json.dumps(other_template):
+ return _error("ValidationError",
+ f"Export {export_name} is imported by stack {other_name}")
+
+ stack_id = stack["StackId"]
+ asyncio.ensure_future(_delete_stack_async(stack_name, stack_id))
+
+ return _xml(200, "DeleteStackResponse", "")
+
+
+# --- UpdateStack ---
+
+def _update_stack(params):
+ from ministack.services.cloudformation import _stacks
+ stack_name = _p(params, "StackName")
+ if not stack_name:
+ return _error("ValidationError", "StackName is required")
+
+ stack = _stacks.get(stack_name)
+ if not stack:
+ return _error("ValidationError",
+ f"Stack [{stack_name}] does not exist")
+
+ current_status = stack.get("StackStatus", "")
+ if current_status not in ("CREATE_COMPLETE", "UPDATE_COMPLETE",
+ "UPDATE_ROLLBACK_COMPLETE"):
+ return _error("ValidationError",
+ f"Stack [{stack_name}] is in {current_status} state "
+ f"and cannot be updated")
+
+ template_body = _p(params, "TemplateBody")
+ if _p(params, "TemplateURL"):
+ return _error("ValidationError",
+ "TemplateURL is not supported; use TemplateBody")
+ if not template_body:
+ # Use previous template if UsePreviousTemplate
+ if _p(params, "UsePreviousTemplate", "false").lower() == "true":
+ template_body = stack.get("_template_body", "{}")
+ else:
+ return _error("ValidationError", "TemplateBody is required")
+
+ try:
+ template = _parse_template(template_body)
+ 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"
+
+ try:
+ param_values = _resolve_parameters(template, provided_params)
+ except ValueError as exc:
+ return _error("ValidationError", str(exc))
+
+ # Save previous state for rollback
+ previous_stack = {
+ "_resources": copy.deepcopy(stack.get("_resources", {})),
+ "_template": copy.deepcopy(stack.get("_template", {})),
+ "_template_body": stack.get("_template_body", ""),
+ "_resolved_params": copy.deepcopy(stack.get("_resolved_params", {})),
+ "Outputs": copy.deepcopy(stack.get("Outputs", [])),
+ }
+
+ stack_id = stack["StackId"]
+ stack["StackStatus"] = "UPDATE_IN_PROGRESS"
+ stack["LastUpdatedTime"] = now_iso()
+ stack["_template_body"] = template_body
+ if tags:
+ stack["Tags"] = tags
+ stack["Parameters"] = [
+ {"ParameterKey": k, "ParameterValue": v["Value"], "NoEcho": v["NoEcho"]}
+ for k, v in param_values.items()
+ ]
+ stack["_conditions"] = _evaluate_conditions(template, param_values)
+
+ _add_event(stack_id, stack_name, stack_name,
+ "AWS::CloudFormation::Stack", "UPDATE_IN_PROGRESS",
+ physical_id=stack_id)
+
+ asyncio.ensure_future(
+ _deploy_stack_async(stack_name, stack_id, template,
+ param_values, disable_rollback, tags,
+ is_update=True, previous_stack=previous_stack)
+ )
+
+ return _xml(200, "UpdateStackResponse",
+ f"<UpdateStackResult><StackId>{stack_id}</StackId></UpdateStackResult>")
+
+
+# --- ValidateTemplate ---
+
+def _validate_template(params):
+ template_body = _p(params, "TemplateBody")
+ if not template_body:
+ return _error("ValidationError", "TemplateBody is required")
+
+ try:
+ template = _parse_template(template_body)
+ except Exception as e:
+ return _error("ValidationError", f"Template format error: {e}")
+ if "Resources" not in template:
+ return _error("ValidationError",
+ "Template format error: At least one Resources member must be defined.")
+ description = template.get("Description", "")
+ param_defs = template.get("Parameters", {})
+
+ params_xml = ""
+ for name, defn in param_defs.items():
+ default = defn.get("Default", "")
+ no_echo = str(defn.get("NoEcho", "false")).lower()
+ ptype = defn.get("Type", "String")
+ desc = defn.get("Description", "")
+ params_xml += (
+ "<member>"
+ f"<ParameterKey>{_esc(name)}</ParameterKey>"
+ f"<DefaultValue>{_esc(str(default))}</DefaultValue>"
+ f"<NoEcho>{no_echo}</NoEcho>"
+ f"<ParameterType>{_esc(ptype)}</ParameterType>"
+ f"<Description>{_esc(desc)}</Description>"
+ "</member>"
+ )
+
+ return _xml(200, "ValidateTemplateResponse",
+ f"<ValidateTemplateResult>"
+ f"<Description>{_esc(description)}</Description>"
+ f"<Parameters>{params_xml}</Parameters>"
+ f"</ValidateTemplateResult>")
+
+
+# --- ListExports ---
+
+def _list_exports(params):
+ from ministack.services.cloudformation import _exports
+ members = ""
+ for name, exp in _exports.items():
+ members += (
+ "<member>"
+ f"<ExportingStackId>{_esc(exp.get('StackId', ''))}</ExportingStackId>"
+ f"<Name>{_esc(name)}</Name>"
+ f"<Value>{_esc(str(exp.get('Value', '')))}</Value>"
+ "</member>"
+ )
+
+ return _xml(200, "ListExportsResponse",
+ f"<ListExportsResult><Exports>{members}</Exports></ListExportsResult>")
+# --- GetTemplateSummary ---
+
+def _get_template_summary(params):
+ from ministack.services.cloudformation import _stacks
+ template_body = _p(params, "TemplateBody")
+ stack_name = _p(params, "StackName")
+
+ if stack_name:
+ stack = _stacks.get(stack_name)
+ if not stack:
+ return _error("ValidationError",
+ f"Stack [{stack_name}] does not exist")
+ template_body = stack.get("_template_body", "{}")
+
+ if not template_body:
+ return _error("ValidationError",
+ "Either TemplateBody or StackName must be provided")
+
+ try:
+ template = _parse_template(template_body)
+ except Exception as e:
+ return _error("ValidationError", f"Template format error: {e}")
+ description = template.get("Description", "")
+ resources = template.get("Resources", {})
+ param_defs = template.get("Parameters", {})
+
+ # Resource types
+ resource_types = sorted(set(
+ r.get("Type", "") for r in resources.values()
+ ))
+ types_xml = "".join(f"<member>{_esc(t)}</member>" for t in resource_types)
+
+ # Parameters
+ params_xml = ""
+ for name, defn in param_defs.items():
+ default = defn.get("Default", "")
+ no_echo = str(defn.get("NoEcho", "false")).lower()
+ ptype = defn.get("Type", "String")
+ desc = defn.get("Description", "")
+ params_xml += (
+ "<member>"
+ f"<ParameterKey>{_esc(name)}</ParameterKey>"
+ f"<DefaultValue>{_esc(str(default))}</DefaultValue>"
+ f"<NoEcho>{no_echo}</NoEcho>"
+ f"<ParameterType>{_esc(ptype)}</ParameterType>"
+ f"<Description>{_esc(desc)}</Description>"
+ "</member>"
+ )
+
+ return _xml(200, "GetTemplateSummaryResponse",
+ f"<GetTemplateSummaryResult>"
+ f"<Description>{_esc(description)}</Description>"
+ f"<ResourceTypes>{types_xml}</ResourceTypes>"
+ f"<Parameters>{params_xml}</Parameters>"
+ f"</GetTemplateSummaryResult>")
+
+
+# ===========================================================================
+# Action Handler Registry
+# ===========================================================================
+
+_ACTION_HANDLERS = {
+ "CreateStack": _create_stack,
+ "DescribeStacks": _describe_stacks,
+ "ListStacks": _list_stacks,
+ "DeleteStack": _delete_stack,
+ "UpdateStack": _update_stack,
+ "DescribeStackEvents": _describe_stack_events,
+ "DescribeStackResource": _describe_stack_resource,
+ "DescribeStackResources": _describe_stack_resources,
+ "GetTemplate": _get_template,
+ "ValidateTemplate": _validate_template,
+ "ListExports": _list_exports,
+ "CreateChangeSet": _create_change_set,
+ "DescribeChangeSet": _describe_change_set,
+ "ExecuteChangeSet": _execute_change_set,
+ "DeleteChangeSet": _delete_change_set,
+ "ListChangeSets": _list_change_sets,
+ "GetTemplateSummary": _get_template_summary,
+}
diff --git a/ministack/services/cloudformation/helpers.py b/ministack/services/cloudformation/helpers.py
new file mode 100644
index 00000000..811c4c77
--- /dev/null
+++ b/ministack/services/cloudformation/helpers.py
@@ -0,0 +1,68 @@
+"""
+CloudFormation helpers — XML response formatting and parameter extraction utilities.
+"""
+
+from html import escape as _esc
+
+from ministack.core.responses import new_uuid
+
+CFN_NS = "http://cloudformation.amazonaws.com/doc/2010-05-08/"
+
+
+def _p(params, key, default=""):
+ """Extract a single value from parsed query-string params."""
+ val = params.get(key, [default])
+ return val[0] if isinstance(val, list) else val
+
+
+def _xml(status, root_tag, inner):
+ body = (
+ f'<?xml version="1.0" encoding="UTF-8"?>'
+ f'<{root_tag} xmlns="{CFN_NS}">'
+ f'{inner}'
+ f'<ResponseMetadata><RequestId>{new_uuid()}</RequestId></ResponseMetadata>'
+ f'</{root_tag}>'
+ ).encode("utf-8")
+ return status, {"Content-Type": "application/xml"}, body
+
+
+def _error(code, message, status=400):
+ t = "Sender" if status < 500 else "Receiver"
+ body = (
+ f'<?xml version="1.0" encoding="UTF-8"?>'
+ f'<ErrorResponse xmlns="{CFN_NS}">'
+ f'<Error><Type>{t}</Type><Code>{code}</Code>'
+ f'<Message>{_esc(message)}</Message></Error>'
+ f'<RequestId>{new_uuid()}</RequestId>'
+ f'</ErrorResponse>'
+ ).encode("utf-8")
+ return status, {"Content-Type": "application/xml"}, body
+
+
+def _extract_members(params, prefix):
+ """Extract Parameters.member.N.Key/Value or Tags.member.N.Key/Value."""
+ result = []
+ i = 1
+ while True:
+ key = (_p(params, f"{prefix}.member.{i}.ParameterKey")
+ or _p(params, f"{prefix}.member.{i}.Key"))
+ if not key:
+ break
+ value = (_p(params, f"{prefix}.member.{i}.ParameterValue")
+ or _p(params, f"{prefix}.member.{i}.Value"))
+ result.append({"Key": key, "Value": value or ""})
+ i += 1
+ return result
+
+
+def _extract_stack_status_filters(params):
+ """Extract StackStatusFilter.member.N values."""
+ filters = []
+ i = 1
+ while True:
+ val = _p(params, f"StackStatusFilter.member.{i}")
+ if not val:
+ break
+ filters.append(val)
+ i += 1
+ return filters
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
new file mode 100644
index 00000000..5c5fe516
--- /dev/null
+++ b/ministack/services/cloudformation/provisioners.py
@@ -0,0 +1,614 @@
+"""
+CloudFormation provisioners — resource create/delete handlers for each AWS resource type.
+"""
+
+import json
+import logging
+import time
+from collections import defaultdict
+
+from ministack.core.responses import new_uuid, now_iso
+
+import ministack.services.s3 as _s3
+import ministack.services.sqs as _sqs
+import ministack.services.sns as _sns
+import ministack.services.dynamodb as _dynamodb
+import ministack.services.lambda_svc as _lambda_svc
+import ministack.services.ssm as _ssm
+import ministack.services.cloudwatch_logs as _cw_logs
+import ministack.services.eventbridge as _eb
+import ministack.services.iam_sts as _iam_sts
+
+
+logger = logging.getLogger("cloudformation")
+
+ACCOUNT_ID = "000000000000"
+REGION = "us-east-1"
+
+
+# ===========================================================================
+# Resource Provisioner Framework
+# ===========================================================================
+
+def _provision_resource(resource_type: str, logical_id: str, props: dict,
+ stack_name: str) -> tuple:
+ """Provision a resource. Returns (physical_id, attributes)."""
+ handler = _RESOURCE_HANDLERS.get(resource_type)
+ if handler and "create" in handler:
+ return handler["create"](logical_id, props, stack_name)
+ # 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)
+ noop_id = f"{stack_name}-{logical_id}-noop-{new_uuid()[:8]}"
+ return noop_id, {}
+ raise ValueError(f"Unsupported resource type: {resource_type}")
+
+
+def _delete_resource(resource_type: str, physical_id: str, props: dict):
+ """Delete a provisioned resource."""
+ handler = _RESOURCE_HANDLERS.get(resource_type)
+ if handler and "delete" in handler:
+ handler["delete"](physical_id, props)
+ return
+ logger.warning("No delete handler for resource type %s (id=%s)",
+ resource_type, physical_id)
+
+
+# ===========================================================================
+# Resource Provisioners
+# ===========================================================================
+
+# --- S3 Bucket ---
+
+def _s3_create(logical_id, props, stack_name):
+ name = props.get("BucketName") or f"{stack_name}-{logical_id.lower()}-{new_uuid()[:8]}"
+ _s3._buckets[name] = {
+ "created": now_iso(),
+ "objects": {},
+ "region": REGION,
+ }
+ versioning = props.get("VersioningConfiguration", {})
+ if versioning.get("Status") == "Enabled":
+ _s3._bucket_versioning[name] = "Enabled"
+ attrs = {
+ "Arn": f"arn:aws:s3:::{name}",
+ "DomainName": f"{name}.s3.amazonaws.com",
+ "RegionalDomainName": f"{name}.s3.{REGION}.amazonaws.com",
+ "WebsiteURL": f"http://{name}.s3-website-{REGION}.amazonaws.com",
+ }
+ return name, attrs
+
+
+def _s3_delete(physical_id, props):
+ _s3._buckets.pop(physical_id, None)
+ _s3._bucket_versioning.pop(physical_id, None)
+ _s3._bucket_policies.pop(physical_id, None)
+ _s3._bucket_tags.pop(physical_id, None)
+ _s3._bucket_encryption.pop(physical_id, None)
+ _s3._bucket_lifecycle.pop(physical_id, None)
+ _s3._bucket_cors.pop(physical_id, None)
+ _s3._bucket_acl.pop(physical_id, None)
+ _s3._bucket_notifications.pop(physical_id, None)
+
+
+# --- SQS Queue ---
+
+def _sqs_create(logical_id, props, stack_name):
+ name = props.get("QueueName") or f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
+ is_fifo = name.endswith(".fifo")
+ url = f"http://localhost:4566/{ACCOUNT_ID}/{name}"
+ arn = f"arn:aws:sqs:{REGION}:{ACCOUNT_ID}:{name}"
+ now_ts = str(int(time.time()))
+
+ attributes = {
+ "QueueArn": arn,
+ "CreatedTimestamp": now_ts,
+ "LastModifiedTimestamp": now_ts,
+ "VisibilityTimeout": str(props.get("VisibilityTimeout", "30")),
+ "MaximumMessageSize": str(props.get("MaximumMessageSize", "262144")),
+ "MessageRetentionPeriod": str(props.get("MessageRetentionPeriod", "345600")),
+ "DelaySeconds": str(props.get("DelaySeconds", "0")),
+ "ReceiveMessageWaitTimeSeconds": str(props.get("ReceiveMessageWaitTimeSeconds", "0")),
+ }
+ if is_fifo:
+ attributes["FifoQueue"] = "true"
+ if props.get("ContentBasedDeduplication"):
+ attributes["ContentBasedDeduplication"] = str(props["ContentBasedDeduplication"]).lower()
+
+ queue = {
+ "name": name,
+ "url": url,
+ "is_fifo": is_fifo,
+ "attributes": attributes,
+ "messages": [],
+ "tags": {},
+ "dedup_cache": {},
+ "fifo_seq": 0,
+ }
+ _sqs._queues[url] = queue
+ _sqs._queue_name_to_url[name] = url
+ return url, {"Arn": arn, "QueueName": name, "QueueUrl": url}
+
+
+def _sqs_delete(physical_id, props):
+ queue = _sqs._queues.pop(physical_id, None)
+ if queue:
+ _sqs._queue_name_to_url.pop(queue.get("name", ""), None)
+
+
+# --- SNS Topic ---
+
+def _sns_create(logical_id, props, stack_name):
+ name = props.get("TopicName") or f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
+ arn = f"arn:aws:sns:{REGION}:{ACCOUNT_ID}:{name}"
+ default_policy = json.dumps({
+ "Version": "2008-10-17",
+ "Id": "__default_policy_ID",
+ "Statement": [{
+ "Sid": "__default_statement_ID",
+ "Effect": "Allow",
+ "Principal": {"AWS": "*"},
+ "Action": ["SNS:Publish", "SNS:Subscribe", "SNS:Receive"],
+ "Resource": arn,
+ }],
+ })
+ _sns._topics[arn] = {
+ "name": name,
+ "arn": arn,
+ "attributes": {
+ "TopicArn": arn,
+ "DisplayName": props.get("DisplayName", name),
+ "Owner": ACCOUNT_ID,
+ "Policy": default_policy,
+ "SubscriptionsConfirmed": "0",
+ "SubscriptionsPending": "0",
+ "SubscriptionsDeleted": "0",
+ "EffectiveDeliveryPolicy": json.dumps({
+ "http": {
+ "defaultHealthyRetryPolicy": {
+ "minDelayTarget": 20,
+ "maxDelayTarget": 20,
+ "numRetries": 3,
+ }
+ }
+ }),
+ },
+ "subscriptions": [],
+ "messages": [],
+ "tags": {},
+ }
+
+ # Handle Subscription property
+ subscriptions = props.get("Subscription", [])
+ for sub_def in subscriptions:
+ protocol = sub_def.get("Protocol", "")
+ endpoint = sub_def.get("Endpoint", "")
+ sub_arn = f"{arn}:{new_uuid()}"
+ sub = {
+ "arn": sub_arn,
+ "topic_arn": arn,
+ "protocol": protocol,
+ "endpoint": endpoint,
+ "confirmed": protocol not in ("http", "https"),
+ "owner": ACCOUNT_ID,
+ "attributes": {},
+ }
+ _sns._topics[arn]["subscriptions"].append(sub)
+ _sns._sub_arn_to_topic[sub_arn] = arn
+
+ return arn, {"TopicArn": arn, "TopicName": name}
+
+
+def _sns_delete(physical_id, props):
+ topic = _sns._topics.pop(physical_id, None)
+ if topic:
+ for sub in topic.get("subscriptions", []):
+ _sns._sub_arn_to_topic.pop(sub.get("arn", ""), None)
+
+
+# --- SNS Subscription (standalone) ---
+
+def _sns_sub_create(logical_id, props, stack_name):
+ topic_arn = props.get("TopicArn", "")
+ protocol = props.get("Protocol", "")
+ endpoint = props.get("Endpoint", "")
+ topic = _sns._topics.get(topic_arn)
+ if not topic:
+ sub_arn = f"{topic_arn}:{new_uuid()}"
+ return sub_arn, {"SubscriptionArn": sub_arn}
+
+ sub_arn = f"{topic_arn}:{new_uuid()}"
+ sub = {
+ "arn": sub_arn,
+ "topic_arn": topic_arn,
+ "protocol": protocol,
+ "endpoint": endpoint,
+ "confirmed": protocol not in ("http", "https"),
+ "owner": ACCOUNT_ID,
+ "attributes": {},
+ }
+ topic["subscriptions"].append(sub)
+ _sns._sub_arn_to_topic[sub_arn] = topic_arn
+ return sub_arn, {"SubscriptionArn": sub_arn}
+
+
+def _sns_sub_delete(physical_id, props):
+ topic_arn = _sns._sub_arn_to_topic.pop(physical_id, None)
+ if topic_arn:
+ topic = _sns._topics.get(topic_arn)
+ if topic:
+ topic["subscriptions"] = [
+ s for s in topic["subscriptions"] if s["arn"] != physical_id
+ ]
+
+
+# --- DynamoDB Table ---
+
+def _ddb_create(logical_id, props, stack_name):
+ name = props.get("TableName") or f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
+ arn = f"arn:aws:dynamodb:{REGION}:{ACCOUNT_ID}:table/{name}"
+
+ key_schema = props.get("KeySchema", [])
+ pk_name = None
+ sk_name = None
+ for ks in key_schema:
+ if ks.get("KeyType") == "HASH":
+ pk_name = ks.get("AttributeName")
+ elif ks.get("KeyType") == "RANGE":
+ sk_name = ks.get("AttributeName")
+
+ attr_defs = props.get("AttributeDefinitions", [])
+ gsis = props.get("GlobalSecondaryIndexes", [])
+ lsis = props.get("LocalSecondaryIndexes", [])
+
+ stream_spec = props.get("StreamSpecification", {})
+ stream_enabled = stream_spec.get("StreamEnabled", False)
+ stream_arn = f"{arn}/stream/{now_iso()}" if stream_enabled else None
+
+ billing = props.get("BillingMode", "PROVISIONED")
+
+ table = {
+ "TableName": name,
+ "TableArn": arn,
+ "TableId": new_uuid(),
+ "TableStatus": "ACTIVE",
+ "CreationDateTime": time.time(),
+ "KeySchema": key_schema,
+ "AttributeDefinitions": attr_defs,
+ "ProvisionedThroughput": props.get("ProvisionedThroughput", {
+ "ReadCapacityUnits": 5,
+ "WriteCapacityUnits": 5,
+ }),
+ "BillingModeSummary": {"BillingMode": billing},
+ "pk_name": pk_name,
+ "sk_name": sk_name,
+ "items": defaultdict(dict),
+ "ItemCount": 0,
+ "TableSizeBytes": 0,
+ "GlobalSecondaryIndexes": gsis,
+ "LocalSecondaryIndexes": lsis,
+ "StreamSpecification": stream_spec if stream_enabled else None,
+ "LatestStreamArn": stream_arn,
+ "LatestStreamLabel": now_iso() if stream_enabled else None,
+ "DeletionProtectionEnabled": props.get("DeletionProtectionEnabled", False),
+ "SSEDescription": None,
+ "Tags": [],
+ }
+ _dynamodb._tables[name] = table
+
+ attrs = {"Arn": arn}
+ if stream_arn:
+ attrs["StreamArn"] = stream_arn
+ return name, attrs
+
+
+def _ddb_delete(physical_id, props):
+ _dynamodb._tables.pop(physical_id, None)
+
+
+# --- Lambda Function ---
+
+def _lambda_create(logical_id, props, stack_name):
+ name = props.get("FunctionName") or f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
+ arn = f"arn:aws:lambda:{REGION}:{ACCOUNT_ID}:function:{name}"
+ runtime = props.get("Runtime", "python3.9")
+ handler = props.get("Handler", "index.handler")
+ role = props.get("Role", f"arn:aws:iam::{ACCOUNT_ID}:role/dummy-role")
+ timeout = int(props.get("Timeout", 3))
+ memory = int(props.get("MemorySize", 128))
+ env_vars = props.get("Environment", {}).get("Variables", {})
+ description = props.get("Description", "")
+ layers = props.get("Layers", [])
+ code = props.get("Code", {})
+
+ func = {
+ "config": {
+ "FunctionName": name,
+ "FunctionArn": arn,
+ "Runtime": runtime,
+ "Role": role,
+ "Handler": handler,
+ "Description": description,
+ "Timeout": timeout,
+ "MemorySize": memory,
+ "LastModified": now_iso(),
+ "CodeSha256": "cfn-deployed",
+ "Version": "$LATEST",
+ "Environment": {"Variables": env_vars},
+ "Layers": [{"Arn": l} if isinstance(l, str) else l for l in layers],
+ "State": "Active",
+ "LastUpdateStatus": "Successful",
+ "PackageType": "Zip",
+ "Architectures": props.get("Architectures", ["x86_64"]),
+ "EphemeralStorage": {"Size": props.get("EphemeralStorage", {}).get("Size", 512)},
+ "TracingConfig": props.get("TracingConfig", {"Mode": "PassThrough"}),
+ "RevisionId": new_uuid(),
+ },
+ "code_zip": None,
+ "code_s3_bucket": code.get("S3Bucket"),
+ "code_s3_key": code.get("S3Key"),
+ "versions": {},
+ "next_version": 1,
+ "tags": {},
+ "policy": {"Version": "2012-10-17", "Id": "default", "Statement": []},
+ "aliases": {},
+ "concurrency": None,
+ "provisioned_concurrency": {},
+ }
+ _lambda_svc._functions[name] = func
+ return name, {"Arn": arn}
+
+
+def _lambda_delete(physical_id, props):
+ _lambda_svc._functions.pop(physical_id, None)
+
+
+# --- IAM Role ---
+
+def _iam_role_create(logical_id, props, stack_name):
+ name = props.get("RoleName") or f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
+ arn = f"arn:aws:iam::{ACCOUNT_ID}:role/{name}"
+ role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()
+ assume_doc = props.get("AssumeRolePolicyDocument", {})
+ if isinstance(assume_doc, dict):
+ assume_doc = json.dumps(assume_doc)
+
+ role = {
+ "RoleName": name,
+ "Arn": arn,
+ "RoleId": role_id,
+ "CreateDate": now_iso(),
+ "Path": props.get("Path", "/"),
+ "AssumeRolePolicyDocument": assume_doc,
+ "Description": props.get("Description", ""),
+ "MaxSessionDuration": int(props.get("MaxSessionDuration", 3600)),
+ "AttachedPolicies": [],
+ "InlinePolicies": {},
+ "Tags": [],
+ }
+
+ # ManagedPolicyArns
+ managed = props.get("ManagedPolicyArns", [])
+ for policy_arn in managed:
+ role["AttachedPolicies"].append({
+ "PolicyName": policy_arn.split("/")[-1],
+ "PolicyArn": policy_arn,
+ })
+
+ # Inline Policies
+ policies = props.get("Policies", [])
+ for pol in policies:
+ pol_name = pol.get("PolicyName", "")
+ pol_doc = pol.get("PolicyDocument", {})
+ if isinstance(pol_doc, dict):
+ pol_doc = json.dumps(pol_doc)
+ role["InlinePolicies"][pol_name] = pol_doc
+
+ # Tags
+ tags = props.get("Tags", [])
+ for t in tags:
+ role["Tags"].append({"Key": t.get("Key", ""), "Value": t.get("Value", "")})
+
+ _iam_sts._roles[name] = role
+ return name, {"Arn": arn, "RoleId": role_id}
+
+
+def _iam_role_delete(physical_id, props):
+ _iam_sts._roles.pop(physical_id, None)
+
+
+# --- IAM Policy ---
+
+def _iam_policy_create(logical_id, props, stack_name):
+ name = props.get("PolicyName") or f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
+ path = props.get("Path", "/")
+ arn = f"arn:aws:iam::{ACCOUNT_ID}:policy{path}{name}"
+ pol_doc = props.get("PolicyDocument", {})
+ if isinstance(pol_doc, dict):
+ pol_doc = json.dumps(pol_doc)
+
+ policy = {
+ "PolicyName": name,
+ "PolicyId": new_uuid().replace("-", "")[:21].upper(),
+ "Arn": arn,
+ "Path": path,
+ "DefaultVersionId": "v1",
+ "AttachmentCount": 0,
+ "IsAttachable": True,
+ "CreateDate": now_iso(),
+ "UpdateDate": now_iso(),
+ "Description": props.get("Description", ""),
+ "Versions": [{
+ "VersionId": "v1",
+ "IsDefaultVersion": True,
+ "Document": pol_doc,
+ "CreateDate": now_iso(),
+ }],
+ "Tags": [],
+ }
+ _iam_sts._policies[arn] = policy
+
+ # Attach to roles if Roles property specified
+ roles = props.get("Roles", [])
+ for role_name in roles:
+ role = _iam_sts._roles.get(role_name)
+ if role:
+ role["AttachedPolicies"].append({
+ "PolicyName": name,
+ "PolicyArn": arn,
+ })
+ policy["AttachmentCount"] += 1
+
+ return arn, {"PolicyArn": arn}
+
+
+def _iam_policy_delete(physical_id, props):
+ _iam_sts._policies.pop(physical_id, None)
+
+
+# --- IAM InstanceProfile ---
+
+def _iam_ip_create(logical_id, props, stack_name):
+ name = props.get("InstanceProfileName") or f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
+ path = props.get("Path", "/")
+ arn = f"arn:aws:iam::{ACCOUNT_ID}:instance-profile{path}{name}"
+ ip_id = new_uuid().replace("-", "")[:21].upper()
+
+ roles = []
+ for rname in props.get("Roles", []):
+ role = _iam_sts._roles.get(rname)
+ if role:
+ roles.append(role)
+
+ profile = {
+ "InstanceProfileName": name,
+ "InstanceProfileId": ip_id,
+ "Arn": arn,
+ "Path": path,
+ "Roles": roles,
+ "CreateDate": now_iso(),
+ "Tags": [],
+ }
+ _iam_sts._instance_profiles[name] = profile
+ return arn, {"Arn": arn}
+
+
+def _iam_ip_delete(physical_id, props):
+ # physical_id is the ARN -- find the name
+ for name, ip in list(_iam_sts._instance_profiles.items()):
+ if ip.get("Arn") == physical_id:
+ _iam_sts._instance_profiles.pop(name, None)
+ return
+
+
+# --- SSM Parameter ---
+
+def _ssm_create(logical_id, props, stack_name):
+ name = props.get("Name") or f"/{stack_name}/{logical_id}"
+ ptype = props.get("Type", "String")
+ value = props.get("Value", "")
+ description = props.get("Description", "")
+ # ARN: no extra slash if name starts with /
+ param_arn = f"arn:aws:ssm:{REGION}:{ACCOUNT_ID}:parameter{name}"
+
+ now = now_iso()
+ _ssm._parameters[name] = {
+ "Name": name,
+ "Type": ptype,
+ "Value": value,
+ "Version": 1,
+ "LastModifiedDate": now,
+ "ARN": param_arn,
+ "DataType": "text",
+ "Description": description,
+ "Tier": props.get("Tier", "Standard"),
+ "AllowedPattern": props.get("AllowedPattern", ""),
+ "Tags": [],
+ }
+ return name, {"Type": ptype, "Value": value}
+
+
+def _ssm_delete(physical_id, props):
+ _ssm._parameters.pop(physical_id, None)
+
+
+# --- CloudWatch Logs LogGroup ---
+
+def _cwlogs_create(logical_id, props, stack_name):
+ name = props.get("LogGroupName") or f"/aws/cloudformation/{stack_name}/{logical_id}"
+ arn = f"arn:aws:logs:{REGION}:{ACCOUNT_ID}:log-group:{name}:*"
+ retention = props.get("RetentionInDays")
+
+ _cw_logs._log_groups[name] = {
+ "arn": arn,
+ "creationTime": int(time.time() * 1000),
+ "retentionInDays": int(retention) if retention else None,
+ "tags": {},
+ "streams": {},
+ "subscriptionFilters": {},
+ }
+ return name, {"Arn": arn}
+
+
+def _cwlogs_delete(physical_id, props):
+ _cw_logs._log_groups.pop(physical_id, None)
+
+
+# --- EventBridge Rule ---
+
+def _eb_rule_create(logical_id, props, stack_name):
+ name = props.get("Name") or f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
+ bus = props.get("EventBusName", "default")
+ key = f"{name}|{bus}"
+ arn = f"arn:aws:events:{REGION}:{ACCOUNT_ID}:rule/{bus}/{name}"
+
+ _eb._rules[key] = {
+ "Name": name,
+ "Arn": arn,
+ "EventBusName": bus,
+ "State": props.get("State", "ENABLED"),
+ "Description": props.get("Description", ""),
+ "ScheduleExpression": props.get("ScheduleExpression", ""),
+ "EventPattern": json.dumps(props["EventPattern"]) if isinstance(props.get("EventPattern"), dict) else props.get("EventPattern", ""),
+ "RoleArn": props.get("RoleArn", ""),
+ }
+
+ targets = props.get("Targets", [])
+ _eb._targets[key] = []
+ for t in targets:
+ _eb._targets[key].append({
+ "Id": t.get("Id", ""),
+ "Arn": t.get("Arn", ""),
+ "RoleArn": t.get("RoleArn", ""),
+ "Input": t.get("Input", ""),
+ "InputPath": t.get("InputPath", ""),
+ })
+
+ return name, {"Arn": arn}
+
+
+def _eb_rule_delete(physical_id, props):
+ bus = props.get("EventBusName", "default")
+ key = f"{physical_id}|{bus}"
+ _eb._rules.pop(key, None)
+ _eb._targets.pop(key, None)
+
+
+# ===========================================================================
+# Resource Handler Registry
+# ===========================================================================
+
+_RESOURCE_HANDLERS = {
+ "AWS::S3::Bucket": {"create": _s3_create, "delete": _s3_delete},
+ "AWS::SQS::Queue": {"create": _sqs_create, "delete": _sqs_delete},
+ "AWS::SNS::Topic": {"create": _sns_create, "delete": _sns_delete},
+ "AWS::SNS::Subscription": {"create": _sns_sub_create, "delete": _sns_sub_delete},
+ "AWS::DynamoDB::Table": {"create": _ddb_create, "delete": _ddb_delete},
+ "AWS::Lambda::Function": {"create": _lambda_create, "delete": _lambda_delete},
+ "AWS::IAM::Role": {"create": _iam_role_create, "delete": _iam_role_delete},
+ "AWS::IAM::Policy": {"create": _iam_policy_create, "delete": _iam_policy_delete},
+ "AWS::IAM::InstanceProfile": {"create": _iam_ip_create, "delete": _iam_ip_delete},
+ "AWS::SSM::Parameter": {"create": _ssm_create, "delete": _ssm_delete},
+ "AWS::Logs::LogGroup": {"create": _cwlogs_create, "delete": _cwlogs_delete},
+ "AWS::Events::Rule": {"create": _eb_rule_create, "delete": _eb_rule_delete},
+}
diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.py
new file mode 100644
index 00000000..a7fac699
--- /dev/null
+++ b/ministack/services/cloudformation/stacks.py
@@ -0,0 +1,344 @@
+"""
+CloudFormation stacks — async stack lifecycle (deploy, delete, update, diff).
+"""
+
+import asyncio
+import copy
+import json
+import logging
+import time
+
+from ministack.core.responses import new_uuid, now_iso
+
+from .engine import (
+ _evaluate_conditions, _parse_template, _resolve_parameters,
+ _resolve_refs, _topological_sort, _NO_VALUE,
+)
+from .provisioners import _provision_resource, _delete_resource, ACCOUNT_ID, REGION
+
+logger = logging.getLogger("cloudformation")
+
+
+# ===========================================================================
+# Stack Events helper
+# ===========================================================================
+
+def _add_event(stack_id, stack_name, logical_id, resource_type, status,
+ reason="", physical_id=""):
+ """Record a stack event."""
+ from ministack.services.cloudformation import _stack_events
+ event = {
+ "StackId": stack_id,
+ "StackName": stack_name,
+ "EventId": new_uuid(),
+ "LogicalResourceId": logical_id,
+ "PhysicalResourceId": physical_id,
+ "ResourceType": resource_type,
+ "ResourceStatus": status,
+ "ResourceStatusReason": reason,
+ "Timestamp": now_iso(),
+ }
+ if stack_id not in _stack_events:
+ _stack_events[stack_id] = []
+ _stack_events[stack_id].append(event)
+
+
+# ===========================================================================
+# Stack Deploy / Delete / Update Logic
+# ===========================================================================
+
+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,
+ previous_stack: dict | None = None):
+ """Background task: provision resources and set final stack status."""
+ from ministack.services.cloudformation import _stacks, _exports
+ status_prefix = "UPDATE" if is_update else "CREATE"
+ stack = _stacks[stack_name]
+
+ mappings = template.get("Mappings", {})
+ conditions = _evaluate_conditions(template, param_values)
+ resources_defs = template.get("Resources", {})
+ outputs_defs = template.get("Outputs", {})
+
+ # Topological sort
+ try:
+ ordered = _topological_sort(resources_defs, conditions)
+ except ValueError as exc:
+ stack["StackStatus"] = f"{status_prefix}_FAILED"
+ stack["StackStatusReason"] = str(exc)
+ _add_event(stack_id, stack_name, stack_name,
+ "AWS::CloudFormation::Stack", f"{status_prefix}_FAILED",
+ str(exc), stack_id)
+ return
+
+ provisioned_resources: dict = stack.get("_resources", {})
+ created_in_this_run = []
+
+ # If update: figure out what to add/modify/remove
+ if is_update and previous_stack:
+ old_resource_names = set(previous_stack.get("_resources", {}).keys())
+ new_resource_names = set(ordered)
+ to_remove = old_resource_names - new_resource_names
+ else:
+ to_remove = set()
+
+ failed = False
+ fail_reason = ""
+
+ for logical_id in ordered:
+ res_def = resources_defs[logical_id]
+ cond = res_def.get("Condition")
+ if cond and not conditions.get(cond, True):
+ continue
+
+ resource_type = res_def.get("Type", "AWS::CloudFormation::CustomResource")
+ raw_props = res_def.get("Properties", {})
+
+ try:
+ # Resolve properties
+ resolved_props = _resolve_refs(
+ copy.deepcopy(raw_props), provisioned_resources, param_values,
+ conditions, mappings, stack_name, stack_id
+ )
+ # Filter out _NO_VALUE properties at top level
+ if isinstance(resolved_props, dict):
+ resolved_props = {
+ k: v for k, v in resolved_props.items() if v is not _NO_VALUE
+ }
+
+ _add_event(stack_id, stack_name, logical_id, resource_type,
+ f"{status_prefix}_IN_PROGRESS")
+
+ physical_id, attrs = _provision_resource(
+ resource_type, logical_id, resolved_props, stack_name
+ )
+ except Exception as exc:
+ logger.error("Failed to provision %s (%s): %s",
+ logical_id, resource_type, exc)
+ _add_event(stack_id, stack_name, logical_id, resource_type,
+ f"{status_prefix}_FAILED", str(exc))
+ failed = True
+ fail_reason = f"Resource {logical_id} failed: {exc}"
+ break
+
+ provisioned_resources[logical_id] = {
+ "PhysicalResourceId": physical_id,
+ "ResourceType": resource_type,
+ "ResourceStatus": f"{status_prefix}_COMPLETE",
+ "LogicalResourceId": logical_id,
+ "Properties": resolved_props,
+ "Attributes": attrs,
+ "Timestamp": now_iso(),
+ }
+ created_in_this_run.append(logical_id)
+
+ _add_event(stack_id, stack_name, logical_id, resource_type,
+ f"{status_prefix}_COMPLETE", physical_id=physical_id)
+
+ # Delete removed resources (update case)
+ if not failed and to_remove:
+ old_resources = previous_stack.get("_resources", {})
+ for logical_id in to_remove:
+ old_res = old_resources.get(logical_id, {})
+ rtype = old_res.get("ResourceType", "")
+ pid = old_res.get("PhysicalResourceId", "")
+ old_props = old_res.get("Properties", {})
+ try:
+ _delete_resource(rtype, pid, old_props)
+ except Exception as exc:
+ logger.warning("Failed to delete old resource %s: %s",
+ logical_id, exc)
+ provisioned_resources.pop(logical_id, None)
+
+ # Delay for realistic async behavior
+ await asyncio.sleep(1.5)
+
+ if failed:
+ if disable_rollback:
+ stack["StackStatus"] = f"{status_prefix}_FAILED"
+ stack["StackStatusReason"] = fail_reason
+ _add_event(stack_id, stack_name, stack_name,
+ "AWS::CloudFormation::Stack", f"{status_prefix}_FAILED",
+ fail_reason, stack_id)
+ else:
+ # Rollback: delete resources created in this run in reverse order
+ stack["StackStatus"] = "ROLLBACK_IN_PROGRESS" if not is_update else "UPDATE_ROLLBACK_IN_PROGRESS"
+ _add_event(stack_id, stack_name, stack_name,
+ "AWS::CloudFormation::Stack", stack["StackStatus"],
+ "Rollback requested", stack_id)
+
+ for logical_id in reversed(created_in_this_run):
+ res = provisioned_resources.get(logical_id, {})
+ rtype = res.get("ResourceType", "")
+ pid = res.get("PhysicalResourceId", "")
+ res_props = res.get("Properties", {})
+ try:
+ _delete_resource(rtype, pid, res_props)
+ _add_event(stack_id, stack_name, logical_id, rtype,
+ "DELETE_COMPLETE", physical_id=pid)
+ except Exception as del_exc:
+ logger.warning("Rollback delete of %s failed: %s",
+ logical_id, del_exc)
+ _add_event(stack_id, stack_name, logical_id, rtype,
+ "DELETE_FAILED", str(del_exc), pid)
+ provisioned_resources.pop(logical_id, None)
+
+ if is_update and previous_stack:
+ # Restore previous resources
+ stack["_resources"] = previous_stack.get("_resources", {})
+ stack["_template"] = previous_stack.get("_template", {})
+ stack["_resolved_params"] = previous_stack.get("_resolved_params", {})
+ stack["Outputs"] = previous_stack.get("Outputs", [])
+ stack["StackStatus"] = "UPDATE_ROLLBACK_COMPLETE"
+ else:
+ stack["StackStatus"] = "ROLLBACK_COMPLETE"
+ _add_event(stack_id, stack_name, stack_name,
+ "AWS::CloudFormation::Stack", stack["StackStatus"],
+ "Rollback complete", stack_id)
+ return
+
+ # Success: resolve outputs
+ 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)
+
+ stack["Outputs"] = resolved_outputs
+ stack["StackStatus"] = f"{status_prefix}_COMPLETE"
+ _add_event(stack_id, stack_name, stack_name,
+ "AWS::CloudFormation::Stack", f"{status_prefix}_COMPLETE",
+ physical_id=stack_id)
+
+
+async def _delete_stack_async(stack_name: str, stack_id: str):
+ """Background task: delete all resources and mark stack DELETE_COMPLETE."""
+ from ministack.services.cloudformation import _stacks, _exports
+ stack = _stacks.get(stack_name)
+ if not stack:
+ return
+
+ stack["StackStatus"] = "DELETE_IN_PROGRESS"
+ _add_event(stack_id, stack_name, stack_name,
+ "AWS::CloudFormation::Stack", "DELETE_IN_PROGRESS",
+ physical_id=stack_id)
+
+ # Export-in-use check already done synchronously in _delete_stack
+
+ resources = stack.get("_resources", {})
+ template = stack.get("_template", {})
+ res_defs = template.get("Resources", {}) if template else {}
+ conditions = stack.get("_conditions", {})
+
+ # Delete in reverse dependency order
+ try:
+ ordered = _topological_sort(res_defs, conditions) if res_defs else list(resources.keys())
+ except ValueError:
+ ordered = list(resources.keys())
+
+ for logical_id in reversed(ordered):
+ res = resources.get(logical_id)
+ if not res:
+ continue
+ rtype = res.get("ResourceType", "")
+ pid = res.get("PhysicalResourceId", "")
+ res_props = res.get("Properties", {})
+
+ _add_event(stack_id, stack_name, logical_id, rtype,
+ "DELETE_IN_PROGRESS", physical_id=pid)
+ try:
+ _delete_resource(rtype, pid, res_props)
+ _add_event(stack_id, stack_name, logical_id, rtype,
+ "DELETE_COMPLETE", physical_id=pid)
+ except Exception as exc:
+ logger.warning("Delete of %s (%s) failed: %s", logical_id, pid, exc)
+ _add_event(stack_id, stack_name, logical_id, rtype,
+ "DELETE_FAILED", str(exc), pid)
+
+ # Remove exports
+ for out in stack.get("Outputs", []):
+ export_name = out.get("ExportName")
+ if export_name:
+ _exports.pop(export_name, None)
+
+ await asyncio.sleep(1.5)
+
+ stack["StackStatus"] = "DELETE_COMPLETE"
+ _add_event(stack_id, stack_name, stack_name,
+ "AWS::CloudFormation::Stack", "DELETE_COMPLETE",
+ physical_id=stack_id)
+
+
+# ===========================================================================
+# Change Set Helpers
+# ===========================================================================
+
+def _diff_resources(old_template: dict, new_template: dict) -> list:
+ """Diff two templates and return a list of change dicts."""
+ old_res = old_template.get("Resources", {})
+ new_res = new_template.get("Resources", {})
+ changes = []
+
+ all_keys = old_res.keys() | new_res.keys()
+ for key in sorted(all_keys):
+ if key not in old_res:
+ changes.append({
+ "ResourceChange": {
+ "Action": "Add",
+ "LogicalResourceId": key,
+ "ResourceType": new_res[key].get("Type", ""),
+ "Replacement": "False",
+ }
+ })
+ elif key not in new_res:
+ changes.append({
+ "ResourceChange": {
+ "Action": "Remove",
+ "LogicalResourceId": key,
+ "ResourceType": old_res[key].get("Type", ""),
+ "PhysicalResourceId": "",
+ "Replacement": "False",
+ }
+ })
+ else:
+ old_props = old_res[key].get("Properties", {})
+ new_props = new_res[key].get("Properties", {})
+ if old_props != new_props:
+ changes.append({
+ "ResourceChange": {
+ "Action": "Modify",
+ "LogicalResourceId": key,
+ "ResourceType": new_res[key].get("Type", ""),
+ "Replacement": "Conditional",
+ }
+ })
+ return changes
diff --git a/pyproject.toml b/pyproject.toml
index 49a73024..a396ad9e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -24,6 +24,7 @@ classifiers = [
dependencies = [
"uvicorn[standard]>=0.30.6",
"httptools>=0.6.1",
+ "pyyaml>=6.0",
]
[project.optional-dependencies]
@@ -38,6 +39,7 @@ dev = [
"duckdb>=0.10.0",
"docker>=7.0.0",
"ruff>=0.4",
+ "hypothesis>=6.0",
]
[project.urls]
diff --git a/tests/conftest.py b/tests/conftest.py
index 88a0315d..4316a9fb 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -187,6 +187,10 @@ def wafv2():
def sesv2():
return make_client("sesv2")
[email protected](scope="session")
+def cfn():
+ return make_client("cloudformation")
+
@pytest.fixture(scope="session")
def sfn_sync():
"""SFN client for StartSyncExecution — forces same endpoint (boto3 normally prefixes sync-)."""
diff --git a/tests/test_cfn_e2e.py b/tests/test_cfn_e2e.py
new file mode 100644
index 00000000..5e456492
--- /dev/null
+++ b/tests/test_cfn_e2e.py
@@ -0,0 +1,292 @@
+"""
+End-to-end test: deploy a CloudFormation stack and use every resource it creates.
+
+Verifies that CFN-provisioned resources are fully functional — not just metadata
+stubs but real working S3 buckets, SQS queues, SNS topics, Lambda functions, etc.
+
+Requires a running ministack server on MINISTACK_ENDPOINT (default localhost:4566).
+"""
+
+import json
+import os
+import time
+
+import boto3
+import pytest
+from botocore.config import Config
+from botocore.exceptions import ClientError
+
+ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+STACK_NAME = "e2e-test"
+
+_kwargs = dict(
+ endpoint_url=ENDPOINT,
+ aws_access_key_id="test",
+ aws_secret_access_key="test",
+ region_name="us-east-1",
+ config=Config(region_name="us-east-1", retries={"max_attempts": 0}),
+)
+
+
+def _client(service):
+ return boto3.client(service, **_kwargs)
+
+
+def _wait_stack(cfn, name, timeout=15):
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ stacks = cfn.describe_stacks(StackName=name)["Stacks"]
+ status = stacks[0]["StackStatus"]
+ if not status.endswith("_IN_PROGRESS"):
+ return stacks[0]
+ time.sleep(0.5)
+ raise TimeoutError(f"Stack {name} stuck at {status}")
+
+
+TEMPLATE = """
+AWSTemplateFormatVersion: '2010-09-09'
+Description: E2E test stack — verifies CFN resources are functional
+
+Parameters:
+ Env:
+ Type: String
+ Default: e2etest
+
+Resources:
+ Bucket:
+ Type: AWS::S3::Bucket
+ Properties:
+ BucketName: !Sub "${AWS::StackName}-${Env}-assets"
+
+ Queue:
+ Type: AWS::SQS::Queue
+ Properties:
+ QueueName: !Sub "${AWS::StackName}-${Env}-events"
+ VisibilityTimeout: 120
+
+ Topic:
+ Type: AWS::SNS::Topic
+ Properties:
+ TopicName: !Sub "${AWS::StackName}-${Env}-alerts"
+
+ Role:
+ Type: AWS::IAM::Role
+ Properties:
+ RoleName: !Sub "${AWS::StackName}-${Env}-role"
+ AssumeRolePolicyDocument:
+ Version: '2012-10-17'
+ Statement:
+ - Effect: Allow
+ Principal:
+ Service: lambda.amazonaws.com
+ Action: sts:AssumeRole
+
+ Processor:
+ Type: AWS::Lambda::Function
+ Properties:
+ FunctionName: !Sub "${AWS::StackName}-${Env}-processor"
+ Runtime: python3.12
+ Handler: index.handler
+ Role: !GetAtt Role.Arn
+ Code:
+ ZipFile: |
+ def handler(event, context):
+ return {"statusCode": 200}
+
+ QueueUrlParam:
+ Type: AWS::SSM::Parameter
+ Properties:
+ Name: !Sub "/${AWS::StackName}/${Env}/queue-url"
+ Type: String
+ Value: !Ref Queue
+
+Outputs:
+ BucketName:
+ Value: !Ref Bucket
+ Export:
+ Name: !Sub "${AWS::StackName}-bucket"
+ QueueUrl:
+ Value: !Ref Queue
+ TopicArn:
+ Value: !Ref Topic
+ ProcessorArn:
+ Value: !GetAtt Processor.Arn
+ RoleArn:
+ Value: !GetAtt Role.Arn
+"""
+
+
[email protected](scope="module")
+def stack():
+ """Deploy the stack once for all tests in this module."""
+ cfn = _client("cloudformation")
+
+ # Clean up from previous run
+ try:
+ cfn.delete_stack(StackName=STACK_NAME)
+ _wait_stack(cfn, STACK_NAME)
+ except ClientError:
+ pass
+
+ cfn.create_stack(StackName=STACK_NAME, TemplateBody=TEMPLATE)
+ s = _wait_stack(cfn, STACK_NAME)
+ assert s["StackStatus"] == "CREATE_COMPLETE", f"Stack failed: {s.get('StackStatusReason')}"
+
+ outputs = {o["OutputKey"]: o["OutputValue"] for o in s.get("Outputs", [])}
+ yield outputs
+
+ cfn.delete_stack(StackName=STACK_NAME)
+ _wait_stack(cfn, STACK_NAME)
+
+
+# ── S3 ──
+
+def test_s3_put_and_get(stack):
+ s3 = _client("s3")
+ bucket = stack["BucketName"]
+ body = json.dumps({"id": "001", "total": 99.99})
+
+ s3.put_object(Bucket=bucket, Key="orders/order-001.json", Body=body.encode())
+ obj = s3.get_object(Bucket=bucket, Key="orders/order-001.json")
+ data = json.loads(obj["Body"].read())
+
+ assert data["id"] == "001"
+ assert data["total"] == 99.99
+
+
+def test_s3_list_objects(stack):
+ s3 = _client("s3")
+ bucket = stack["BucketName"]
+
+ s3.put_object(Bucket=bucket, Key="docs/readme.txt", Body=b"hello")
+ listing = s3.list_objects_v2(Bucket=bucket)
+
+ assert listing["KeyCount"] >= 1
+ keys = [o["Key"] for o in listing["Contents"]]
+ assert "docs/readme.txt" in keys
+
+
+# ── SQS ──
+
+def test_sqs_send_receive_delete(stack):
+ sqs = _client("sqs")
+ url = stack["QueueUrl"]
+
+ sqs.send_message(QueueUrl=url, MessageBody=json.dumps({"event": "order.created"}))
+ sqs.send_message(QueueUrl=url, MessageBody=json.dumps({"event": "order.shipped"}))
+
+ msgs = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=10, WaitTimeSeconds=1)
+ received = msgs.get("Messages", [])
+ assert len(received) == 2
+
+ events = sorted(json.loads(m["Body"])["event"] for m in received)
+ assert events == ["order.created", "order.shipped"]
+
+ for m in received:
+ sqs.delete_message(QueueUrl=url, ReceiptHandle=m["ReceiptHandle"])
+
+ empty = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=10, WaitTimeSeconds=1)
+ assert len(empty.get("Messages", [])) == 0
+
+
+# ── SNS ──
+
+def test_sns_publish(stack):
+ sns = _client("sns")
+ topic_arn = stack["TopicArn"]
+
+ resp = sns.publish(TopicArn=topic_arn, Subject="Test Alert",
+ Message=json.dumps({"alert": "test", "severity": "low"}))
+ assert "MessageId" in resp
+
+
+# ── SSM ──
+
+def test_ssm_read_cfn_param(stack):
+ ssm = _client("ssm")
+ param = ssm.get_parameter(Name=f"/{STACK_NAME}/e2etest/queue-url")["Parameter"]
+
+ assert param["Value"] == stack["QueueUrl"]
+
+
+def test_ssm_write_and_read(stack):
+ ssm = _client("ssm")
+ ssm.put_parameter(Name=f"/{STACK_NAME}/e2etest/flags", Type="String",
+ Value=json.dumps({"dark_mode": True}))
+
+ flags = json.loads(ssm.get_parameter(Name=f"/{STACK_NAME}/e2etest/flags")["Parameter"]["Value"])
+ assert flags["dark_mode"] is True
+
+
+# ── Lambda ──
+
+def test_lambda_invoke(stack):
+ lam = _client("lambda")
+ resp = lam.invoke(FunctionName=f"{STACK_NAME}-e2etest-processor",
+ Payload=json.dumps({"action": "test"}).encode())
+ assert resp["StatusCode"] == 200
+
+
+# ── IAM wiring ──
+
+def test_lambda_role_matches_iam_role(stack):
+ lam = _client("lambda")
+ iam = _client("iam")
+
+ fn = lam.get_function(FunctionName=f"{STACK_NAME}-e2etest-processor")["Configuration"]
+ role = iam.get_role(RoleName=f"{STACK_NAME}-e2etest-role")["Role"]
+
+ assert fn["Role"] == role["Arn"]
+
+
+# ── Cross-service pipeline ──
+
+def test_e2e_pipeline(stack):
+ """S3 upload → SQS queue → read back from S3 → SNS alert."""
+ s3 = _client("s3")
+ sqs = _client("sqs")
+ sns = _client("sns")
+ bucket = stack["BucketName"]
+ url = stack["QueueUrl"]
+ topic_arn = stack["TopicArn"]
+
+ # Upload orders to S3
+ for i in range(3):
+ order = {"id": f"pipe-{i}", "item": f"widget-{i}", "qty": (i + 1) * 5}
+ s3.put_object(Bucket=bucket, Key=f"pipeline/order-{i}.json",
+ Body=json.dumps(order).encode())
+
+ # Queue processing events
+ for i in range(3):
+ sqs.send_message(QueueUrl=url,
+ MessageBody=json.dumps({"event": "process", "key": f"pipeline/order-{i}.json"}))
+
+ # Consume queue, read each order from S3
+ msgs = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=10, WaitTimeSeconds=1)
+ assert len(msgs.get("Messages", [])) == 3
+
+ total_qty = 0
+ for m in msgs["Messages"]:
+ body = json.loads(m["Body"])
+ obj = s3.get_object(Bucket=bucket, Key=body["key"])
+ order = json.loads(obj["Body"].read())
+ total_qty += order["qty"]
+ sqs.delete_message(QueueUrl=url, ReceiptHandle=m["ReceiptHandle"])
+
+ assert total_qty == 5 + 10 + 15 # 30
+
+ # Send completion alert
+ resp = sns.publish(TopicArn=topic_arn, Subject="Pipeline Done",
+ Message=json.dumps({"processed": 3, "total_qty": total_qty}))
+ assert "MessageId" in resp
+
+
+# ── Exports ──
+
+def test_cfn_exports_available(stack):
+ cfn = _client("cloudformation")
+ exports = cfn.list_exports()["Exports"]
+ names = {e["Name"]: e["Value"] for e in exports}
+
+ assert f"{STACK_NAME}-bucket" in names
+ assert names[f"{STACK_NAME}-bucket"] == stack["BucketName"]
diff --git a/tests/test_cfn_integration_properties.py b/tests/test_cfn_integration_properties.py
new file mode 100644
index 00000000..018ec646
--- /dev/null
+++ b/tests/test_cfn_integration_properties.py
@@ -0,0 +1,384 @@
+"""Hypothesis-based integration tests for the CloudFormation service.
+
+These tests run against a LIVE ministack server via boto3. They generate
+random CloudFormation templates and verify deployment invariants.
+"""
+
+import json
+import os
+import string
+import time
+import urllib.request
+
+import boto3
+import pytest
+from botocore.config import Config
+from botocore.exceptions import ClientError
+from hypothesis import given, settings, assume, HealthCheck
+import hypothesis.strategies as st
+
+from ministack.services.cloudformation import _parse_template
+
+ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+
+_kwargs = dict(
+ endpoint_url=ENDPOINT,
+ aws_access_key_id="test",
+ aws_secret_access_key="test",
+ region_name="us-east-1",
+ config=Config(region_name="us-east-1", retries={"max_attempts": 0}),
+)
+
+
+def _make_client(service):
+ return boto3.client(service, **_kwargs)
+
+
+def _wait_stack(cfn, name, timeout=25):
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ stacks = cfn.describe_stacks(StackName=name)["Stacks"]
+ status = stacks[0]["StackStatus"]
+ if not status.endswith("_IN_PROGRESS"):
+ return stacks[0]
+ time.sleep(0.5)
+ raise TimeoutError(f"Stack {name} stuck at {status}")
+
+
+def _reset_server():
+ req = urllib.request.Request(
+ f"{ENDPOINT}/_ministack/reset", data=b"", method="POST"
+ )
+ try:
+ urllib.request.urlopen(req, timeout=5)
+ except Exception:
+ pass
+
+
[email protected](autouse=True)
+def reset_between_tests():
+ _reset_server()
+
+
+# ---------------------------------------------------------------------------
+# Resource types and minimal properties
+# ---------------------------------------------------------------------------
+
+RESOURCE_TYPES = [
+ "AWS::S3::Bucket",
+ "AWS::SQS::Queue",
+ "AWS::SNS::Topic",
+ "AWS::DynamoDB::Table",
+ "AWS::Lambda::Function",
+ "AWS::IAM::Role",
+ "AWS::SSM::Parameter",
+ "AWS::Logs::LogGroup",
+ "AWS::Events::Rule",
+]
+
+TYPES_WITH_ARN = {
+ "AWS::S3::Bucket",
+ "AWS::SQS::Queue",
+ "AWS::SNS::Topic",
+ "AWS::DynamoDB::Table",
+ "AWS::Lambda::Function",
+ "AWS::IAM::Role",
+ "AWS::Logs::LogGroup",
+ "AWS::Events::Rule",
+}
+
+
+def _props_for_type(rtype, name):
+ if rtype == "AWS::S3::Bucket":
+ return {"BucketName": name}
+ elif rtype == "AWS::SQS::Queue":
+ return {"QueueName": name}
+ elif rtype == "AWS::SNS::Topic":
+ return {"TopicName": name}
+ elif rtype == "AWS::DynamoDB::Table":
+ return {
+ "TableName": name,
+ "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}],
+ "AttributeDefinitions": [
+ {"AttributeName": "id", "AttributeType": "S"}
+ ],
+ }
+ elif rtype == "AWS::Lambda::Function":
+ return {
+ "FunctionName": name,
+ "Runtime": "python3.12",
+ "Handler": "index.handler",
+ "Role": "arn:aws:iam::000000000000:role/fake",
+ "Code": {"ZipFile": "def handler(e,c): pass"},
+ }
+ elif rtype == "AWS::IAM::Role":
+ return {
+ "RoleName": name,
+ "AssumeRolePolicyDocument": {
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Effect": "Allow",
+ "Principal": {"Service": "lambda.amazonaws.com"},
+ "Action": "sts:AssumeRole",
+ }
+ ],
+ },
+ }
+ elif rtype == "AWS::SSM::Parameter":
+ return {"Name": f"/{name}", "Type": "String", "Value": "test"}
+ elif rtype == "AWS::Logs::LogGroup":
+ return {"LogGroupName": f"/{name}"}
+ elif rtype == "AWS::Events::Rule":
+ return {
+ "Name": name,
+ "ScheduleExpression": "rate(1 hour)",
+ "State": "ENABLED",
+ }
+ return {}
+
+
+# ---------------------------------------------------------------------------
+# Hypothesis strategies
+# ---------------------------------------------------------------------------
+
+
+def random_cfn_template(draw):
+ slug = draw(
+ st.text(alphabet=string.ascii_lowercase, min_size=4, max_size=6)
+ )
+ count = draw(st.integers(min_value=1, max_value=6))
+ resources = {}
+ for i in range(count):
+ rtype = draw(st.sampled_from(RESOURCE_TYPES))
+ name = f"hyp-{slug}-{i}"
+ resources[f"Res{i}"] = {
+ "Type": rtype,
+ "Properties": _props_for_type(rtype, name),
+ }
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": resources,
+ }
+ return (f"hyp-{slug}", template)
+
+
+def random_cfn_template_with_outputs(draw):
+ stack_name, template = draw(random_cfn_template())
+ outputs = {}
+ for logical_id, res in template["Resources"].items():
+ idx = logical_id.replace("Res", "")
+ outputs[f"Out{idx}Ref"] = {"Value": {"Ref": logical_id}}
+ if res["Type"] in TYPES_WITH_ARN:
+ outputs[f"Out{idx}Arn"] = {
+ "Value": {"Fn::GetAtt": [logical_id, "Arn"]}
+ }
+ template["Outputs"] = outputs
+ return (stack_name, template)
+
+
+def broken_cfn_template(draw):
+ kind = draw(st.sampled_from(["bad_type", "not_json"]))
+ slug = draw(
+ st.text(alphabet=string.ascii_lowercase, min_size=4, max_size=6)
+ )
+ stack_name = f"hyp-brk-{slug}"
+ if kind == "bad_type":
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Bad0": {
+ "Type": "AWS::Fake::DoesNotExist",
+ "Properties": {},
+ }
+ },
+ }
+ return (kind, stack_name, json.dumps(template))
+ else:
+ raw = draw(
+ st.text(
+ alphabet=string.ascii_letters + string.digits,
+ min_size=5,
+ max_size=30,
+ )
+ )
+ return (kind, stack_name, raw)
+
+
+# ---------------------------------------------------------------------------
+# Snapshot helper for cleanup verification
+# ---------------------------------------------------------------------------
+
+
+def _snapshot():
+ s3 = _make_client("s3")
+ sqs = _make_client("sqs")
+ sns = _make_client("sns")
+ ddb = _make_client("dynamodb")
+ lam = _make_client("lambda")
+ iam = _make_client("iam")
+ ssm = _make_client("ssm")
+ logs = _make_client("logs")
+ events = _make_client("events")
+ return {
+ "s3": len(s3.list_buckets()["Buckets"]),
+ "sqs": len(sqs.list_queues().get("QueueUrls", [])),
+ "sns": len(sns.list_topics()["Topics"]),
+ "dynamodb": len(ddb.list_tables()["TableNames"]),
+ "lambda": len(lam.list_functions()["Functions"]),
+ "iam_roles": len(
+ [
+ r
+ for r in iam.list_roles()["Roles"]
+ if r["RoleName"].startswith("hyp-")
+ ]
+ ),
+ "ssm": len(ssm.describe_parameters()["Parameters"]),
+ "logs": len(logs.describe_log_groups()["logGroups"]),
+ "events": len(events.list_rules()["Rules"]),
+ }
+
+
+# ---------------------------------------------------------------------------
+# Tests
+# ---------------------------------------------------------------------------
+
+
+@given(random_cfn_template())
+@settings(max_examples=100)
+def test_generator_produces_valid_templates(data):
+ """Generator produces structurally valid templates (no server)."""
+ stack_name, template = data
+ assert "Resources" in template
+ assert len(template["Resources"]) >= 1
+ for res in template["Resources"].values():
+ assert res["Type"] in RESOURCE_TYPES
+ parsed = _parse_template(json.dumps(template))
+ assert "Resources" in parsed
+
+
+@given(random_cfn_template())
+@settings(
+ max_examples=20,
+ deadline=45000,
+ suppress_health_check=[HealthCheck.too_slow],
+)
+def test_all_resources_tracked_in_stack(data):
+ """Every template resource appears in describe_stack_resources."""
+ cfn = _make_client("cloudformation")
+ stack_name, template = data
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, stack_name)
+ assume(stack["StackStatus"] == "CREATE_COMPLETE")
+ resources = cfn.describe_stack_resources(StackName=stack_name)[
+ "StackResources"
+ ]
+ template_ids = set(template["Resources"].keys())
+ stack_ids = {r["LogicalResourceId"] for r in resources}
+ assert template_ids == stack_ids
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+
+
+@given(random_cfn_template())
+@settings(
+ max_examples=15,
+ deadline=60000,
+ suppress_health_check=[HealthCheck.too_slow],
+)
+def test_delete_cleans_up_all_resources(data):
+ """Deleting a stack leaves service state unchanged."""
+ cfn = _make_client("cloudformation")
+ stack_name, template = data
+ before = _snapshot()
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, stack_name)
+ assume(stack["StackStatus"] == "CREATE_COMPLETE")
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+ after = _snapshot()
+ assert before == after, (
+ f"Resource leak detected: before={before}, after={after}"
+ )
+
+
+@given(random_cfn_template_with_outputs())
+@settings(
+ max_examples=20,
+ deadline=45000,
+ suppress_health_check=[HealthCheck.too_slow],
+)
+def test_outputs_resolve_to_nonempty(data):
+ """All declared Outputs resolve to non-empty values."""
+ cfn = _make_client("cloudformation")
+ stack_name, template = data
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, stack_name)
+ assume(stack["StackStatus"] == "CREATE_COMPLETE")
+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack.get("Outputs", [])}
+ expected_keys = set(template["Outputs"].keys())
+ assert expected_keys == set(outputs.keys()), (
+ f"Missing outputs: {expected_keys - set(outputs.keys())}"
+ )
+ for key, value in outputs.items():
+ assert value, f"Output {key} resolved to empty"
+ assert "${" not in value, f"Output {key} contains unresolved placeholder: {value}"
+ if key.endswith("Arn"):
+ assert value.startswith("arn:aws:"), (
+ f"Output {key} should be an ARN, got: {value}"
+ )
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+
+
+@given(random_cfn_template())
+@settings(
+ max_examples=20,
+ deadline=45000,
+ suppress_health_check=[HealthCheck.too_slow],
+)
+def test_stack_events_cover_all_resources(data):
+ """Every template resource has a CREATE_COMPLETE event."""
+ cfn = _make_client("cloudformation")
+ stack_name, template = data
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, stack_name)
+ assume(stack["StackStatus"] == "CREATE_COMPLETE")
+ events = cfn.describe_stack_events(StackName=stack_name)["StackEvents"]
+ create_complete_ids = {
+ e["LogicalResourceId"]
+ for e in events
+ if e.get("ResourceStatus") == "CREATE_COMPLETE"
+ }
+ template_ids = set(template["Resources"].keys())
+ assert template_ids.issubset(create_complete_ids), (
+ f"Resources missing CREATE_COMPLETE event: {template_ids - create_complete_ids}"
+ )
+ stack_name_in_events = {e.get("StackName") for e in events}
+ assert stack_name in stack_name_in_events
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+
+
+@given(broken_cfn_template())
+@settings(
+ max_examples=20,
+ deadline=45000,
+ suppress_health_check=[HealthCheck.too_slow],
+)
+def test_invalid_templates_return_structured_errors(data):
+ """Invalid templates produce errors, not hangs."""
+ kind, stack_name, body = data
+ cfn = _make_client("cloudformation")
+ if kind == "not_json":
+ with pytest.raises(ClientError):
+ cfn.create_stack(StackName=stack_name, TemplateBody=body)
+ elif kind == "bad_type":
+ cfn.create_stack(StackName=stack_name, TemplateBody=body)
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] in ("CREATE_FAILED", "ROLLBACK_COMPLETE"), (
+ f"Expected terminal failure status, got: {stack['StackStatus']}"
+ )
diff --git a/tests/test_cfn_properties.py b/tests/test_cfn_properties.py
new file mode 100644
index 00000000..eaaa1165
--- /dev/null
+++ b/tests/test_cfn_properties.py
@@ -0,0 +1,268 @@
+"""Hypothesis property-based tests for CloudFormation engine pure functions."""
+
+import json
+import string
+import re
+
+import pytest
+from hypothesis import given, settings, assume
+import hypothesis.strategies as st
+
+from ministack.services.cloudformation import (
+ _parse_template,
+ _validate_template,
+ _resolve_parameters,
+ _evaluate_conditions,
+ _resolve_refs,
+ _extract_deps,
+ _topological_sort,
+ _NO_VALUE,
+)
+
+# ---------------------------------------------------------------------------
+# Shared constants
+# ---------------------------------------------------------------------------
+STACK_NAME = "test"
+STACK_ID = "arn:aws:cloudformation:us-east-1:000000000000:stack/test/uuid"
+EMPTY_RESOURCES: dict = {}
+EMPTY_PARAMS: dict = {}
+EMPTY_CONDITIONS: dict = {}
+EMPTY_MAPPINGS: dict = {}
+
+# Intrinsic function key prefixes to filter out
+_INTRINSIC_PREFIXES = ("Ref", "Fn::Join", "Fn::Sub", "Fn::Select", "Fn::Split",
+ "Fn::If", "Fn::Base64", "Fn::FindInMap", "Fn::GetAtt",
+ "Fn::GetAZs", "Fn::Cidr", "Fn::ImportValue", "Fn::Equals",
+ "Fn::And", "Fn::Or", "Fn::Not", "Condition")
+
+def _has_intrinsic_keys(obj):
+ """Return True if obj (or any nested value) contains intrinsic function keys."""
+ if isinstance(obj, dict):
+ for key in obj:
+ if key in _INTRINSIC_PREFIXES or key.startswith("Fn::"):
+ return True
+ if _has_intrinsic_keys(obj[key]):
+ return True
+ elif isinstance(obj, list):
+ return any(_has_intrinsic_keys(item) for item in obj)
+ return False
+
+# ---------------------------------------------------------------------------
+# Shared strategies
+# ---------------------------------------------------------------------------
+_json_values = st.recursive(
+ st.text(min_size=0, max_size=20) | st.integers(-1000, 1000) | st.booleans(),
+ lambda children: (
+ st.lists(children, max_size=5)
+ | st.dictionaries(
+ st.text(alphabet=string.ascii_letters, min_size=1, max_size=8),
+ children,
+ max_size=5,
+ )
+ ),
+ max_leaves=20,
+)
+
+def random_dag(draw):
+ """Generate a random DAG as a CloudFormation resources dict.
+
+ Resources are named R0..R(N-1). Edges go from higher-index to lower-index
+ only (j depends on i where i < j), guaranteeing acyclicity.
+ """
+ n = draw(st.integers(min_value=2, max_value=15))
+ resources = {}
+ for j in range(n):
+ deps = []
+ for i in range(j):
+ if draw(st.booleans()):
+ deps.append(f"R{i}")
+ defn = {"Type": "AWS::CloudFormation::WaitConditionHandle"}
+ if deps:
+ defn["DependsOn"] = deps
+ resources[f"R{j}"] = defn
+ return resources
+
+def cyclic_resources(draw):
+ """Generate resources with a guaranteed circular dependency (ring)."""
+ n = draw(st.integers(min_value=3, max_value=8))
+ resources = {}
+ for i in range(n):
+ dep_index = (i - 1) % n
+ resources[f"R{i}"] = {
+ "Type": "AWS::CloudFormation::WaitConditionHandle",
+ "DependsOn": [f"R{dep_index}"],
+ }
+ return resources
+
+@given(
+ st.dictionaries(
+ st.text(alphabet=string.ascii_letters, min_size=1, max_size=8),
+ _json_values,
+ min_size=1,
+ max_size=5,
+ )
+)
+@settings(max_examples=100)
+def test_ht001_parse_template_json_roundtrip(d):
+ d["Resources"] = {}
+ raw = json.dumps(d)
+ parsed = _parse_template(raw)
+ for key in d:
+ assert key in parsed, f"Key {key!r} missing after parse"
+
+@given(_json_values)
+@settings(max_examples=100)
+def test_ht002_resolve_refs_identity_on_plain_values(value):
+ assume(not _has_intrinsic_keys(value))
+ result = _resolve_refs(
+ value, EMPTY_RESOURCES, EMPTY_PARAMS, EMPTY_CONDITIONS,
+ EMPTY_MAPPINGS, STACK_NAME, STACK_ID,
+ )
+ assert result == value
+
+@given(random_dag())
+@settings(max_examples=100)
+def test_ht003_topo_sort_all_resources_present(resources):
+ order = _topological_sort(resources, {})
+ assert set(order) == set(resources.keys())
+
+@given(random_dag())
+@settings(max_examples=100)
+def test_ht004_topo_sort_deps_respected(resources):
+ order = _topological_sort(resources, {})
+ for name, defn in resources.items():
+ deps = defn.get("DependsOn", [])
+ if isinstance(deps, str):
+ deps = [deps]
+ for dep in deps:
+ assert order.index(dep) < order.index(name), (
+ f"{dep} should come before {name} in topological order"
+ )
+
+@given(random_dag())
+@settings(max_examples=100)
+def test_ht005_topo_sort_deterministic(resources):
+ order1 = _topological_sort(resources, {})
+ order2 = _topological_sort(resources, {})
+ assert order1 == order2
+
+@given(cyclic_resources())
+@settings(max_examples=100)
+def test_ht006_topo_sort_circular_detection(resources):
+ with pytest.raises(ValueError, match=r"(?i)circular"):
+ _topological_sort(resources, {})
+
+@given(
+ st.lists(
+ st.tuples(
+ st.text(alphabet=string.ascii_letters, min_size=1, max_size=10),
+ st.text(min_size=0, max_size=10),
+ st.text(min_size=0, max_size=10),
+ ),
+ min_size=1,
+ max_size=5,
+ )
+)
+@settings(max_examples=100)
+def test_ht007_condition_evaluator_is_pure(cond_specs):
+ conditions = {}
+ for name, left, right in cond_specs:
+ conditions[name] = {"Fn::Equals": [left, right]}
+ template = {"Conditions": conditions}
+ params: dict = {}
+ result1 = _evaluate_conditions(template, params)
+ result2 = _evaluate_conditions(template, params)
+ assert result1 == result2
+
+@given(
+ st.text(alphabet=string.ascii_letters + string.digits, min_size=1, max_size=3),
+ st.lists(
+ st.text(alphabet=string.ascii_letters + string.digits, min_size=1, max_size=10),
+ min_size=1,
+ max_size=10,
+ ),
+)
+@settings(max_examples=100)
+def test_ht008_join_split_roundtrip(delimiter, parts):
+ # Ensure no part contains the delimiter
+ assume(all(delimiter not in part for part in parts))
+
+ joined = _resolve_refs(
+ {"Fn::Join": [delimiter, parts]},
+ EMPTY_RESOURCES, EMPTY_PARAMS, EMPTY_CONDITIONS,
+ EMPTY_MAPPINGS, STACK_NAME, STACK_ID,
+ )
+ split_back = _resolve_refs(
+ {"Fn::Split": [delimiter, joined]},
+ EMPTY_RESOURCES, EMPTY_PARAMS, EMPTY_CONDITIONS,
+ EMPTY_MAPPINGS, STACK_NAME, STACK_ID,
+ )
+ assert split_back == parts
+
+@given(
+ st.lists(
+ st.text(alphabet=string.ascii_letters, min_size=1, max_size=10),
+ min_size=1,
+ max_size=20,
+ ),
+ st.data(),
+)
+@settings(max_examples=100)
+def test_ht009_fn_select_valid_index(items, data):
+ idx = data.draw(st.integers(min_value=0, max_value=len(items) - 1))
+ result = _resolve_refs(
+ {"Fn::Select": [idx, items]},
+ EMPTY_RESOURCES, EMPTY_PARAMS, EMPTY_CONDITIONS,
+ EMPTY_MAPPINGS, STACK_NAME, STACK_ID,
+ )
+ assert result == items[idx]
+
+@given(
+ st.lists(
+ st.text(alphabet=string.ascii_letters + string.digits, min_size=1, max_size=10),
+ min_size=2,
+ max_size=5,
+ unique=True,
+ ),
+ st.text(alphabet=string.ascii_letters + string.digits, min_size=1, max_size=10),
+)
+@settings(max_examples=100)
+def test_ht010_parameter_allowed_values(allowed, test_value):
+ template = {
+ "Parameters": {
+ "Param1": {
+ "Type": "String",
+ "AllowedValues": allowed,
+ }
+ }
+ }
+ provided = [{"Key": "Param1", "Value": test_value}]
+ if test_value in allowed:
+ result = _resolve_parameters(template, provided)
+ assert result["Param1"]["Value"] == test_value
+ else:
+ with pytest.raises(ValueError, match="AllowedValues"):
+ _resolve_parameters(template, provided)
+
+@given(
+ st.lists(
+ st.text(alphabet=string.ascii_letters, min_size=1, max_size=8),
+ min_size=1,
+ max_size=5,
+ unique=True,
+ ),
+)
+@settings(max_examples=100)
+def test_ht011_fn_sub_completeness(var_names):
+ template_str = " ".join(f"${{{name}}}" for name in var_names)
+ mapping = {name: f"val_{name}" for name in var_names}
+ result = _resolve_refs(
+ {"Fn::Sub": [template_str, mapping]},
+ EMPTY_RESOURCES, EMPTY_PARAMS, EMPTY_CONDITIONS,
+ EMPTY_MAPPINGS, STACK_NAME, STACK_ID,
+ )
+ assert "${" not in result, (
+ f"Unresolved substitution in result: {result!r}"
+ )
diff --git a/tests/test_services.py b/tests/test_services.py
index da696e2f..3d018e38 100644
--- a/tests/test_services.py
+++ b/tests/test_services.py
@@ -15193,3 +15193,485 @@ def test_waf_tags(wafv2):
wafv2.untag_resource(ResourceARN=arn, TagKeys=["env"])
tags_resp3 = wafv2.list_tags_for_resource(ResourceARN=arn)
assert not any(t["Key"] == "env" for t in tags_resp3["TagInfoForResource"]["TagList"])
+# ========== CloudFormation ==========
+
+
+def _wait_stack(cfn, name, timeout=10):
+ """Poll until stack reaches terminal status."""
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ stacks = cfn.describe_stacks(StackName=name)["Stacks"]
+ status = stacks[0]["StackStatus"]
+ if not status.endswith("_IN_PROGRESS"):
+ return stacks[0]
+ time.sleep(0.5)
+ raise TimeoutError(f"Stack {name} stuck at {status}")
+
+
+def test_cfn_create_describe_delete_stack(cfn, s3):
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Bucket": {
+ "Type": "AWS::S3::Bucket",
+ "Properties": {"BucketName": "cfn-t01-bucket"},
+ }
+ },
+ }
+ cfn.create_stack(StackName="cfn-t01", TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, "cfn-t01")
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+
+ s3.head_bucket(Bucket="cfn-t01-bucket")
+
+ cfn.delete_stack(StackName="cfn-t01")
+ _wait_stack(cfn, "cfn-t01")
+
+ with pytest.raises(ClientError):
+ s3.head_bucket(Bucket="cfn-t01-bucket")
+
+
+def test_cfn_stack_with_parameters(cfn, sqs):
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Parameters": {
+ "QueueName": {
+ "Type": "String",
+ "Default": "cfn-t02-default",
+ }
+ },
+ "Resources": {
+ "Queue": {
+ "Type": "AWS::SQS::Queue",
+ "Properties": {"QueueName": {"Ref": "QueueName"}},
+ }
+ },
+ }
+ cfn.create_stack(StackName="cfn-t02a", TemplateBody=json.dumps(template))
+ _wait_stack(cfn, "cfn-t02a")
+
+ urls = sqs.list_queues(QueueNamePrefix="cfn-t02-default").get("QueueUrls", [])
+ assert any("cfn-t02-default" in u for u in urls)
+
+ cfn.create_stack(
+ StackName="cfn-t02b",
+ TemplateBody=json.dumps(template),
+ Parameters=[{"ParameterKey": "QueueName", "ParameterValue": "cfn-t02-custom"}],
+ )
+ _wait_stack(cfn, "cfn-t02b")
+
+ urls = sqs.list_queues(QueueNamePrefix="cfn-t02-custom").get("QueueUrls", [])
+ assert any("cfn-t02-custom" in u for u in urls)
+
+
+def test_cfn_intrinsic_ref_getatt(cfn, ssm):
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "MyQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Properties": {"QueueName": "cfn-t03-queue"},
+ },
+ "Param": {
+ "Type": "AWS::SSM::Parameter",
+ "Properties": {
+ "Name": "cfn-t03-param",
+ "Type": "String",
+ "Value": {"Fn::GetAtt": ["MyQueue", "Arn"]},
+ },
+ },
+ },
+ }
+ cfn.create_stack(StackName="cfn-t03", TemplateBody=json.dumps(template))
+ _wait_stack(cfn, "cfn-t03")
+
+ val = ssm.get_parameter(Name="cfn-t03-param")["Parameter"]["Value"]
+ assert val.startswith("arn:aws:sqs:")
+
+
+def test_cfn_conditions(cfn, s3):
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Parameters": {
+ "Create": {"Type": "String", "Default": "yes"},
+ },
+ "Conditions": {
+ "ShouldCreate": {"Fn::Equals": [{"Ref": "Create"}, "yes"]},
+ },
+ "Resources": {
+ "Bucket": {
+ "Type": "AWS::S3::Bucket",
+ "Condition": "ShouldCreate",
+ "Properties": {"BucketName": "cfn-t04-cond"},
+ },
+ },
+ }
+ cfn.create_stack(StackName="cfn-t04a", TemplateBody=json.dumps(template))
+ _wait_stack(cfn, "cfn-t04a")
+ s3.head_bucket(Bucket="cfn-t04-cond")
+
+ # Delete first stack so the bucket name is freed
+ cfn.delete_stack(StackName="cfn-t04a")
+ _wait_stack(cfn, "cfn-t04a")
+
+ cfn.create_stack(
+ StackName="cfn-t04b",
+ TemplateBody=json.dumps(template),
+ Parameters=[{"ParameterKey": "Create", "ParameterValue": "no"}],
+ )
+ stack = _wait_stack(cfn, "cfn-t04b")
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+
+ with pytest.raises(ClientError):
+ s3.head_bucket(Bucket="cfn-t04-cond")
+
+
+def test_cfn_outputs_exports(cfn):
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Bucket": {
+ "Type": "AWS::S3::Bucket",
+ "Properties": {"BucketName": "cfn-t05-exports"},
+ },
+ },
+ "Outputs": {
+ "BucketOut": {
+ "Value": {"Ref": "Bucket"},
+ "Export": {"Name": "cfn-t05-bucket-export"},
+ },
+ },
+ }
+ cfn.create_stack(StackName="cfn-t05", TemplateBody=json.dumps(template))
+ _wait_stack(cfn, "cfn-t05")
+
+ exports = cfn.list_exports()["Exports"]
+ assert any(e["Name"] == "cfn-t05-bucket-export" for e in exports)
+
+
+def test_cfn_fn_sub(cfn, ssm):
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "MyBucket": {
+ "Type": "AWS::S3::Bucket",
+ "Properties": {"BucketName": "cfn-t06-src"},
+ },
+ "Param": {
+ "Type": "AWS::SSM::Parameter",
+ "Properties": {
+ "Name": "cfn-t06-param",
+ "Type": "String",
+ "Value": {"Fn::Sub": "${MyBucket}-replica"},
+ },
+ },
+ },
+ }
+ cfn.create_stack(StackName="cfn-t06", TemplateBody=json.dumps(template))
+ _wait_stack(cfn, "cfn-t06")
+
+ val = ssm.get_parameter(Name="cfn-t06-param")["Parameter"]["Value"]
+ assert val == "cfn-t06-src-replica"
+
+
+def test_cfn_multi_resource_dependencies(cfn):
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Role": {
+ "Type": "AWS::IAM::Role",
+ "Properties": {
+ "RoleName": "cfn-t07-role",
+ "AssumeRolePolicyDocument": {
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Effect": "Allow",
+ "Principal": {"Service": "lambda.amazonaws.com"},
+ "Action": "sts:AssumeRole",
+ }
+ ],
+ },
+ },
+ },
+ "Func": {
+ "Type": "AWS::Lambda::Function",
+ "Properties": {
+ "FunctionName": "cfn-t07-func",
+ "Runtime": "python3.9",
+ "Handler": "index.handler",
+ "Role": {"Fn::GetAtt": ["Role", "Arn"]},
+ "Code": {"ZipFile": "def handler(e,c): return {}"},
+ },
+ },
+ },
+ }
+ cfn.create_stack(StackName="cfn-t07", TemplateBody=json.dumps(template))
+ _wait_stack(cfn, "cfn-t07")
+
+ from tests.conftest import make_client
+ iam = make_client("iam")
+ lam = make_client("lambda")
+ role = iam.get_role(RoleName="cfn-t07-role")["Role"]
+ func = lam.get_function(FunctionName="cfn-t07-func")["Configuration"]
+ assert func["Role"] == role["Arn"]
+
+
+def test_cfn_change_set_lifecycle(cfn):
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Bucket": {
+ "Type": "AWS::S3::Bucket",
+ "Properties": {"BucketName": "cfn-t08-cs"},
+ },
+ },
+ }
+ cfn.create_change_set(
+ StackName="cfn-t08",
+ ChangeSetName="cfn-t08-cs1",
+ TemplateBody=json.dumps(template),
+ ChangeSetType="CREATE",
+ )
+ time.sleep(1)
+
+ cs = cfn.describe_change_set(StackName="cfn-t08", ChangeSetName="cfn-t08-cs1")
+ assert cs["ChangeSetName"] == "cfn-t08-cs1"
+
+ cfn.execute_change_set(StackName="cfn-t08", ChangeSetName="cfn-t08-cs1")
+ stack = _wait_stack(cfn, "cfn-t08")
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+
+
+def test_cfn_update_stack(cfn, s3):
+ template_v1 = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "BucketA": {
+ "Type": "AWS::S3::Bucket",
+ "Properties": {"BucketName": "cfn-t09-a"},
+ },
+ },
+ }
+ cfn.create_stack(StackName="cfn-t09", TemplateBody=json.dumps(template_v1))
+ _wait_stack(cfn, "cfn-t09")
+
+ template_v2 = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "BucketA": {
+ "Type": "AWS::S3::Bucket",
+ "Properties": {"BucketName": "cfn-t09-a"},
+ },
+ "BucketB": {
+ "Type": "AWS::S3::Bucket",
+ "Properties": {"BucketName": "cfn-t09-b"},
+ },
+ },
+ }
+ cfn.update_stack(StackName="cfn-t09", TemplateBody=json.dumps(template_v2))
+ stack = _wait_stack(cfn, "cfn-t09")
+ assert stack["StackStatus"] == "UPDATE_COMPLETE"
+
+ s3.head_bucket(Bucket="cfn-t09-a")
+ s3.head_bucket(Bucket="cfn-t09-b")
+
+
+def test_cfn_delete_nonexistent_stack(cfn):
+ # AWS returns 200 for deleting non-existent stacks (idempotent)
+ cfn.delete_stack(StackName="cfn-nonexistent-xyz")
+ # But describing it should fail
+ with pytest.raises(ClientError):
+ cfn.describe_stacks(StackName="cfn-nonexistent-xyz")
+
+
+def test_cfn_validate_template(cfn):
+ valid_template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Parameters": {
+ "Env": {"Type": "String", "Default": "dev"},
+ },
+ "Resources": {
+ "Bucket": {
+ "Type": "AWS::S3::Bucket",
+ "Properties": {"BucketName": "cfn-t11-validate"},
+ },
+ },
+ }
+ result = cfn.validate_template(TemplateBody=json.dumps(valid_template))
+ assert any(p["ParameterKey"] == "Env" for p in result["Parameters"])
+
+ invalid_template = {"AWSTemplateFormatVersion": "2010-09-09"}
+ with pytest.raises(ClientError):
+ cfn.validate_template(TemplateBody=json.dumps(invalid_template))
+
+
+def test_cfn_list_stacks(cfn):
+ for name in ("cfn-t12-a", "cfn-t12-b"):
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Bucket": {
+ "Type": "AWS::S3::Bucket",
+ "Properties": {"BucketName": f"{name}-bucket"},
+ },
+ },
+ }
+ cfn.create_stack(StackName=name, TemplateBody=json.dumps(template))
+ _wait_stack(cfn, "cfn-t12-a")
+ _wait_stack(cfn, "cfn-t12-b")
+
+ summaries = cfn.list_stacks()["StackSummaries"]
+ names = [s["StackName"] for s in summaries]
+ assert "cfn-t12-a" in names
+ assert "cfn-t12-b" in names
+
+
+def test_cfn_stack_events(cfn):
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Bucket": {
+ "Type": "AWS::S3::Bucket",
+ "Properties": {"BucketName": "cfn-t13-events"},
+ },
+ },
+ }
+ cfn.create_stack(StackName="cfn-t13", TemplateBody=json.dumps(template))
+ _wait_stack(cfn, "cfn-t13")
+
+ events = cfn.describe_stack_events(StackName="cfn-t13")["StackEvents"]
+ assert len(events) > 0
+ assert all("ResourceStatus" in e for e in events)
+
+
+def test_cfn_yaml_template(cfn, s3):
+ yaml_body = """
+AWSTemplateFormatVersion: '2010-09-09'
+Resources:
+ Bucket:
+ Type: AWS::S3::Bucket
+ Properties:
+ BucketName: cfn-t14-yaml
+"""
+ cfn.create_stack(StackName="cfn-t14", TemplateBody=yaml_body)
+ _wait_stack(cfn, "cfn-t14")
+
+ s3.head_bucket(Bucket="cfn-t14-yaml")
+
+
+def test_cfn_rollback_on_failure(cfn, s3):
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Bucket": {
+ "Type": "AWS::S3::Bucket",
+ "Properties": {"BucketName": "cfn-t15-rollback"},
+ },
+ "Bad": {
+ "Type": "AWS::Fake::Nope",
+ "Properties": {},
+ },
+ },
+ }
+ cfn.create_stack(
+ StackName="cfn-t15",
+ TemplateBody=json.dumps(template),
+ DisableRollback=False,
+ )
+ stack = _wait_stack(cfn, "cfn-t15")
+ assert stack["StackStatus"] == "ROLLBACK_COMPLETE"
+
+ with pytest.raises(ClientError):
+ s3.head_bucket(Bucket="cfn-t15-rollback")
+
+
+def test_cfn_import_nonexistent_export(cfn):
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Param": {
+ "Type": "AWS::SSM::Parameter",
+ "Properties": {
+ "Name": "cfn-t16-param",
+ "Type": "String",
+ "Value": {"Fn::ImportValue": "NonExistentExport123"},
+ },
+ },
+ },
+ }
+ cfn.create_stack(StackName="cfn-t16", TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, "cfn-t16")
+ assert stack["StackStatus"] in ("CREATE_FAILED", "ROLLBACK_COMPLETE")
+
+
+def test_cfn_delete_stack_with_active_imports(cfn):
+ exporter_template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Bucket": {
+ "Type": "AWS::S3::Bucket",
+ "Properties": {"BucketName": "cfn-t17-exporter"},
+ },
+ },
+ "Outputs": {
+ "BucketOut": {
+ "Value": {"Ref": "Bucket"},
+ "Export": {"Name": "cfn-t17-export"},
+ },
+ },
+ }
+ cfn.create_stack(StackName="cfn-t17-exp", TemplateBody=json.dumps(exporter_template))
+ _wait_stack(cfn, "cfn-t17-exp")
+
+ importer_template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Param": {
+ "Type": "AWS::SSM::Parameter",
+ "Properties": {
+ "Name": "cfn-t17-param",
+ "Type": "String",
+ "Value": {"Fn::ImportValue": "cfn-t17-export"},
+ },
+ },
+ },
+ }
+ cfn.create_stack(StackName="cfn-t17-imp", TemplateBody=json.dumps(importer_template))
+ _wait_stack(cfn, "cfn-t17-imp")
+
+ with pytest.raises(ClientError):
+ cfn.delete_stack(StackName="cfn-t17-exp")
+
+
+def test_cfn_update_rollback_on_failure(cfn, s3):
+ template_v1 = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Bucket": {
+ "Type": "AWS::S3::Bucket",
+ "Properties": {"BucketName": "cfn-t18-orig"},
+ },
+ },
+ }
+ cfn.create_stack(StackName="cfn-t18", TemplateBody=json.dumps(template_v1))
+ _wait_stack(cfn, "cfn-t18")
+
+ template_v2 = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Bucket": {
+ "Type": "AWS::S3::Bucket",
+ "Properties": {"BucketName": "cfn-t18-orig"},
+ },
+ "Bad": {
+ "Type": "AWS::Fake::Nope",
+ "Properties": {},
+ },
+ },
+ }
+ cfn.update_stack(StackName="cfn-t18", TemplateBody=json.dumps(template_v2))
+ stack = _wait_stack(cfn, "cfn-t18")
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+
+ s3.head_bucket(Bucket="cfn-t18-orig")