How to Deploy a Serverless Application on AWS Lambda Using Terraform
In the ever-evolving landscape of cloud computing, serverless architecture has emerged as a powerful paradigm that enables developers to build and deploy applications without the hassle of managing server infrastructure. AWS Lambda stands out as one of the leading serverless platforms, allowing you to run code in response to events while automatically managing the computing resources. In this article, we will delve into how to deploy a serverless application on AWS Lambda using Terraform, a popular Infrastructure as Code (IaC) tool that simplifies the process of managing cloud resources.
What is AWS Lambda?
AWS Lambda is a serverless compute service that lets you run code without provisioning or managing servers. You can trigger Lambda functions through various AWS services, such as API Gateway, DynamoDB, or S3. This model allows you to focus solely on writing code while AWS handles the underlying infrastructure.
Key Benefits of Using AWS Lambda
- Cost-Effective: You pay only for the compute time you consume.
- Scalability: Automatically scales your application by running code in response to demand.
- Event-Driven: Easily integrate with other AWS services and respond to events in real time.
What is Terraform?
Terraform is an open-source tool that allows you to define and manage your cloud infrastructure using code. With its declarative approach, you can easily provision, change, and version your infrastructure safely and efficiently.
Advantages of Using Terraform
- Infrastructure as Code: Manage your infrastructure using a high-level configuration language.
- Version Control: Track changes to your infrastructure just like you would with application code.
- Multi-Cloud Support: Easily manage resources across different cloud providers.
Use Case: Creating a Simple Serverless API
In this tutorial, we will create a simple serverless API using AWS Lambda and Terraform. Our API will respond to HTTP requests and return a JSON response. Here’s a step-by-step guide to get you started.
Prerequisites
Before you begin, ensure you have the following:
- An AWS account
- Terraform installed (version 0.12 or higher)
- AWS CLI configured with your credentials
Step 1: Set Up Your Project Directory
Create a new directory for your Terraform project:
mkdir serverless-api
cd serverless-api
Step 2: Create a Lambda Function
Create a file named lambda_function.py
in your project directory. This file will contain the code for your AWS Lambda function.
import json
def lambda_handler(event, context):
return {
'statusCode': 200,
'body': json.dumps('Hello from AWS Lambda!')
}
Step 3: Create a Terraform Configuration
Next, create a file named main.tf
. This file will define the AWS resources we need for our serverless application.
provider "aws" {
region = "us-east-1"
}
resource "aws_lambda_function" "my_lambda" {
function_name = "my_serverless_api"
handler = "lambda_function.lambda_handler"
runtime = "python3.8"
source_code_hash = filebase64sha256("lambda_function.zip")
filename = "lambda_function.zip"
role = aws_iam_role.lambda_exec.arn
}
resource "aws_iam_role" "lambda_exec" {
name = "lambda_exec_role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Action = "sts:AssumeRole",
Principal = {
Service = "lambda.amazonaws.com"
},
Effect = "Allow",
Sid = ""
}]
})
}
resource "aws_api_gateway_rest_api" "my_api" {
name = "My Serverless API"
description = "API for my serverless application"
}
resource "aws_api_gateway_resource" "my_resource" {
rest_api_id = aws_api_gateway_rest_api.my_api.id
parent_id = aws_api_gateway_rest_api.my_api.root_resource_id
path_part = "hello"
}
resource "aws_api_gateway_method" "my_method" {
rest_api_id = aws_api_gateway_rest_api.my_api.id
resource_id = aws_api_gateway_resource.my_resource.id
http_method = "GET"
authorization = "NONE"
}
resource "aws_api_gateway_integration" "my_integration" {
rest_api_id = aws_api_gateway_rest_api.my_api.id
resource_id = aws_api_gateway_resource.my_resource.id
http_method = aws_api_gateway_method.my_method.http_method
integration_http_method = "POST"
type = "AWS_PROXY"
uri = aws_lambda_function.my_lambda.invoke_arn
}
resource "aws_api_gateway_deployment" "my_deployment" {
depends_on = [aws_api_gateway_integration.my_integration]
rest_api_id = aws_api_gateway_rest_api.my_api.id
stage_name = "dev"
}
Step 4: Package and Deploy Your Lambda Function
Before deploying, you need to package your Lambda function. Create a ZIP file of your Lambda function:
zip lambda_function.zip lambda_function.py
Now, deploy your infrastructure using Terraform:
terraform init
terraform apply
Review the changes and type yes
to confirm the deployment.
Step 5: Test Your API
Once the deployment is complete, Terraform will output the URL of your API. To test it, use curl
or any REST client:
curl https://<API_ID>.execute-api.us-east-1.amazonaws.com/dev/hello
You should see a response like:
{"statusCode":200,"body":"Hello from AWS Lambda!"}
Troubleshooting Common Issues
- Permission Denied: Ensure your IAM role has the necessary permissions to execute the Lambda function.
- Invalid Lambda Handler: Double-check that the handler name matches the function defined in your code.
- API Gateway Errors: Verify that the API Gateway methods and integrations are correctly set up.
Conclusion
Deploying a serverless application on AWS Lambda using Terraform can streamline your development process and enhance scalability. With the steps outlined in this article, you can create a simple serverless API and understand the foundational concepts of AWS Lambda and Terraform. As you grow more comfortable, explore additional features such as monitoring, logging, and advanced integrations to enhance the functionality of your applications. Happy coding!