Terraform AWS Lambda Function Deployment Example: A Step-by-Step Guide
In this tutorial, we will explore how to deploy AWS Lambda functions using Terraform. Terraform is a popular infrastructure as code (IaC) tool that allows you to manage and provision infrastructure resources, including AWS Lambda functions.
Prerequisites
Before you start, make sure you have the following prerequisites:
- AWS account with the necessary credentials set up
- Terraform installed on your machine
- A code editor or IDE of your choice
Step 1: Create a New Terraform Configuration File
Create a new file called main.tf and add the following code:
provider "aws" {
region = "us-west-2"
}
resource "aws_lambda_function" "example" {
filename = "lambda_function_payload.zip"
function_name = "example_lambda_function"
handler = "index.handler"
runtime = "nodejs14.x"
role = aws_iam_role.lambda_exec.arn
}
resource "aws_iam_role" "lambda_exec" {
name = "example_lambda_exec"
description = "Execution role for example lambda function"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "lambda.amazonaws.com"
}
}
]
})
}
This code creates a new AWS Lambda function with the necessary execution role.
Step 2: Create a New Lambda Function Payload
Create a new file called index.js and add the following code:
exports.handler = async (event) => {
console.log('Received event:', event)
return {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
};
This code creates a simple Lambda function that returns a Hello World message.
Step 3: Zip the Lambda Function Payload
Zip the index.js file into a new file called lambda_function_payload.zip.
Step 4: Initialize Terraform
Run the following command to initialize Terraform:
terraform init
Step 5: Apply the Terraform Configuration
Run the following command to apply the Terraform configuration:
terraform apply
This will create the AWS Lambda function and execution role in your AWS account.
Common Mistakes
Here are some common mistakes to watch out for:
- Make sure you have the correct AWS credentials set up
- Make sure you have the correct Terraform version installed
- Make sure you have the correct Lambda function payload zipped and uploaded
Conclusion
In this tutorial, we learned how to deploy an AWS Lambda function using Terraform. We created a new Terraform configuration file, created a new Lambda function payload, zipped the payload, initialized Terraform, and applied the Terraform configuration. We also covered some common mistakes to watch out for.

Leave a Reply