Skip to main content

Be a Problem Solver

Deploying AWS Lambda Functions in Different Environments with AWS SAM

Table of Contents

When developing Lambda functions, you may need to verify the behavior of your code in a test environment before deploying it to production. For example, your Lambda function needs to send a email to your client, but you don’t want to disturb your client while still developing the code. In this post, we’ll explore how to use the AWS Serverless Application Model (SAM) and samconfig.toml to manage different environments for your Lambda functions.

The source code for this post is available here.

# Prerequisites

Before you start, ensure that you have finished reading my previous post on Configuring AWS Lambda Deployment via AWS SAM.

# Describing the Lambda Function

Let’s consider a simple Lambda function that emulates sending an email to a client. From the code snippet below, you can see that the function reads the email address from the environment variable EMAIL_ADDRESS and prints the email content.

import os

def lambda_handler(event, context):
    try:
        # Read email address from the environment
        email_address = os.environ.get("EMAIL_ADDRESS")

        # Print out the email address
        print(f"Email address is: {email_address}")

        return {"statusCode": 200, "body": f"Email address is: {email_address}"}

    except Exception as e:
        return {"statusCode": 500, "body": f"An error occurred: {str(e)}"}

# Template configuration

In the Parameters section of the template.yaml file, we define an environment parameter that specifies the environment in which the Lambda function will run. This parameter has two allowed values: test and prod.

Parameters:
  Environment:
    Type: String
    Default: "test"
    AllowedValues:
      - test
      - prod

To change the behavior of the Lambda function based on the environment variable, the Mappings section (similar to a dictionary in Python) defines different EmailAddress values for the test and prod environments.

Mappings:
  EmailAddress:
    test:
      status: "test@gmail.com"
    prod:
      status: "prod@gmail.com"

When defining the Lambda function, we set the FunctionName property to send-email-${Environment}. This allows us to create two different Lambda function endpoints based on the Environment parameter. Additionally, EMAIL_ADDRESS changes based on the environment parameter. For instance, when the environment is set to test:

  1. FunctionName is send-email-test,
  2. EMAIL_ADDRESS is test@gmail.com.
SendEmailFunction:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: !Sub "send-email-${Environment}"
      CodeUri: src/
      Handler: app.lambda_handler
      Runtime: python3.11
      Environment:
        Variables:
          EMAIL_ADDRESS: !FindInMap [EmailAddress, !Ref Environment, status]

# SAM configuration file

In samconfig.toml, you can define the configurations for the test and prod environments. As shown in the file, the parameter_overrides flag sets the Environment to either test or prod. This setting is linked to the Environment parameter in the template.yaml file. Note that the stack name and S3 bucket name differ for each environment.

Imgur

# Deploying the Lambda function in different environments

To deploy the Lambda function across different environments, use the --config-env flag to change configurations from the samconfig.toml file. For example, to deploy the Lambda function in the test environment, use the following command:

sam build --config-env test && sam package --config-env test && sam deploy --config-env test

In the deployment summary, you will see that the configuration for the test environment is used. Once the deployment is complete, a stack named send-email-test is created in AWS CloudFormation. You can then test the Lambda function to verify that the test email address is printed out.

Imgur Imgur

Similarly, deploy the Lambda function in the prod environment by running the following command:

sam build && sam package && sam deploy

Note that prod is the default environment, so you don’t need to specify the --config-env flag. ou can test the Lambda function to confirm that it prints the prod email address.

Imgur Imgur

# Clean up

To clean up the resources in both environments, run the following commands:

sam delete --config-env test
sam delete # for prod environment

# Summary

  1. The samconfig.toml file can store various configurations for different environments, enabling straightforward deployment of the Lambda function across multiple environments.
  2. By using Mappings with an Environment parameter in the template.yaml file, you can modify the behavior of the Lambda function across different configurations