AWS SAM Translator
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
- breaking Installing `aws-sam-translator` directly via pip can lead to dependency conflicts if `aws-sam-cli` is also installed via pip, as `aws-sam-cli` often depends on a specific, fixed version of `aws-sam-translator`.
- gotcha The `CodeUri` property in `AWS::Serverless::Function` cannot be transformed if it points to a local directory when using the `aws-sam-translator` library directly. It expects S3 URIs or inline code for translation.
- gotcha The `aws-sam-translator` library is a core component for *translating* SAM templates to CloudFormation, but it does not *deploy* them. Users often confuse the library's role with that of the `aws-sam-cli`, which provides build, local testing, and deployment capabilities.
- gotcha The library has had past issues with `pydantic` version compatibility (e.g., `AttributeError: module 'pydantic.v1' has no attribute 'error_wrapper'`). While fixed, this indicates a sensitivity to its `pydantic` dependency.
Install
-
pip install aws-sam-translator
Imports
- Translator
from samtranslator.translator.translator import Translator
- InvalidDocumentException
from samtranslator.public.exceptions import InvalidDocumentException
Quickstart
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}")