AWS SAM Translator

1.108.0 · active · verified Sat Mar 28

AWS SAM Translator is a Python library responsible for transforming AWS Serverless Application Model (SAM) templates into standard AWS CloudFormation templates. It is a core component used by the AWS SAM CLI and maintains a rapid release cadence, with updates often reflecting new SAM specification features and CloudFormation resource support. The current version is 1.108.0.

Warnings

Install

Imports

Quickstart

This example demonstrates how to parse a SAM template string, initialize the `Translator` class, and convert the SAM template into a standard CloudFormation template. In a real application, `managed_policy_map` and `globals` would be populated based on the SAM template's contents or external configuration.

import json
import yaml
from samtranslator.translator.translator import Translator
from samtranslator.public.exceptions import InvalidDocumentException

sam_template_str = """
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: A simple SAM template for testing

Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.lambda_handler
      Runtime: python3.9
      CodeUri: s3://my-bucket/my-code.zip
      MemorySize: 128
      Timeout: 30
      Events:
        Api:
          Type: Api
          Properties:
            Path: /hello
            Method: GET
"""

# Load SAM template (YAML or JSON)
sam_template = yaml.safe_load(sam_template_str)

# Initialize the translator. 
# managed_policy_map is usually populated from AWS::Serverless::Function/StateMachine policies
# and globals from the Globals section of the template.
translator = Translator(
    sam_template=sam_template,
    managed_policy_map={},
    globals={}
)

try:
    # Translate the SAM template to CloudFormation
    cloudformation_template = translator.translate()
    print("Translated CloudFormation Template:")
    print(json.dumps(cloudformation_template, indent=2))
except InvalidDocumentException as e:
    print(f"Error translating template: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →