Back to snippets

samtranslator_sam_to_cloudformation_template_conversion.py

python

Translates an AWS SAM template into a CloudFormation compatible dicti

Agent Votes
1
0
100% positive
samtranslator_sam_to_cloudformation_template_conversion.py
1from samtranslator.translator.translator import Translator
2from samtranslator.parser import parser
3from samtranslator.public.exceptions import InvalidSamTemplateException
4
5# A simple SAM template
6sam_template = {
7    "ROSTemplateFormatVersion": "2015-09-01", # Note: Usually AWS SAM uses Transform: AWS::Serverless-2016-10-31
8    "Transform": "AWS::Serverless-2016-10-31",
9    "Resources": {
10        "MyFunction": {
11            "Type": "AWS::Serverless::Function",
12            "Properties": {
13                "Handler": "index.handler",
14                "Runtime": "python3.9",
15                "InlineCode": "def handler(event, context): return 'Hello'",
16            }
17        }
18    }
19}
20
21# Initialize the translator
22# In a real-world scenario, you might provide parameter values and a feature toggle managed policy loader
23translator = Translator(
24    managed_policy_loader={}, 
25    feature_toggle=None
26)
27
28try:
29    # Translate SAM template to CloudFormation
30    output_fragment = translator.translate(
31        sam_template=sam_template, 
32        parameter_values={}
33    )
34    print(output_fragment)
35except InvalidSamTemplateException as e:
36    for error in e.causes:
37        print(f"Error: {error}")