How do I deploy an AWS Lambda function using container images?
Overview
In this guide, you’ll learn how to deploy an AWS Lambda function using a container image. We’ll use Amazon Elastic Container Registry (ECR) to store the container image and create a Lambda function that uses this image.
Steps
- Create an ECR Repository: We need a place to store our container image.
- Define IAM Roles and Policies: Lambda needs permissions to fetch the container image from ECR.
- Deploy the Lambda Function: We’ll create a Lambda function using the container image from ECR.
Terraform Program
Below is the complete code to achieve the above steps. It includes comments to explain each part.
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
// Create an ECR repository to store our container image
const example = new aws.ecr.Repository("example", {name: "example-repo"});
// IAM role that the Lambda function will assume
const lambdaExecRole = new aws.iam.Role("lambda_exec_role", {
name: "lambda_exec_role",
assumeRolePolicy: JSON.stringify({
Version: "2012-10-17",
Statement: [{
Action: "sts:AssumeRole",
Effect: "Allow",
Principal: {
Service: "lambda.amazonaws.com",
},
}],
}),
});
// IAM policy to allow the Lambda function to read the ECR image
const lambdaExecPolicy = new aws.iam.RolePolicy("lambda_exec_policy", {
name: "lambda_exec_policy",
role: lambdaExecRole.name,
policy: JSON.stringify({
Version: "2012-10-17",
Statement: [{
Action: [
"ecr:GetDownloadUrlForLayer",
"ecr:BatchGetImage",
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
],
Effect: "Allow",
Resource: "*",
}],
}),
});
// Create the Lambda function
const exampleFunction = new aws.lambda.Function("example", {
name: "example_lambda_function",
role: lambdaExecRole.arn,
packageType: "Image",
imageUri: pulumi.interpolate`${example.repositoryUrl}:latest`,
});
export const lambdaFunctionName = exampleFunction.name;
export const lambdaFunctionArn = exampleFunction.arn;
export const ecrRepositoryUrl = example.repositoryUrl;
Key Points
- ECR Repository: Stores your container image.
- IAM Role: Grants necessary permissions for Lambda to pull the image and write logs.
- Lambda Function: Defined with the container image from ECR.
Summary
By following these steps, you’ve successfully deployed an AWS Lambda function using a container image. This setup includes creating an ECR repository, defining the necessary IAM roles and policies, and then deploying the Lambda function with the specified image.
Deploy this code
Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.
Sign upNew to Pulumi?
Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.
Sign upThank you for your feedback!
If you have a question about how to use Pulumi, reach out in Community Slack.
Open an issue on GitHub to report a problem or suggest an improvement.