Skip to content

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

Apply SAM transforms to cfn templates (#986)

maximoosemine86058852069d
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b6ed32f7..3a71c67b 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -27,7 +27,7 @@ jobs:
cache: "pip"
- name: Install dependencies
- run: pip install -e . && pip install -r requirements.txt boto3 pytest pytest-xdist duckdb docker cbor2 pyyaml cryptography
+ run: pip install -e . && pip install -r requirements.txt boto3 pytest pytest-xdist duckdb docker cbor2 pyyaml cryptography aws-sam-translator
- name: Plan test shards
id: plan
@@ -58,7 +58,7 @@ jobs:
cache: "pip"
- name: Install dependencies
- run: pip install -e . && pip install -r requirements.txt boto3 pytest pytest-xdist duckdb docker cbor2 pyyaml cryptography
+ run: pip install -e . && pip install -r requirements.txt boto3 pytest pytest-xdist duckdb docker cbor2 pyyaml cryptography aws-sam-translator
- name: Start MiniStack
run: |
diff --git a/Dockerfile.full b/Dockerfile.full
index 1a662e25..036f74ba 100644
--- a/Dockerfile.full
+++ b/Dockerfile.full
@@ -15,6 +15,7 @@ RUN pip install --no-cache-dir --no-compile \
"psycopg2-binary>=2.9" \
"duckdb>=0.10.0" \
"asyncssh>=2.14" \
+ "aws-sam-translator>=1.90" \
"boto3>=1.34" \
"awscli"
diff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.py
index 4c7a68d7..bae7b498 100644
--- a/ministack/services/cloudformation/changesets.py
+++ b/ministack/services/cloudformation/changesets.py
@@ -11,6 +11,7 @@ from ministack.core.responses import get_account_id, new_uuid, now_iso
from .engine import (
_NO_VALUE,
+ _apply_sam_transform_if_applicable,
_evaluate_conditions,
_parse_template,
_resolve_parameters,
@@ -135,6 +136,7 @@ def _create_change_set(params):
try:
template = _parse_template(template_body)
+ template = _apply_sam_transform_if_applicable(template)
except Exception as e:
return _error("ValidationError", f"Template format error: {e}")
diff --git a/ministack/services/cloudformation/engine.py b/ministack/services/cloudformation/engine.py
index 83771445..80641737 100644
--- a/ministack/services/cloudformation/engine.py
+++ b/ministack/services/cloudformation/engine.py
@@ -4,11 +4,14 @@ condition evaluation, intrinsic function resolution, and topological sorting.
"""
import base64
+import copy
import heapq
import json
+import logging
import os
import re
from collections import defaultdict
+from types import SimpleNamespace
import yaml
@@ -560,3 +563,43 @@ def _topological_sort(resources: dict, conditions: dict) -> list:
)
return result
+
+
+# ===========================================================================
+# SAM Transform
+# ===========================================================================
+
+_SAM_TRANSFORM = "AWS::Serverless-2016-10-31"
+
+# Supress benign errors from samtranslator
+logging.getLogger("samtranslator.feature_toggle.feature_toggle").setLevel(logging.ERROR)
+
+_NO_IAM_POLICY_LOADER = SimpleNamespace(load=lambda: {})
+
+def _apply_sam_transform_if_applicable(template: dict) -> dict:
+ declared = template.get("Transform")
+ transforms = declared if isinstance(declared, list) else [declared]
+ if _SAM_TRANSFORM not in transforms:
+ return template
+
+ try:
+ from samtranslator.translator.transform import transform as _sam_transform
+ except ImportError as e:
+ raise ValueError(
+ "Template uses the AWS::Serverless-2016-10-31 transform, but the SAM "
+ "transform was not applied because the optional 'aws-sam-translator' "
+ "package is not installed. Either run ministack's 'full' image (or "
+ "`pip install ministack[full]`) to enable SAM support, or expand the "
+ "template to native CloudFormation first (e.g. `sam build` / "
+ "`aws cloudformation package`). See https://ministack.org/docs/iac#sam"
+ ) from e
+
+ prev_region = os.environ.get("AWS_DEFAULT_REGION")
+ os.environ["AWS_DEFAULT_REGION"] = get_region()
+ try:
+ return _sam_transform(copy.deepcopy(template), {}, _NO_IAM_POLICY_LOADER)
+ finally:
+ if prev_region is None:
+ os.environ.pop("AWS_DEFAULT_REGION", None)
+ else:
+ os.environ["AWS_DEFAULT_REGION"] = prev_region
diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.py
index 007e0224..4e8bb3dd 100644
--- a/ministack/services/cloudformation/handlers.py
+++ b/ministack/services/cloudformation/handlers.py
@@ -18,6 +18,7 @@ from .changesets import (
)
from .engine import (
_NO_VALUE,
+ _apply_sam_transform_if_applicable,
_evaluate_conditions,
_parse_template,
_resolve_parameters,
@@ -54,6 +55,7 @@ def _create_stack(params):
try:
template = _parse_template(template_body)
+ template = _apply_sam_transform_if_applicable(template)
except Exception as e:
return _error("ValidationError", f"Template format error: {e}")
provided_params = _extract_members(params, "Parameters")
@@ -474,6 +476,7 @@ def _update_stack(params):
try:
template = _parse_template(template_body)
+ template = _apply_sam_transform_if_applicable(template)
except Exception as e:
return _error("ValidationError", f"Template format error: {e}")
provided_params = _extract_members(params, "Parameters")
diff --git a/pyproject.toml b/pyproject.toml
index 66e54e53..dde8498b 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -35,6 +35,7 @@ full = [
"psycopg2-binary>=2.9",
"pymysql>=1.1",
"asyncssh>=2.14",
+ "aws-sam-translator>=1.90",
]
dev = [
"boto3>=1.34",
@@ -50,6 +51,7 @@ dev = [
"mypy-boto3-lambda (>=1.42.85,<2.0.0)",
"asyncssh>=2.14",
"websockets>=12.0",
+ "aws-sam-translator>=1.90",
]
[project.urls]
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 2082fe89..ce08a798 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -3756,3 +3756,181 @@ def test_cfn_lambda_layer_packages_importable(cfn, s3, lam):
assert payload["value"] == "from-cfn-layer"
finally:
cfn.delete_stack(StackName=stack_name)
+
+
+def test_cfn_sam_transform_function_and_simple_table(cfn, lam, s3, ddb):
+ pytest.importorskip("samtranslator")
+ suffix = _uuid_mod.uuid4().hex[:8]
+ bucket = f"cfn-sam-code-{suffix}"
+ key = "handler.zip"
+ s3.create_bucket(Bucket=bucket)
+
+ code = b"def handler(event, context):\n return {'ok': True}\n"
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", code)
+ s3.put_object(Bucket=bucket, Key=key, Body=buf.getvalue())
+
+ stack_name = f"cfn-sam-basic-{suffix}"
+ fn_name = f"sam-fn-{suffix}"
+ table_name = f"sam-table-{suffix}"
+
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Transform": "AWS::Serverless-2016-10-31",
+ "Resources": {
+ "MyFunction": {
+ "Type": "AWS::Serverless::Function",
+ "Properties": {
+ "FunctionName": fn_name,
+ "Handler": "index.handler",
+ "Runtime": "python3.12",
+ "CodeUri": {"Bucket": bucket, "Key": key},
+ "MemorySize": 256,
+ "Timeout": 10,
+ "Environment": {"Variables": {"TABLE": table_name}},
+ },
+ },
+ "MyTable": {
+ "Type": "AWS::Serverless::SimpleTable",
+ "Properties": {
+ "TableName": table_name,
+ "PrimaryKey": {"Name": "pk", "Type": "String"},
+ },
+ },
+ },
+ "Outputs": {
+ "FunctionName": {"Value": {"Ref": "MyFunction"}},
+ },
+ }
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+
+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack.get("Outputs", [])}
+ assert outputs["FunctionName"] == fn_name
+
+ resp = lam.invoke(FunctionName=fn_name, Payload=b"{}")
+ assert resp["StatusCode"] == 200
+ payload = json.loads(resp["Payload"].read())
+ assert payload.get("ok") is True
+
+ resources = cfn.describe_stack_resources(StackName=stack_name)["StackResources"]
+ rtypes = {r["ResourceType"] for r in resources}
+ assert "AWS::IAM::Role" in rtypes, f"Expected auto-generated IAM role, got {rtypes}"
+ assert "AWS::Lambda::Function" in rtypes
+ assert "AWS::DynamoDB::Table" in rtypes
+
+ table_desc = ddb.describe_table(TableName=table_name)["Table"]
+ ks = {k["AttributeName"]: k["KeyType"] for k in table_desc["KeySchema"]}
+ assert ks.get("pk") == "HASH"
+
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+ s3.delete_object(Bucket=bucket, Key=key)
+ s3.delete_bucket(Bucket=bucket)
+
+
+def test_cfn_sam_transform_serverless_api(cfn, s3, lam):
+ pytest.importorskip("samtranslator")
+ suffix = _uuid_mod.uuid4().hex[:8]
+ bucket = f"cfn-sam-api-code-{suffix}"
+ key = "handler.zip"
+ s3.create_bucket(Bucket=bucket)
+
+ code = b"def handler(event, context):\n return {'statusCode': 200, 'body': 'ok'}\n"
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", code)
+ s3.put_object(Bucket=bucket, Key=key, Body=buf.getvalue())
+
+ stack_name = f"cfn-sam-api-{suffix}"
+ fn_name = f"sam-api-fn-{suffix}"
+
+ openapi_body = {
+ "openapi": "3.0.1",
+ "info": {"title": "test", "version": "1.0"},
+ "paths": {
+ "/hello": {
+ "get": {
+ "x-amazon-apigateway-integration": {
+ "type": "aws_proxy",
+ "httpMethod": "POST",
+ "uri": {"Fn::Sub": "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyFunction.Arn}/invocations"},
+ "passthroughBehavior": "WHEN_NO_MATCH",
+ }
+ }
+ }
+ },
+ }
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Transform": "AWS::Serverless-2016-10-31",
+ "Resources": {
+ "MyApi": {
+ "Type": "AWS::Serverless::Api",
+ "Properties": {
+ "Name": f"sam-api-{suffix}",
+ "StageName": "v1",
+ "DefinitionBody": openapi_body,
+ },
+ },
+ "MyFunction": {
+ "Type": "AWS::Serverless::Function",
+ "Properties": {
+ "FunctionName": fn_name,
+ "Handler": "index.handler",
+ "Runtime": "python3.12",
+ "CodeUri": {"Bucket": bucket, "Key": key},
+ },
+ },
+ },
+ }
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+
+ resources = cfn.describe_stack_resources(StackName=stack_name)["StackResources"]
+ rtypes = {r["ResourceType"] for r in resources}
+ assert "AWS::ApiGateway::RestApi" in rtypes, f"Missing RestApi in {rtypes}"
+ assert "AWS::ApiGateway::Deployment" in rtypes, f"Missing Deployment in {rtypes}"
+ assert "AWS::ApiGateway::Stage" in rtypes, f"Missing Stage in {rtypes}"
+ assert "AWS::Lambda::Function" in rtypes
+ assert "AWS::IAM::Role" in rtypes
+
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+ s3.delete_object(Bucket=bucket, Key=key)
+ s3.delete_bucket(Bucket=bucket)
+
+
+def test_cfn_sam_transform_missing_translator_falls_back(monkeypatch):
+ import sys
+
+ from ministack.services.cloudformation.engine import (
+ _apply_sam_transform_if_applicable,
+ )
+
+ # Simulate the package being absent: a None entry makes `from ... import`
+ # raise ImportError even if samtranslator is installed in the test env.
+ monkeypatch.setitem(sys.modules, "samtranslator.translator.transform", None)
+
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Transform": "AWS::Serverless-2016-10-31",
+ "Resources": {
+ "MyFunction": {
+ "Type": "AWS::Serverless::Function",
+ "Properties": {"Handler": "index.handler", "Runtime": "python3.12"},
+ },
+ },
+ }
+ with pytest.raises(ValueError) as exc:
+ _apply_sam_transform_if_applicable(template)
+ msg = str(exc.value)
+ assert "AWS::Serverless-2016-10-31" in msg
+ assert "docs/iac#sam" in msg
+
+ # Templates that don't use the SAM transform are unaffected.
+ plain = {"Resources": {"B": {"Type": "AWS::S3::Bucket", "Properties": {}}}}
+ assert _apply_sam_transform_if_applicable(plain) is plain