AWS Lambda with Terraform: A Step-by-Step Guide
AWS Lambda with Terraform: A Step-by-Step Guide
Terraform is a powerful tool for managing infrastructure as code (IaC). AWS Lambda allows you to run code without provisioning or managing servers. Combining these two is the most effective way to build scalable and reusable serverless architectures.
In this guide, we will create an AWS Lambda function from scratch using Terraform.
<div class="toc"> <ul> <li><a href="#prerequisites">Prerequisites</a></li> <li><a href="#step-1-project-structure">Step 1: Project Structure</a></li> <li><a href="#step-2-creating-iam-role">Step 2: Creating IAM Role</a></li> <li><a href="#step-3-preparing-lambda-code">Step 3: Preparing Lambda Code</a></li> <li><a href="#step-4-defining-lambda-with-terraform">Step 4: Defining Lambda with Terraform</a></li> <li><a href="#step-5-deployment">Step 5: Deployment</a></li> <li><a href="#step-6-cleanup">Step 6: Cleanup</a></li> <li><a href="#conclusion">Conclusion</a></li> </ul> </div>Prerequisites
Before starting, ensure you have the following:
- AWS Account: A user with access keys.
- AWS CLI: Installed and configured (
aws configure). - Terraform: Installed (v1.0+).
Step 1: Project Structure
Create your project directory and prepare the following files:
mkdir lambda-terraform-demo
cd lambda-terraform-demo
touch main.tf variables.tf outputs.tf lambda_function.py
Start by defining the AWS provider in main.tf:
provider "aws" {
region = "eu-central-1" # Or your preferred region
}
Step 2: Creating IAM Role
The Lambda function needs an IAM role to execute. This role grants Lambda permission to access AWS services (e.g., CloudWatch Logs).
# IAM Role for Lambda (Assume Role Policy)
resource "aws_iam_role" "lambda_exec" {
name = "serverless_lambda"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Action = "sts:AssumeRole"
Effect = "Allow"
Sid = ""
Principal = {
Service = "lambda.amazonaws.com"
}
}
]
})
}
# Basic Permissions for CloudWatch Logs
resource "aws_iam_role_policy_attachment" "lambda_policy" {
role = aws_iam_role.lambda_exec.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}
Step 3: Preparing Lambda Code
Let's create a simple Python function. Open lambda_function.py:
def lambda_handler(event, context):
print("Lambda triggered via Terraform!")
return {
'statusCode': 200,
'body': 'Hello, Terraform!'
}
Step 4: Defining Lambda with Terraform
Now we will define the Lambda function itself. Terraform needs to zip the code before uploading it to AWS.
# Zip the Python code
data "archive_file" "lambda_zip" {
type = "zip"
source_file = "lambda_function.py"
output_path = "lambda_function_payload.zip"
}
# Lambda Function Resource
resource "aws_lambda_function" "test_lambda" {
# Use local zip file
filename = "lambda_function_payload.zip"
function_name = "lambda_function_name"
role = aws_iam_role.lambda_exec.arn
handler = "lambda_function.lambda_handler"
# Hash check to redeploy on code changes
source_code_hash = data.archive_file.lambda_zip.output_base64sha256
runtime = "python3.9"
environment {
variables = {
foo = "bar"
}
}
}
Step 5: Deployment
Run the following commands in your terminal to apply the configuration:
-
Initialize: Downloads Terraform and required plugins.
terraform init -
Plan: See the changes to be made.
terraform plan -
Apply: Create the resources.
terraform apply -auto-approve
Once completed, you can view your Lambda function in the AWS Console and run it from the "Test" tab.
Step 6: Cleanup
To avoid incurring costs after you are done testing, you can delete the resources:
terraform destroy -auto-approve
Conclusion
In this guide, you learned how to automate a basic AWS Lambda function using Terraform. The IaC approach ensures your infrastructure is versionable, testable, and reproducible.
For more advanced topics, check out our AWS Consultancy services or get Terraform Consultancy support for complex infrastructures. You can also explore other articles on DevOpsN for container-based solutions.
Kaynak / Source: https://awsfundamentals.com/blog/aws-lambda-with-terraform