### Install Dependencies and Run Tests Source: https://github.com/aws/serverless-application-model/blob/develop/README.md Commands to initialize project dependencies and run tests using make. These are standard commands for setting up the development environment. ```bash make init ``` ```bash make pr ``` -------------------------------- ### Install pyenv Source: https://github.com/aws/serverless-application-model/blob/develop/DEVELOPMENT_GUIDE.md Installs pyenv using the official installer script. This tool helps manage multiple Python versions. ```bash curl -L https://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-installer | bash ``` -------------------------------- ### Install pre-commit hooks Source: https://github.com/aws/serverless-application-model/blob/develop/DEVELOPMENT_GUIDE.md Installs git hooks managed by pre-commit. This ensures code formatting and other checks are run automatically before each commit. ```bash pre-commit install ``` -------------------------------- ### Install Python versions with pyenv Source: https://github.com/aws/serverless-application-model/blob/develop/DEVELOPMENT_GUIDE.md Installs specific Python versions using pyenv. Ensure these versions are supported by the project. ```bash pyenv install 3.10.20 ``` ```bash pyenv install 3.11.15 ``` ```bash pyenv install 3.12.13 ``` ```bash pyenv install 3.13.12 ``` ```bash pyenv install 3.14.3 ``` -------------------------------- ### SAM Globals Section Example Source: https://context7.com/aws/serverless-application-model/llms.txt Illustrates the use of the Globals section in a SAM template to define shared configurations for resources like Functions, APIs, and Tables. ```yaml # Globals section example # Globals support Function, Api, HttpApi, SimpleTable, and LayerVersion. # Primitive values are overridden by the resource; maps are merged; lists are prepended. # Example: # Globals: # Function: # Timeout: 30 # MemorySize: 128 # Api: # CorsConfiguration: # AllowMethods: ['GET', 'POST'] # AllowHeaders: ['*'] ``` -------------------------------- ### SAM Globals Example: Function Configuration Source: https://github.com/aws/serverless-application-model/blob/develop/docs/globals.rst Demonstrates how to define global configurations for AWS::Serverless::Function resources, including runtime, timeout, and environment variables. Resources inherit these settings unless explicitly overridden. ```yaml Globals: Function: Runtime: nodejs24.x Timeout: 180 Handler: index.handler Environment: Variables: TABLE_NAME: data-table Resources: HelloWorldFunction: Type: AWS::Serverless::Function Properties: Environment: Variables: MESSAGE: "Hello From SAM" ThumbnailFunction: Type: AWS::Serverless::Function Properties: Events: Thumbnail: Type: Api Properties: Path: /thumbnail Method: POST ``` -------------------------------- ### Deploy SAM Application with SAM CLI Source: https://github.com/aws/serverless-application-model/blob/develop/README.md Command to deploy a SAM application using the SAM CLI. Ensure you have the SAM CLI installed and configured. ```bash sam sync --stack-name sam-app ``` -------------------------------- ### Packaged SAM template with S3 URIs Source: https://github.com/aws/serverless-application-model/blob/develop/HOWTO.md Example of a SAM template after packaging, where `CodeUri` and `DefinitionUri` properties are updated to point to the S3 locations of the uploaded artifacts. ```yaml MyLambdaFunction: Type: AWS::Serverless::Function Properties: CodeUri: s3:/// ... MyApi: Type: AWS::Serverless::Api Properties: DefinitionUri: s3:/// ... ``` -------------------------------- ### Example AWS SAM Resource for API Source: https://github.com/aws/serverless-application-model/blob/develop/CONTRIBUTING.md This YAML snippet demonstrates how a new AWS SAM resource for an API endpoint might be defined. It includes properties for the API's name, path, and HTTP method. ```yaml Type: 'AWS::Serverless::Api' Properties: # Name of API endpoint Name: # Path to their endpoint. Example: /hello Path: # HTTP Method for their endpoint. Example: GET, POST etc Method: ``` -------------------------------- ### Define Lambda Function and API resources in SAM template Source: https://github.com/aws/serverless-application-model/blob/develop/HOWTO.md Example SAM template snippet showing how to define a Lambda function with `CodeUri` pointing to local code and an API with `DefinitionUri` pointing to a local OpenAPI specification. ```yaml MyLambdaFunction: Type: AWS::Serverless::Function Properties: CodeUri: ./code ... MyApi: Type: AWS::Serverless::Api Properties: DefinitionUri: ./specs/swagger.yaml ... ``` -------------------------------- ### Profile SAM CLI Translation Source: https://github.com/aws/serverless-application-model/blob/develop/DEVELOPMENT_GUIDE.md Use cProfile to generate a profile of the SAM translate command for performance analysis. Install snakeviz to visualize the results. ```bash pip install snakeviz ``` ```bash python -m cProfile -o sam_profile_results bin/sam-translate.py translate --template-file=tests/translator/input/alexa_skill.yaml --output-template=cfn-template.json snakeviz sam_profile_results ``` -------------------------------- ### SAM Globals Override Example: Map Merging Source: https://github.com/aws/serverless-application-model/blob/develop/docs/globals.rst Shows how map-based properties, such as Environment Variables, are merged. Resource-specific entries are added to or override global map entries. ```yaml Globals: Function: Environment: Variables: TABLE_NAME: data-table Resources: MyFunction: Type: AWS::Serverless::Function Properties: Environment: Variables: MESSAGE: "Hello From SAM" ``` -------------------------------- ### SAM Globals Override Example: Primitive Value Replacement Source: https://github.com/aws/serverless-application-model/blob/develop/docs/globals.rst Illustrates how a primitive value like Runtime specified in a resource's properties overrides the global setting. The resource's value takes precedence. ```yaml Globals: Function: Runtime: nodejs24.x Resources: MyFunction: Type: AWS::Serverless::Function Properties: Runtime: python3.14 ``` -------------------------------- ### Configure CodeDeploy Hook Function Source: https://github.com/aws/serverless-application-model/blob/develop/docs/safe_lambda_deployments.rst Configure a Lambda function to act as a CodeDeploy hook for pre-traffic events. This example disables traffic shifting for the hook function itself and grants necessary permissions for CodeDeploy and Lambda invocation. ```yaml FunctionName: 'CodeDeployHook_preTrafficHook' DeploymentPreference: Enabled: False Policies: - Version: "2012-10-17" Statement: - Effect: "Allow" Action: - "codedeploy:PutLifecycleEventHookExecutionStatus" Resource: "*" - Version: "2012-10-17" Statement: - Effect: "Allow" Action: - "lambda:InvokeFunction" Resource: !GetAtt MyLambdaFunction.Arn ``` -------------------------------- ### Skip Tests for a Specific Service Source: https://github.com/aws/serverless-application-model/blob/develop/INTEGRATION_TESTS.md Use the @skipIf decorator to conditionally skip tests for a particular service in a given region. 'XRay' is used as an example service. ```python @skipIf(current_region_does_not_support('XRay'), 'XRay is not supported in this testing region') ``` -------------------------------- ### Grant Full DynamoDB Access with Managed Policy Source: https://github.com/aws/serverless-application-model/blob/develop/docs/policy_templates.rst This example shows how to grant a Lambda function full access to all DynamoDB tables using an AWS Managed Policy. This is generally too permissive for most use cases. ```yaml MyFunction: Type: AWS::Serverless::Function Properties: ... Policies: # Give your Lambda Function Full Access to DynamoDB - AmazonDynamoDBFullAccess ... MyTable: Type: AWS::Serverless::SimpleTable ``` -------------------------------- ### Grant CRUD Permissions to a Specific DynamoDB Table Source: https://github.com/aws/serverless-application-model/blob/develop/docs/policy_templates.rst This example demonstrates using a SAM Policy Template to grant only CRUD permissions to a specific DynamoDB table referenced by !Ref MyTable. This is a more secure approach than using a broad managed policy. ```yaml MyFunction: Type: AWS::Serverless::Function Properties: ... Policies: # Give just CRUD permissions to one table - DynamoDBCrudPolicy: TableName: !Ref MyTable ... MyTable: Type: AWS::Serverless::SimpleTable ``` -------------------------------- ### Initialize Development Environment Source: https://github.com/aws/serverless-application-model/blob/develop/INTEGRATION_TESTS.md Run this command to set up the necessary development environment for the tests. ```bash make init ``` -------------------------------- ### Initialize a new SAM project Source: https://github.com/aws/serverless-application-model/blob/develop/HOWTO.md Use the `sam init` command to create a new serverless application project. Specify the runtime for your Lambda functions. ```shell $ sam init --runtime python3.14 ``` -------------------------------- ### Prepare Companion Stack Source: https://github.com/aws/serverless-application-model/blob/develop/INTEGRATION_TESTS.md Execute this command to create a companion stack required for running the tests, which includes resources like an S3 bucket. ```bash make prepare-companion-stack ``` -------------------------------- ### SAM Translate CLI Package and Deploy Source: https://context7.com/aws/serverless-application-model/llms.txt Shows how to use the SAM translate CLI for packaging artifacts to S3, transforming templates, and deploying CloudFormation stacks. ```bash # Package local artifacts to S3 then transform (requires --s3-bucket) python bin/sam-translate.py package \ --template-file template.yaml \ --s3-bucket my-artifact-bucket \ --output-template packaged.json # Package, transform, and deploy in one shot python bin/sam-translate.py deploy \ --template-file template.yaml \ --s3-bucket my-artifact-bucket \ --output-template packaged.json \ --capabilities CAPABILITY_IAM \ --stack-name my-sam-app # Enable verbose (DEBUG) logging for troubleshooting python bin/sam-translate.py --template-file template.yaml --verbose --stdout ``` -------------------------------- ### Run All Integration Tests Source: https://github.com/aws/serverless-application-model/blob/develop/INTEGRATION_TESTS.md This command executes the entire suite of integration tests from the root of the repository. ```bash make integ-test ``` -------------------------------- ### Enable AutoPublishAlias and DeploymentPreference Source: https://github.com/aws/serverless-application-model/blob/develop/docs/safe_lambda_deployments.rst Configure SAM to automatically publish a new Lambda version and alias it, with CodeDeploy handling traffic shifting and monitoring. ```yaml AutoPublishAlias: live DeploymentPreference: Type: Linear10PercentEvery10Minutes ``` -------------------------------- ### SAM Translate CLI Basic Usage Source: https://context7.com/aws/serverless-application-model/llms.txt Demonstrates basic command-line usage for the SAM translate script, including specifying input/output paths and printing to stdout. ```bash # Basic transformation (reads template.yaml, writes transformed-template.json) python bin/sam-translate.py # Specify custom input and output paths python bin/sam-translate.py \ --template-file my-service/template.yaml \ --output-template /tmp/cfn-output.json # Print the transformed template to stdout instead of a file python bin/sam-translate.py \ --template-file template.yaml \ --stdout ``` -------------------------------- ### Package SAM Template for CloudFormation Source: https://github.com/aws/serverless-application-model/blob/develop/DEVELOPMENT_GUIDE.md Package a SAM template to prepare it for CloudFormation deployment, especially when CodeUri points to a local path. Replace placeholders with your specific paths and S3 bucket. ```bash # Optional: You only need to run the package command in certain cases; e.g. when your CodeUri specifies a local path # Replace MY_TEMPLATE_PATH with the path to your template and MY_S3_BUCKET with an existing S3 bucket aws cloudformation package --template-file MY_TEMPLATE_PATH/template.yaml --output-template-file output-template.yaml --s3-bucket MY_S3_BUCKET ``` -------------------------------- ### Package local artifacts to S3 using AWS SAM CLI Source: https://github.com/aws/serverless-application-model/blob/develop/HOWTO.md Use the `sam package` command from the AWS SAM CLI to upload local artifacts to S3 and create a deployable template. This command automates the process of preparing your application for deployment. ```bash $ sam package \ --template-file /path_to_template/template.yaml \ --s3-bucket bucket-name \ --s3-prefix appname/branchname/version \ --output-template-file packaged-template.yaml ``` -------------------------------- ### Create SAM virtualenv Source: https://github.com/aws/serverless-application-model/blob/develop/DEVELOPMENT_GUIDE.md Creates a virtual environment named 'sam310' for Python 3.10 using pyenv. This isolates project dependencies. ```bash pyenv virtualenv 3.10.16 sam310 ``` -------------------------------- ### Create Python Virtual Environment Source: https://github.com/aws/serverless-application-model/blob/develop/README.md Commands to create and activate a Python virtual environment using venv. This is a prerequisite for setting up the development environment. ```bash python3 -m venv .venv source .venv/bin/activate ``` -------------------------------- ### Core SAM transform engine with `Translator` and `Parser` Source: https://context7.com/aws/serverless-application-model/llms.txt Instantiate `Translator` and `Parser` directly for fine-grained control over the SAM transformation pipeline, including custom plugins and boto session management. This approach is suitable when you need to manage the transformation process more closely. ```python import boto3 from samtranslator.public.translator import ManagedPolicyLoader, Translator from samtranslator.public.parser import Parser from samtranslator.public.plugins import BasePlugin from samtranslator.plugins import LifeCycleEvents from samtranslator.model.exceptions import InvalidDocumentException ``` -------------------------------- ### Enable API Gateway Logs with AWS CLI Source: https://github.com/aws/serverless-application-model/blob/develop/docs/faq.rst Use this AWS CLI command to enable data tracing, set log level to Info, and enable metrics for an API Gateway stage. This can be run as a post-deployment step in CI/CD or via a CloudFormation custom resource. ```bash aws apigateway update-stage \ --rest-api-id \ --stage-name \ --patch-operations \ op=replace,path=/*/*/logging/dataTrace,value=true \ op=replace,path=/*/*/logging/loglevel,value=Info \ op=replace,path=/*/*/metrics/enabled,value=true ``` -------------------------------- ### Configure pyenv in shell Source: https://github.com/aws/serverless-application-model/blob/develop/DEVELOPMENT_GUIDE.md Adds pyenv initialization commands to your shell configuration file (.bashrc or .zshrc) to make pyenv commands available. ```bash export PATH="$HOME/.pyenv/bin:$PATH" eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)" ``` -------------------------------- ### Generate Transform Test Files Source: https://github.com/aws/serverless-application-model/blob/develop/DEVELOPMENT_GUIDE.md Use this script to generate input and output files for transform tests. Always verify the generated output. ```bash python3 bin/add_transform_test.py --template-file template.yaml ``` -------------------------------- ### Use Policy Template with No Parameters Source: https://github.com/aws/serverless-application-model/blob/develop/docs/policy_templates.rst When a policy template does not require any parameters, specify an empty dictionary as its value. This ensures SAM correctly processes the policy. ```yaml Policies: - CloudWatchPutMetricPolicy: {} ``` -------------------------------- ### Format code with Black Source: https://github.com/aws/serverless-application-model/blob/develop/DEVELOPMENT_GUIDE.md Formats the project's code using Black. This command is typically run via a Makefile. ```bash make format ``` -------------------------------- ### Configure SAM for Instant Traffic Shifting Source: https://github.com/aws/serverless-application-model/blob/develop/docs/safe_lambda_deployments.rst Use the AutoPublishAlias property to automatically create and manage a Lambda alias that points to the latest published version of your function. ```yaml AutoPublishAlias: ``` -------------------------------- ### Deploy Transformed CloudFormation Template Source: https://github.com/aws/serverless-application-model/blob/develop/DEVELOPMENT_GUIDE.md Deploy the generated CloudFormation template to AWS. Ensure you provide a unique stack name for each deployment and include necessary capabilities like CAPABILITY_NAMED_IAM. ```bash # Deploy your transformed CloudFormation template # Replace MY_STACK_NAME with a unique name each time you deploy aws cloudformation deploy --template-file cfn-template.json --capabilities CAPABILITY_NAMED_IAM --stack-name MY_STACK_NAME ``` -------------------------------- ### SAM Globals Supported Properties: Function, Api, HttpApi, SimpleTable, LayerVersion Source: https://github.com/aws/serverless-application-model/blob/develop/docs/globals.rst Lists the properties supported within the Globals section for various SAM resource types. This helps in understanding what configurations can be centralized. ```yaml Globals: Function: # Properties of AWS::Serverless::Function Handler: Runtime: CodeUri: DeadLetterQueue: Description: MemorySize: Timeout: VpcConfig: Environment: Tags: Tracing: KmsKeyArn: Layers: AutoPublishAlias: DeploymentPreference: RolePath: PermissionsBoundary: ReservedConcurrentExecutions: EventInvokeConfig: Architectures: EphemeralStorage: RuntimeManagementConfig: LoggingConfig: FileSystemConfigs: Api: # Properties of AWS::Serverless::Api # Also works with Implicit APIs Auth: Name: DefinitionUri: MergeDefinitions: CacheClusterEnabled: CacheClusterSize: Variables: EndpointConfiguration: MethodSettings: BinaryMediaTypes: MinimumCompressionSize: Cors: GatewayResponses: AccessLogSetting: CanarySetting: TracingEnabled: OpenApiVersion: Domain: SecurityPolicy: EndpointAccessMode: HttpApi: # Properties of AWS::Serverless::HttpApi # Also works with Implicit APIs Auth: CorsConfiguration: AccessLogSettings: Tags: DefaultRouteSettings: RouteSettings: Domain: SimpleTable: # Properties of AWS::Serverless::SimpleTable SSESpecification: LayerVersion: # Properties of AWS::Serverless::LayerVersion PublishLambdaVersion: ``` -------------------------------- ### Deploy packaged SAM template using AWS SAM CLI Source: https://github.com/aws/serverless-application-model/blob/develop/HOWTO.md Deploy the packaged SAM template to AWS CloudFormation using the `sam deploy` command from the AWS SAM CLI. This command simplifies the deployment process by creating and executing a changeset. ```bash $ sam deploy \ --template-file /path_to_template/packaged-template.yaml \ --stack-name my-new-stack \ --capabilities CAPABILITY_IAM ``` -------------------------------- ### Deploy packaged SAM template using AWS CLI Source: https://github.com/aws/serverless-application-model/blob/develop/HOWTO.md Deploy the packaged SAM template to AWS CloudFormation using the `aws cloudformation deploy` command. This command creates and executes a changeset for the deployment. ```bash $ aws cloudformation deploy \ --template-file /path_to_template/packaged-template.yaml \ --stack-name my-new-stack \ --capabilities CAPABILITY_IAM ``` -------------------------------- ### Activate virtualenv Source: https://github.com/aws/serverless-application-model/blob/develop/DEVELOPMENT_GUIDE.md Activates the 'sam310' virtual environment. This ensures that subsequent commands use the Python interpreter and packages within this environment. ```bash pyenv activate sam310 ``` -------------------------------- ### Create a Custom SAM Transform Plugin Source: https://context7.com/aws/serverless-application-model/llms.txt Implement custom logic to hook into the SAM transform lifecycle. Use `on_before_transform_resource` for resource-level validation, `on_before_transform_template` for template-wide modifications before resource processing, and `on_after_transform_template` for post-processing validation. ```python from samtranslator.public.plugins import BasePlugin from samtranslator.model.exceptions import InvalidResourceException, InvalidDocumentException class EnvVarValidatorPlugin(BasePlugin): """Ensure every Lambda function declares at least one environment variable.""" REQUIRED_ENV = "APP_ENV" def on_before_transform_resource(self, logical_id, resource_type, resource_properties): if resource_type != "AWS::Serverless::Function": return env_vars = resource_properties.get("Environment", {}).get("Variables", {}) if self.REQUIRED_ENV not in env_vars: raise InvalidResourceException( logical_id, f"Missing required environment variable '{self.REQUIRED_ENV}'.", ) def on_before_transform_template(self, template_dict): # Can mutate template_dict freely; runs once before any resource transform template_dict.setdefault("Metadata", {})["TransformedBy"] = "my-pipeline" def on_after_transform_template(self, template): # Runs after all resources are transformed; good for cross-resource validations functions = [ k for k, v in template.get("Resources", {}).items() if v.get("Type") == "AWS::Lambda::Function" ] print(f"Total Lambda functions generated: {len(functions)}") # Plug into the translator from samtranslator.public.translator import Translator from samtranslator.public.parser import Parser import boto3 translator = Translator( managed_policy_map=None, sam_parser=Parser(), plugins=[EnvVarValidatorPlugin()], boto_session=boto3.session.Session(region_name="us-east-1"), ) ``` -------------------------------- ### High-level SAM-to-CloudFormation conversion with `transform()` Source: https://context7.com/aws/serverless-application-model/llms.txt Use the `transform()` function for programmatic SAM-to-CloudFormation conversion outside of CloudFormation, such as in CI pipelines. It requires a SAM template, parameter values, and a managed policy loader. ```python import boto3 import json from samtranslator.yaml_helper import yaml_parse from samtranslator.public.translator import ManagedPolicyLoader from samtranslator.translator.transform import transform from samtranslator.model.exceptions import InvalidDocumentException iam_client = boto3.client("iam", region_name="us-east-1") managed_policy_loader = ManagedPolicyLoader(iam_client) sam_template = yaml_parse(""" Transform: AWS::Serverless-2016-10-31 Resources: HelloFunction: Type: AWS::Serverless::Function Properties: Handler: index.handler Runtime: python3.12 CodeUri: s3://my-bucket/my-code.zip Events: HelloApi: Type: Api Properties: Path: /hello Method: get Policies: - DynamoDBCrudPolicy: TableName: !Ref MyTable MyTable: Type: AWS::Serverless::SimpleTable """) try: cfn_template = transform( input_fragment=sam_template, parameter_values={}, managed_policy_loader=managed_policy_loader, passthrough_metadata=False, ) print(json.dumps(cfn_template, indent=2)) except InvalidDocumentException as e: print(e.message) for cause in e.causes: print(" -", cause.message) ``` -------------------------------- ### Set local Python versions with pyenv Source: https://github.com/aws/serverless-application-model/blob/develop/DEVELOPMENT_GUIDE.md Configures the project to use specific Python versions locally. This command creates a .python-version file. ```bash pyenv local 3.10.20 3.11.15 3.12.13 3.13.12 3.14.3 ``` -------------------------------- ### Package local artifacts to S3 using AWS CLI Source: https://github.com/aws/serverless-application-model/blob/develop/HOWTO.md Automate uploading local Lambda function code and API definitions to an S3 bucket using the `aws cloudformation package` command. This generates a packaged template with S3 URIs. ```bash $ aws cloudformation package \ --template-file /path_to_template/template.yaml \ --s3-bucket bucket-name \ --s3-prefix appname/branchname/version \ --output-template-file packaged-template.yaml ``` -------------------------------- ### Define a Serverless Function with SAM Source: https://github.com/aws/serverless-application-model/blob/develop/README.md Use the AWS::Serverless::Function resource to define a Lambda function with inline code. This is a basic SAM template structure. ```yaml Transform: AWS::Serverless-2016-10-31 Resources: MyFunction: Type: AWS::Serverless::Function Properties: Runtime: nodejs24.x Handler: index.handler InlineCode: | exports.handler = async (event) => { console.log(event); } ``` -------------------------------- ### Iterate and Mutate SAM Resources with SamTemplate Source: https://context7.com/aws/serverless-application-model/llms.txt Use `SamTemplate` to programmatically interact with SAM template resources. It allows filtering by resource type, in-place mutation of resource properties, and easy conversion back to a dictionary. ```python from samtranslator.public.sdk.template import SamTemplate raw_template = { "Resources": { "FuncA": {"Type": "AWS::Serverless::Function", "Properties": {"Handler": "a.h", "Runtime": "python3.12"}}, "FuncB": {"Type": "AWS::Serverless::Function", "Properties": {"Handler": "b.h", "Runtime": "nodejs20.x"}}, "MyApi": {"Type": "AWS::Serverless::Api", "Properties": {"StageName": "prod"}}, "RegularBucket": {"Type": "AWS::S3::Bucket", "Properties": {}}, } } template = SamTemplate(raw_template) # Iterate over all valid SAM resources (non-SAM types are skipped) for logical_id, resource in template.iterate(): print(logical_id, resource.type) # Filter by specific SAM type for logical_id, resource in template.iterate({"AWS::Serverless::Function"}): resource.properties["Timeout"] = 30 # mutate in-place template.set(logical_id, resource) # Access and modify globals globals_section = template.get_globals() # Get a specific resource api = template.get("MyApi") print(api.type) print(api.properties) # Delete a resource template.delete("RegularBucket") # Back to dict updated = template.to_dict() print(list(updated["Resources"].keys())) ``` -------------------------------- ### Run Specific Test File with Pytest Source: https://github.com/aws/serverless-application-model/blob/develop/INTEGRATION_TESTS.md Use this command to run tests from a specific file. Replace 'path/to/the/test_file.py' with the actual file path. ```bash pytest --no-cov path/to/the/test_file.py ``` -------------------------------- ### SAM Template Globals Configuration Source: https://context7.com/aws/serverless-application-model/llms.txt Defines default settings for all Lambda functions and API Gateway configurations within the SAM template. These globals can be overridden by individual resource properties. ```yaml Transform: AWS::Serverless-2016-10-31 Globals: Function: Runtime: python3.12 Timeout: 30 MemorySize: 256 Environment: Variables: STAGE: production LOG_LEVEL: INFO Tracing: Active Layers: - !Ref CommonLayer Api: Cors: AllowOrigin: "'*'" AllowHeaders: "'Content-Type,X-Amz-Date,Authorization'" TracingEnabled: true ``` -------------------------------- ### SAM Connectors for Resource Permissions Source: https://context7.com/aws/serverless-application-model/llms.txt Use AWS::Serverless::Connector or the embedded Connectors shorthand to automatically generate IAM policies for resource interactions. Specify the source, destination, and required permissions (e.g., Read, Write). ```yaml Transform: AWS::Serverless-2016-10-31 Resources: # Method 1: standalone Connector resource MyFunction: Type: AWS::Serverless::Function Properties: Handler: app.handler Runtime: python3.12 MyQueue: Type: AWS::SQS::Queue FunctionToQueueConnector: Type: AWS::Serverless::Connector Properties: Source: Id: MyFunction Destination: Id: MyQueue Permissions: - Write # grants sqs:SendMessage # Method 2: embedded Connectors shorthand on the source resource EventProcessor: Type: AWS::Serverless::Function Properties: Handler: events.handler Runtime: python3.12 Connectors: ReadFromStream: # connector logical ID suffix Properties: Destination: Id: EventStream Permissions: - Read # grants kinesis:GetRecords, kinesis:DescribeStream, etc. EventStream: Type: AWS::Kinesis::Stream Properties: ShardCount: 1 ``` -------------------------------- ### Generate Dynamic Lambda Function Names Source: https://github.com/aws/serverless-application-model/blob/develop/HOWTO.md Use !Sub for string substitution to create unique Lambda function names based on template parameters. ```YAML Transform: 'AWS::Serverless-2016-10-31' # Parameters are CloudFormation features to pass input # to your template when you create a stack Parameters: FunctionNameSuffix: Type: String Resources: MyFunction: Type: AWS::Serverless::Function Properties: # !Sub performs string substitution FunctionName: !Sub "mylambda-${FunctionNameSuffix}" Handler: index.handler Runtime: nodejs24.x CodeUri: s3://bucket/key ``` -------------------------------- ### Additive Lists with Globals Source: https://github.com/aws/serverless-application-model/blob/develop/docs/globals.rst Global list properties are prepended to resource-specific lists. This is useful for adding common configurations like security group IDs to all functions. ```yaml Globals: Function: VpcConfig: SecurityGroupIds: - sg-123 - sg-456 Resources: MyFunction: Type: AWS::Serverless::Function Properties: VpcConfig: SecurityGroupIds: - sg-first ``` ```json [ "sg-123", "sg-456", "sg-first" ] ``` -------------------------------- ### Transform SAM Template to CloudFormation Source: https://github.com/aws/serverless-application-model/blob/develop/DEVELOPMENT_GUIDE.md Convert a SAM template into a CloudFormation template using the SAM translate script. Ensure you use the correct output file path from the packaging step if performed. ```bash # Transform your SAM template into a CloudFormation template # Replace "output-template.yaml" if you didn't run the package command above or specified a different path for --output-template-file bin/sam-translate.py --template-file=output-template.yaml ``` -------------------------------- ### SAM Template with CodeDeploy Deployment Preferences Source: https://context7.com/aws/serverless-application-model/llms.txt Configures a Lambda function to use AWS CodeDeploy for safe deployments, including traffic shifting, CloudWatch alarm monitoring, and pre/post traffic hooks. ```yaml Transform: AWS::Serverless-2016-10-31 Resources: MyService: Type: AWS::Serverless::Function Properties: Handler: app.handler Runtime: python3.12 CodeUri: s3://my-bucket/app.zip AutoPublishAlias: live # creates/updates a Lambda alias on each deploy DeploymentPreference: Type: Linear10PercentEvery1Minute # or Canary10Percent5Minutes, AllAtOnce, etc. Alarms: - !Ref ErrorRateAlarm Hooks: PreTraffic: !Ref PreTrafficCheck PostTraffic: !Ref PostTrafficCheck # Role: !Ref CustomCodeDeployRole # optional; SAM creates one if omitted ``` -------------------------------- ### Environment Variables with Globals Source: https://github.com/aws/serverless-application-model/blob/develop/docs/globals.rst Global environment variables are merged with resource-specific environment variables. Resource-specific variables take precedence if names conflict. ```json { "STAGE": "Production", "TABLE_NAME": "resource-table", "NEW_VAR": "hello" } ``` -------------------------------- ### Dynamically Set S3 Location for Lambda Code Source: https://github.com/aws/serverless-application-model/blob/develop/HOWTO.md Use !Ref to dynamically set the S3 bucket and key for Lambda function code based on template parameters. ```YAML Transform: 'AWS::Serverless-2016-10-31' # Parameters are CloudFormation features to pass input # to your template when you create a stack Parameters: BucketName: Type: String CodeKey: Type: String Resources: MyFunction: Type: AWS::Serverless::Function Properties: Handler: index.handler Runtime: nodejs24.x CodeUri: # !Ref function allows you to fetch value # of parameters and other resources at runtime Bucket: !Ref BucketName Key: !Ref CodeKey ``` -------------------------------- ### Add pyenv to PATH on Windows Source: https://github.com/aws/serverless-application-model/blob/develop/DEVELOPMENT_GUIDE.md Use this command on Windows to add pyenv to your system's PATH environment variable. ```bash export PATH="/c/Users//.pyenv/libexec:$PATH" ``` -------------------------------- ### Configure CodeDeploy for Controlled Traffic Shifting Source: https://github.com/aws/serverless-application-model/blob/develop/docs/safe_lambda_deployments.rst Set up CodeDeploy with specific traffic shifting types, alarms for monitoring, and hooks for pre- or post-deployment actions. ```yaml MyLambdaFunction: Type: AWS::Serverless::Function Properties: Handler: index.handler Runtime: nodejs24.x AutoPublishAlias: live DeploymentPreference: Type: Linear10PercentEvery10Minutes Alarms: # A list of alarms that you want to monitor - !Ref AliasErrorMetricGreaterThanZeroAlarm - !Ref LatestVersionErrorMetricGreaterThanZeroAlarm Hooks: ``` -------------------------------- ### Translate SAM Template with Custom Plugin Source: https://context7.com/aws/serverless-application-model/llms.txt Translates a SAM template to a CloudFormation template, injecting a 'ManagedBy' tag into Lambda functions using a custom plugin. ```python class TagInjectorPlugin(BasePlugin): def on_before_transform_resource(self, logical_id, resource_type, resource_properties): if resource_type == "AWS::Serverless::Function": tags = resource_properties.get("Tags", {}) tags["ManagedBy"] = "sam-translator" resource_properties["Tags"] = tags boto_session = boto3.session.Session(region_name="us-west-2") iam_client = boto_session.client("iam") sam_parser = Parser() translator = Translator( managed_policy_map=None, # lazy-loaded via get_managed_policy_map callback sam_parser=sam_parser, plugins=[TagInjectorPlugin()], # injected before built-in plugins boto_session=boto_session, ) sam_template = { "Transform": "AWS::Serverless-2016-10-31", "Resources": { "MyFunc": { "Type": "AWS::Serverless::Function", "Properties": { "Handler": "app.handler", "Runtime": "python3.12", "InlineCode": "def handler(e, c): return {}", }, } }, } managed_policy_loader = ManagedPolicyLoader(iam_client) try: cfn = translator.translate( sam_template=sam_template, parameter_values={"AWS::Region": "us-west-2"}, get_managed_policy_map=lambda: managed_policy_loader.load(), ) print(list(cfn["Resources"].keys())) # e.g. ['MyFunc', 'MyFuncRole'] except InvalidDocumentException as e: for cause in e.causes: print(cause.message) ``` -------------------------------- ### transform() — High-level SAM-to-CloudFormation conversion Source: https://context7.com/aws/serverless-application-model/llms.txt A one-shot convenience function that wraps the Parser and Translator classes to return a CloudFormation template dictionary. This is ideal for programmatic use outside of CloudFormation, such as in CI pipelines or tooling. ```APIDOC ## transform() ### Description Converts a SAM template into a CloudFormation template dictionary. This function is suitable for programmatic use outside of CloudFormation. ### Method `transform` function ### Parameters - **input_fragment** (dict) - The SAM template as a Python dictionary. - **parameter_values** (dict) - A dictionary of parameter values to use for intrinsic functions. - **managed_policy_loader** (ManagedPolicyLoader) - An instance of ManagedPolicyLoader for loading IAM policies. - **passthrough_metadata** (bool) - Whether to pass through metadata from the input template. ### Request Example ```python import boto3 import json from samtranslator.yaml_helper import yaml_parse from samtranslator.public.translator import ManagedPolicyLoader from samtranslator.translator.transform import transform from samtranslator.model.exceptions import InvalidDocumentException iam_client = boto3.client("iam", region_name="us-east-1") managed_policy_loader = ManagedPolicyLoader(iam_client) sam_template = yaml_parse(""" Transform: AWS::Serverless-2016-10-31 Resources: HelloFunction: Type: AWS::Serverless::Function Properties: Handler: index.handler Runtime: python3.12 CodeUri: s3://my-bucket/my-code.zip Events: HelloApi: Type: Api Properties: Path: /hello Method: get Policies: - DynamoDBCrudPolicy: TableName: !Ref MyTable MyTable: Type: AWS::Serverless::SimpleTable """) try: cfn_template = transform( input_fragment=sam_template, parameter_values={}, managed_policy_loader=managed_policy_loader, passthrough_metadata=False, ) print(json.dumps(cfn_template, indent=2)) except InvalidDocumentException as e: print(e.message) for cause in e.causes: print(" -", cause.message) ``` ### Response #### Success Response A dictionary representing the generated CloudFormation template. #### Response Example ```json { "AWSTemplateFormatVersion": "2010-09-09", "Transform": "AWS::Serverless-2016-10-31", "Resources": { "HelloFunction": { "Type": "AWS::Lambda::Function", "Properties": { "Handler": "index.handler", "Runtime": "python3.12", "CodeUri": "s3://my-bucket/my-code.zip", "Policies": [ { "DynamoDBCrudPolicy": { "TableName": { "Ref": "MyTable" } } } ] } }, "HelloApi": { "Type": "AWS::ApiGateway::RestApi", "Properties": { "Name": "HelloApi" } }, "HelloApiMethod": { "Type": "AWS::ApiGateway::Method", "Properties": { "HttpMethod": "GET", "ResourceId": { "Ref": "HelloApi" }, "RestApiId": { "Ref": "HelloApi" }, "Integration": { "IntegrationHttpMethod": "POST", "Type": "AWS", "Uri": { "Fn::Sub": "arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function/HelloFunction/invocations" } }, "AuthorizationType": "NONE", "PathPart": "hello" } }, "HelloApiDeployment": { "Type": "AWS::ApiGateway::Deployment", "Properties": { "RestApiId": { "Ref": "HelloApi" } } }, "HelloApiStage": { "Type": "AWS::ApiGateway::Stage", "Properties": { "DeploymentId": { "Ref": "HelloApiDeployment" }, "RestApiId": { "Ref": "HelloApi" }, "StageName": "Prod" } }, "MyTable": { "Type": "AWS::DynamoDB::Table", "Properties": { "TableName": "MyTable" } } } } ``` ``` -------------------------------- ### Scoped IAM Policies for Serverless Functions Source: https://context7.com/aws/serverless-application-model/llms.txt Use policy templates to attach least-privilege IAM inline policies scoped to specific named resources. This avoids overly broad AWS-managed policies. Ensure the resource names (e.g., TableName, BucketName) are correctly referenced. ```yaml Transform: AWS::Serverless-2016-10-31 Resources: OrderProcessor: Type: AWS::Serverless::Function Properties: Handler: processor.handler Runtime: python3.12 CodeUri: s3://my-bucket/processor.zip Policies: # Scoped CRUD access to a single DynamoDB table - DynamoDBCrudPolicy: TableName: !Ref OrdersTable # Read-only access to one S3 bucket - S3ReadPolicy: BucketName: !Ref ArtifactBucket # Send messages to a specific SQS queue - SQSSendMessagePolicy: QueueName: !GetAtt NotificationQueue.QueueName # No-parameter policy: use an empty dict {} - CloudWatchPutMetricPolicy: {} # Mix with a standard AWS managed policy - AWSXRayDaemonWriteAccess # Mix with an inline policy statement - Version: "2012-10-17" Statement: - Effect: Allow Action: secretsmanager:GetSecretValue Resource: !Sub "arn:${AWS::Partition}:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:MySecret-*" OrdersTable: Type: AWS::Serverless::SimpleTable Properties: PrimaryKey: Name: orderId Type: String ArtifactBucket: Type: AWS::S3::Bucket NotificationQueue: Type: AWS::SQS::Queue ``` -------------------------------- ### Run Specific Test Method with Pytest Source: https://github.com/aws/serverless-application-model/blob/develop/INTEGRATION_TESTS.md Execute a particular test method within a test class in a specific file. Adjust the path and method names as needed. ```bash pytest --no-cov integration/single/test_basic_api.py::TestBasicApi::test_basic_api ``` -------------------------------- ### Load IAM Managed Policies with ManagedPolicyLoader Source: https://context7.com/aws/serverless-application-model/llms.txt Loads a map of IAM managed policy names to their ARNs using the ManagedPolicyLoader. This is required for resolving policy names in SAM templates. The first call may hit the IAM API, while subsequent calls use cached results. ```python import boto3 from samtranslator.public.translator import ManagedPolicyLoader iam_client = boto3.client("iam", region_name="us-east-1") loader = ManagedPolicyLoader(iam_client) # First call hits IAM API (paginated); subsequent calls return cached result. policy_map = loader.load() # {"AmazonDynamoDBFullAccess": "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess", ...} arn = policy_map.get("AmazonS3ReadOnlyAccess") print(arn) # arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess ``` -------------------------------- ### Environment Variable for Current Lambda Version Source: https://github.com/aws/serverless-application-model/blob/develop/docs/safe_lambda_deployments.rst Use an environment variable to store the current version of the Lambda function. This is recommended for hook functions to reference the version being tested. ```yaml Environment: Variables: CurrentVersion: !Ref MySafeLambdaFunction.Version ``` -------------------------------- ### Handle SAM Translator Exceptions Source: https://context7.com/aws/serverless-application-model/llms.txt Illustrates how to catch and process SAM translator exceptions, including InvalidDocumentException and its causes like InvalidResourceException. Custom validation can also raise these exceptions. ```python from samtranslator.public.exceptions import ( InvalidDocumentException, InvalidResourceException, InvalidEventException, ) from samtranslator.translator.transform import transform from samtranslator.public.translator import ManagedPolicyLoader import boto3 iam_client = boto3.client("iam", region_name="us-east-1") # Template with two bad resources bad_template = { "Transform": "AWS::Serverless-2016-10-31", "Resources": { "BadFunction": { "Type": "AWS::Serverless::Function", "Properties": { # Missing Handler & Runtime — will fail "CodeUri": "s3://bucket/key.zip", }, }, "GoodTable": { "Type": "AWS::Serverless::SimpleTable", }, }, } try: transform(bad_template, {}, ManagedPolicyLoader(iam_client)) except InvalidDocumentException as doc_err: print(doc_err.message) # "Invalid Serverless Application Specification document. Number of errors found: 1." for cause in doc_err.causes: print(type(cause).__name__, "->", cause.message) # InvalidResourceException -> Resource with id [BadFunction] is invalid. ... # doc_err.metadata aggregates metadata from all causes print(doc_err.metadata) # defaultdict(, {...}) # Raise manually for custom validation def validate_function(logical_id, props): if "Handler" not in props: raise InvalidResourceException(logical_id, "Property 'Handler' is required.") try: validate_function("MyFunc", {"Runtime": "python3.12"}) except InvalidResourceException as e: print(e.message) # "Resource with id [MyFunc] is invalid. Property 'Handler' is required." ``` -------------------------------- ### PreTraffic Hook Lambda Function Configuration Source: https://github.com/aws/serverless-application-model/blob/develop/docs/safe_lambda_deployments.rst Configures a Lambda function to act as a PreTraffic hook for CodeDeploy. This function is invoked before traffic shifting begins and must report its status back to CodeDeploy. ```yaml PreTrafficLambdaFunction: Type: AWS::Serverless::Function Properties: Handler: preTrafficHook.handler Policies: - Version: "2012-10-17" Statement: - Effect: "Allow" Action: - "codedeploy:PutLifecycleEventHookExecutionStatus" Resource: !Sub 'arn:${AWS::Partition}:codedeploy:${AWS::Region}:${AWS::AccountId}:deploymentgroup:${ServerlessDeploymentApplication}/*' - Version: "2012-10-17" Statement: - Effect: "Allow" Action: - "lambda:InvokeFunction" Resource: !GetAtt MyLambdaFunction.Arn Runtime: nodejs24.x FunctionName: 'CodeDeployHook_preTrafficHook' DeploymentPreference: Enabled: False Role: "" Environment: Variables: CurrentVersion: !Ref MyLambdaFunction.Version ```