Using Lambda with infrastructure as code (IaC)
Lambda functions rarely run in isolation. Instead, they often form part of a serverless application with other resources such as
databases, queues, and storage. With infrastructure as code (IaC)
IaC tools for Lambda
- Amazon CloudFormation
-
CloudFormation is the foundational IaC service from Amazon. You can use YAML or JSON templates to model and provision your entire Amazon infrastructure, including Lambda functions. CloudFormation handles the complexities of creating, updating, and deleting your Amazon resources.
- Amazon Serverless Application Model (Amazon SAM)
-
Amazon SAM is an open-source framework built on top of CloudFormation. It provides a simplified syntax for defining serverless applications. Use Amazon SAM templates to quickly provision Lambda functions, APIs, databases, and event sources with just a few lines of YAML.
- Amazon Cloud Development Kit (Amazon CDK)
-
The CDK is a code-first approach to IaC. You can define your Lambda-based architecture using TypeScript, JavaScript, Python, Java, C#/.Net, or Go. Choose your preferred language and use programming elements like parameters, conditionals, loops, composition, and inheritance to define the desired outcome of your infrastructure. The CDK then generates the underlying CloudFormation templates for deployment. For an example of how to use Lambda with CDK, see Deploying Lambda functions with the Amazon CDK.
Amazon also provides a service called Amazon Infrastructure Composer to develop IaC templates using a simple graphical interface. With Infrastructure Composer, you design an application architecture by dragging, grouping, and connecting Amazon Web Services services in a visual canvas. Infrastructure Composer then creates an Amazon SAM template or an Amazon CloudFormation template from your design that you can use to deploy your application.
In the Getting started with IaC for Lambda section below, you use Infrastructure Composer to develop a template for a serverless application based on an existing Lambda function.
Getting started with IaC for Lambda
In this tutorial, you can get started using IaC with Lambda by creating an Amazon SAM template from an existing Lambda function and then building out a serverless application in Infrastructure Composer by adding other Amazon resources.
As you carry out this tutorial, you’ll learn some fundamental concepts, like how Amazon resources are specified in Amazon SAM. You’ll also learn how to use Infrastructure Composer to build a serverless application you can deploy using Amazon SAM or Amazon CloudFormation.
To complete this tutorial, you’ll carry out the following steps:
-
Create an example Lambda function
-
Use the Lambda console to view the Amazon SAM template for the function
-
Export your function’s configuration to Amazon Infrastructure Composer and design a simple serverless application based on your function’s configuration
-
Save an updated Amazon SAM template you can use as a basis to deploy your serverless application
Prerequisites
In this tutorial, you use Infrastructure Composer’s local sync feature to save your template and code files to your local build machine. To use this feature, you need a browser that supports the File System Access API, which allows web applications to read, write, and save files in your local file system . We recommend using either Google Chrome or Microsoft Edge. For more information about the File System Access API, see What is the File System Access API?
Create a Lambda function
In this first step, you create a Lambda function you can use to complete the rest of the tutorial. To keep things simple, you use the Lambda console to create a basic 'Hello world' function using the Python 3.11 runtime.
To create a 'Hello world' Lambda function using the console
-
Open the Lambda console
. -
Choose Create function.
-
Leave Author from scratch selected, and under Basic information, enter
LambdaIaCDemo
for Function name. -
For Runtime, select Python 3.11.
-
Choose Create function.
View the Amazon SAM template for your function
Before you export your function configuration to Infrastructure Composer, use the Lambda console to view your function's current configuration as an Amazon SAM template. By following the steps in this section, you'll learn about the anatomy of an Amazon SAM template and how to define resources like Lambda functions to start specifying a serverless application.
To view the Amazon SAM template for your function
-
Open the Functions page
of the Lambda console. -
Choose the function you just created (
LambdaIaCDemo
). -
In the Function overview pane, choose Template.
In place of the diagram representing your function’s configuration, you’ll see an Amazon SAM template for your function. The template should look like the following.
# This AWS SAM template has been generated from your function's # configuration. If your function has one or more triggers, note # that the AWS resources associated with these triggers aren't fully # specified in this template and include placeholder values.Open this template # in AWS Application Composer or your favorite IDE and modify # it to specify a serverless application with other AWS resources. AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: An AWS Serverless Specification template describing your function. Resources: LambdaIaCDemo: Type: AWS::Serverless::Function Properties: CodeUri: . Description: '' MemorySize: 128 Timeout: 3 Handler: lambda_function.lambda_handler Runtime: python3.11 Architectures: - x86_64 EventInvokeConfig: MaximumEventAgeInSeconds: 21600 MaximumRetryAttempts: 2 EphemeralStorage: Size: 512 RuntimeManagementConfig: UpdateRuntimeOn: Auto SnapStart: ApplyOn: None PackageType: Zip Policies: Statement: - Effect: Allow Action: - logs:CreateLogGroup Resource: arn:aws:logs:us-east-1:123456789012:* - Effect: Allow Action: - logs:CreateLogStream - logs:PutLogEvents Resource: - >- arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/LambdaIaCDemo:*
Let’s take a moment to look at the YAML template for your function and understand some key concepts.
The template starts with the declaration Transform: AWS::Serverless-2016-10-31
. This declaration is required because behind
the scenes, Amazon SAM templates are deployed through Amazon CloudFormation. Using the Transform
statement identifies the template as an Amazon SAM
template file.
Following the Transform
declaration comes the Resources
section. This is where the Amazon resources you want to
deploy with your Amazon SAM template are defined. Amazon SAM templates can contain a combination of Amazon SAM resources and Amazon CloudFormation resources. This is
because during deployment, Amazon SAM templates expand to Amazon CloudFormation templates, so any valid Amazon CloudFormation syntax can be added to an Amazon SAM template.
At the moment, there is just one resource defined in the Resources
section of the template, your Lambda function
LambdaIaCDemo
. To add a Lambda function to an Amazon SAM template, you use the AWS::Serverless::Function
resource type. The Properties
of a Lambda
function resource define the function’s runtime, function handler, and other configuration options. The path to your function’s source code
that Amazon SAM should use to deploy the function is also defined here. To learn more about Lambda function resources in Amazon SAM, see
AWS::Serverless::Function
in the Amazon SAM Developer Guide.
As well as the function properties and configurations, the template also specifies an Amazon Identity and Access Management (IAM) policy for your function. This
policy gives your function permission to write logs to Amazon CloudWatch Logs. When you create a function in the Lambda console, Lambda automatically
attaches this policy to your function. To learn more about specifying an IAM policy for a function in an Amazon SAM template, see the
policies
property on the AWS::Serverless::Function
page of the Amazon SAM Developer Guide.
To learn more about the structure of Amazon SAM templates, see Amazon SAM template anatomy.
Use Amazon Infrastructure Composer to design a serverless application
To start building out a simple serverless application using your function’s Amazon SAM template as a starting point, you export your function configuration to Infrastructure Composer and activate Infrastructure Composer’s local sync mode. Local sync automatically saves your function’s code and your Amazon SAM template to your local build machine and keeps your saved template synced as you add other Amazon resources in Infrastructure Composer.
To export your function to Infrastructure Composer
-
In the Function Overview pane, choose Export to Application Composer.
To export your function's configuration and code to Infrastructure Composer, Lambda creates an Amazon S3 bucket in your account to temporarily store this data.
-
In the dialog box, choose Confirm and create project to accept the default name for this bucket and export your function's configuration and code to Infrastructure Composer.
-
(Optional) To choose another name for the Amazon S3 bucket that Lambda creates, enter a new name and choose Confirm and create project. Amazon S3 bucket names must be globally unique and follow the bucket naming rules.
Selecting Confirm and create project opens the Infrastructure Composer console. On the canvas, you’ll see your Lambda function.
-
From the Menu dropdown, choose Activate local sync.
-
In the dialog box that opens, choose Select folder and select a folder on your local build machine.
-
Choose Activate to activate local sync.
To export your function to Infrastructure Composer, you need permission to use certain API actions. If you're unable to export your function, see Required permissions and make sure you have the permissions you need.
Note
Standard Amazon S3 pricing
To avoid additional charges being added to your Amazon Web Services account, follow the instructions in Deleting a bucket after you have exported your function to Infrastructure Composer. For more information about the Amazon S3 bucket Lambda creates, see Using Amazon Lambda with Amazon Infrastructure Composer.
To design your serverless application in Infrastructure Composer
After activating local sync, changes you make in Infrastructure Composer will be reflected in the Amazon SAM template saved on your local build machine. You can now drag and drop additional Amazon resources onto the Infrastructure Composer canvas to build out your application. In this example, you add an Amazon SQS simple queue as a trigger for your Lambda function and a DynamoDB table for the function to write data to.
-
Add an Amazon SQS trigger to your Lambda function by doing the following:
-
In the search field in the Resources palette, enter
SQS
. -
Drag the SQS Queue resource onto your canvas and position it to the left of your Lambda function.
-
Choose Details, and for Logical ID enter
LambdaIaCQueue
. -
Choose Save.
-
Connect your Amazon SQS and Lambda resources by clicking on the Subscription port on the SQS queue card and dragging it to the left hand port on the Lambda function card. The appearance of a line between the two resources indicates a successful connection. Infrastructure Composer also displays a message at the bottom of the canvas indicating that the two resources are successfully connected.
-
-
Add an Amazon DynamoDB table for your Lambda function to write data to by doing the following:
-
In the search field in the Resources palette, enter
DynamoDB
. -
Drag the DynamoDB Table resource onto your canvas and position it to the right of your Lambda function.
-
Choose Details, and for Logical ID enter
LambdaIaCTable
. -
Choose Save.
-
Connect the DynamoDB table to your Lambda function by clicking on the right hand port of the Lambda function card and dragging it to the left hand port on the DynamoDB card.
-
Now that you’ve added these extra resources, let’s take a look at the updated Amazon SAM template Infrastructure Composer has created.
To view your updated Amazon SAM template
-
On the Infrastructure Composer canvas, choose Template to switch from the canvas view to the template view.
Your Amazon SAM template should now contain the following additional resources and properties:
-
An Amazon SQS queue with the identifier
LambdaIaCQueue
LambdaIaCQueue: Type: AWS::SQS::Queue Properties: MessageRetentionPeriod: 345600
When you add an Amazon SQS queue using Infrastructure Composer, Infrastructure Composer sets the
MessageRetentionPeriod
property. You can also set theFifoQueue
property by selecting Details on the SQS Queue card and checking or unchecking Fifo queue.To set other properties for your queue, you can manually edit the template to add them. To learn more about the
AWS::SQS::Queue
resource and its available properties, see Amazon::SQS::Queue in the Amazon CloudFormation User Guide. -
An
Events
property in your Lambda function definition that specifies the Amazon SQS queue as a trigger for the functionEvents: LambdaIaCQueue: Type: SQS Properties: Queue: !GetAtt LambdaIaCQueue.Arn BatchSize: 1
The
Events
property consists of an event type and a set of properties that depend on the type. To learn about the different Amazon Web Services services you can configure to trigger a Lambda function and the properties you can set, see EventSource in the Amazon SAM Developer Guide. -
A DynamoDB table with the identifier
LambdaIaCTable
LambdaIaCTable: Type: AWS::DynamoDB::Table Properties: AttributeDefinitions: - AttributeName: id AttributeType: S BillingMode: PAY_PER_REQUEST KeySchema: - AttributeName: id KeyType: HASH StreamSpecification: StreamViewType: NEW_AND_OLD_IMAGES
When you add a DynamoDB table using Infrastructure Composer, you can set your table's keys by choosing Details on the DynamoDB table card and editing the key values. Infrastructure Composer also sets default values for a number of other properties including
BillingMode
andStreamViewType
.To learn more about these properties and other properties you can add to your Amazon SAM template, see Amazon::DynamoDB::Table in the Amazon CloudFormation User Guide.
-
A new IAM policy that gives your function permission to perform CRUD operations on the DynamoDB table you added.
Policies: ... - DynamoDBCrudPolicy: TableName: !Ref LambdaIaCTable
The complete final Amazon SAM template should look like the following.
AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: An AWS Serverless Specification template describing your function. Resources: LambdaIaCDemo: Type: AWS::Serverless::Function Properties: CodeUri: . Description: '' MemorySize: 128 Timeout: 3 Handler: lambda_function.lambda_handler Runtime: python3.11 Architectures: - x86_64 EventInvokeConfig: MaximumEventAgeInSeconds: 21600 MaximumRetryAttempts: 2 EphemeralStorage: Size: 512 RuntimeManagementConfig: UpdateRuntimeOn: Auto SnapStart: ApplyOn: None PackageType: Zip Policies: - Statement: - Effect: Allow Action: - logs:CreateLogGroup Resource: arn:aws:logs:us-east-1:594035263019:* - Effect: Allow Action: - logs:CreateLogStream - logs:PutLogEvents Resource: - arn:aws:logs:us-east-1:594035263019:log-group:/aws/lambda/LambdaIaCDemo:* - DynamoDBCrudPolicy: TableName: !Ref LambdaIaCTable Events: LambdaIaCQueue: Type: SQS Properties: Queue: !GetAtt LambdaIaCQueue.Arn BatchSize: 1 Environment: Variables: LAMBDAIACTABLE_TABLE_NAME: !Ref LambdaIaCTable LAMBDAIACTABLE_TABLE_ARN: !GetAtt LambdaIaCTable.Arn LambdaIaCQueue: Type: AWS::SQS::Queue Properties: MessageRetentionPeriod: 345600 LambdaIaCTable: Type: AWS::DynamoDB::Table Properties: AttributeDefinitions: - AttributeName: id AttributeType: S BillingMode: PAY_PER_REQUEST KeySchema: - AttributeName: id KeyType: HASH StreamSpecification: StreamViewType: NEW_AND_OLD_IMAGES
Deploy your serverless application using Amazon SAM (optional)
If you want to use Amazon SAM to deploy a serverless application using the template you just created in Infrastructure Composer, you first need to install the Amazon SAM CLI. To do this, follow the instructions in Installing the Amazon SAM CLI.
Before you deploy your application, you also need to update the function code that Infrastructure Composer saved along with your template. At the moment, the lambda_function.py
file that Infrastructure Composer saved contains only
the basic 'Hello world' code that Lambda provided when you created the function.
To update your function code, copy the following code and paste it into the lambda_function.py
file Infrastructure Composer saved to
your local build machine. You specified the directory for Infrastructure Composer to save this file to when you activated Local Sync mode.
This code accepts a key value pair in a message from the Amazon SQS queue you created in Infrastructure Composer. If both the key and value are strings, the code then uses them to write an item to the DynamoDB table defined in your template.
import boto3 import os import json # define the DynamoDB table that Lambda will connect to tablename = os.environ['LAMBDAIACTABLE_TABLE_NAME'] # create the DynamoDB resource dynamo = boto3.client('dynamodb') def lambda_handler(event, context): # get the message out of the SQS event message = event['Records'][0]['body'] data = json.loads(message) # write event data to DDB table if check_message_format(data): key = next(iter(data)) value = data[key] dynamo.put_item( TableName=tablename, Item={ 'id': {'S': key}, 'Value': {'S': value} } ) else: raise ValueError("Input data not in the correct format") # check that the event object contains a single key value # pair that can be written to the database def check_message_format(message): if len(message) != 1: return False key, value = next(iter(message.items())) if not (isinstance(key, str) and isinstance(value, str)): return False else: return True
To deploy your serverless application
To deploy your application using the Amazon SAM CLI, carry out the following steps. For your function to build and deploy correctly,
Python version 3.11 must be installed on your build machine and on your PATH
.
-
Run the following command from the directory in which Infrastructure Composer saved your
template.yaml
andlambda_function.py
files.sam build
This command gathers the build artifacts for your application and places them in the proper format and location to deploy them.
-
To deploy your application and create the Lambda, Amazon SQS, and DynamoDB resources specified in your Amazon SAM template, run the following command.
sam deploy --guided
Using the
--guided
flag means that Amazon SAM will show you prompts to guide you through the deployment process. For this deployment, accept the default options by pressing Enter.
During the deployment process, Amazon SAM creates the following resources in your Amazon Web Services account:
-
An Amazon CloudFormation stack named
sam-app
-
A Lambda function with the name format
sam-app-LambdaIaCDemo-
99VXPpYQVv1M
-
An Amazon SQS queue with the name format
sam-app-LambdaIaCQueue-
xL87VeKsGiIo
-
A DynamoDB table with the name format
sam-app-LambdaIaCTable-
CN0S66C0VLNV
Amazon SAM also creates the necessary IAM roles and policies so that your Lambda function can read messages from the Amazon SQS queue and perform CRUD operations on the DynamoDB table.
Testing your deployed application (optional)
To confirm that your serverless application deployed correctly, send a message to your Amazon SQS queue containing a key value pair and check that Lambda writes an item into your DynamoDB table using these values.
To test your serverless application
-
Open the Queues
page of the Amazon SQS console and select the queue that Amazon SAM created from your template. The name has the format sam-app-LambdaIaCQueue-
.xL87VeKsGiIo
-
Choose Send and receive messages and paste the following JSON into the Message body in the Send message section.
{ "myKey": "myValue" }
-
Choose Send message.
Sending your message to the queue causes Lambda to invoke your function through the event source mapping defined in your Amazon SAM template. To confirm that Lambda has invoked your function as expected, confirm that an item has been added to your DynamoDB table.
-
Open the Tables
page of the DynamoDB console and select your table. The name has the format sam-app-LambdaIaCTable-
.CN0S66C0VLNV
-
Choose Explore table items. In the Items returned pane, you should see an item with the id
myKey
and the ValuemyValue
.