How to Deploy a Serverless Application on AWS with Terraform
In recent years, serverless architecture has gained immense traction among developers looking for scalable and efficient solutions. AWS Lambda, Amazon's serverless computing service, enables you to run code without provisioning or managing servers, allowing you to focus on writing code instead of worrying about infrastructure. When combined with Terraform, an Infrastructure as Code (IaC) tool, you can automate the deployment of your serverless applications with ease. In this article, we will guide you through the entire process of deploying a serverless application on AWS using Terraform, complete with code examples and actionable insights.
What is Serverless Computing?
Serverless computing is a cloud computing execution model where the cloud provider dynamically manages the allocation and provisioning of servers. This means you can run your applications without needing to manage the server infrastructure. You only pay for the resources you consume, making it a cost-effective solution for many use cases, including:
- Microservices: Deploying small, independent services that can scale automatically.
- Real-time Data Processing: Handling events from data streams, IoT devices, or APIs.
- Web Applications: Building responsive applications that can handle varying loads seamlessly.
Why Use Terraform for Serverless Deployment?
Terraform is an open-source tool that allows you to define your infrastructure using a high-level configuration language. It provides several benefits:
- Infrastructure as Code: Define your infrastructure in code, making it version-controlled and easily reproducible.
- Multi-Provider Support: Deploy applications across various cloud providers, not just AWS.
- State Management: Terraform keeps track of your infrastructure state, allowing for easy updates and rollbacks.
Prerequisites
Before we start deploying our serverless application, ensure you have the following:
- An AWS account
- Terraform installed (version 0.12 or higher)
- AWS CLI installed and configured
Step-by-Step Guide to Deploy a Serverless Application on AWS with Terraform
Step 1: Set Up Your Project Directory
Create a new directory for your project and navigate into it:
mkdir my-serverless-app
cd my-serverless-app
Step 2: Create a Terraform Configuration File
Create a file named main.tf
in your project directory. This file will contain the configuration for our AWS resources.
provider "aws" {
region = "us-east-1"
}
resource "aws_lambda_function" "my_function" {
function_name = "MyServerlessFunction"
handler = "index.handler"
runtime = "nodejs14.x"
role = aws_iam_role.lambda_exec.arn
filename = "function.zip"
source_code_hash = filebase64sha256("function.zip")
}
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_iam_policy_attachment" "lambda_policy" {
name = "lambda_policy_attachment"
roles = [aws_iam_role.lambda_exec.name]
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}
Step 3: Create Your Lambda Function Code
In the same project directory, create a file named index.js
and add the following code:
exports.handler = async (event) => {
console.log("Event: ", JSON.stringify(event, null, 2));
return {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
};
Next, you need to zip your function code:
zip function.zip index.js
Step 4: Initialize Terraform
Run the following command to initialize your Terraform project. This will download the necessary provider plugins.
terraform init
Step 5: Plan Your Deployment
Before deploying, it’s good practice to preview the changes Terraform will make to your AWS environment:
terraform plan
Step 6: Apply Your Configuration
Now you’re ready to deploy your serverless application. Run the following command to apply your configuration:
terraform apply
Confirm the action by typing yes
when prompted.
Step 7: Testing Your Lambda Function
Once the deployment is complete, you can test your Lambda function using the AWS Console or the AWS CLI. To invoke your function from the CLI, use the following command:
aws lambda invoke --function-name MyServerlessFunction output.txt
Check the output.txt
file for the response.
Troubleshooting Common Issues
- Permissions Error: Ensure your AWS IAM role has the necessary permissions. Review the
AWSLambdaBasicExecutionRole
policy. - Incorrect Runtime: Verify that you are using a compatible runtime for your code. Check the AWS Lambda documentation for supported runtimes.
Conclusion
Deploying a serverless application on AWS with Terraform simplifies the process of managing your infrastructure while allowing you to focus on writing code. By following the steps outlined in this guide, you can set up and deploy your serverless application quickly and efficiently. As you grow more familiar with Terraform and serverless architecture, you can explore more advanced features like API Gateway integration, event triggers, and more. Happy coding!