Step-by-step Guide to Building Serverless Applications on AWS with Terraform
In today’s fast-paced tech landscape, serverless architecture has emerged as a game-changer for developers. By abstracting infrastructure management, it allows teams to focus more on building applications rather than managing servers. Coupled with Terraform, a powerful tool for provisioning infrastructure as code, developers can seamlessly deploy serverless applications on AWS. This article will guide you through the process of creating serverless applications using AWS and Terraform, providing you with clear code examples and actionable insights.
What is Serverless Architecture?
Before diving into the technicalities, let’s define what serverless architecture entails. Serverless doesn't mean there are no servers; rather, it allows developers to build and run applications without managing the underlying infrastructure. AWS Lambda is a prime example of a serverless compute service that lets you execute code in response to events without provisioning or managing servers.
Use Cases for Serverless Applications
- Microservices: Develop small, independent services that can scale automatically.
- Web Applications: Build dynamic websites that can handle varying traffic levels.
- Data Processing: Execute data transformations or ETL processes triggered by events.
- IoT Backends: Process data from Internet of Things devices efficiently.
Why Use Terraform for Serverless Applications?
Terraform is an open-source infrastructure as code (IaC) tool that allows you to define and manage your infrastructure using a declarative configuration language. Benefits of using Terraform include:
- Version Control: Infrastructure changes can be tracked in version control systems.
- Reusable Modules: Create reusable configurations for different environments.
- Multi-Cloud Support: Manage resources across multiple cloud providers.
Prerequisites
Before we get started, ensure you have the following:
- An AWS account
- Terraform installed on your machine
- Basic knowledge of AWS services (Lambda, API Gateway, IAM)
Step 1: Set Up Your Terraform Environment
First, create a directory for your Terraform project:
mkdir my-serverless-app
cd my-serverless-app
Next, initialize your Terraform project:
terraform init
This command initializes the project and downloads the necessary providers.
Step 2: Define Your Lambda Function
Create a file named main.tf
in your project directory. This file will contain the configuration for your AWS Lambda function.
provider "aws" {
region = "us-east-1" # Specify your desired AWS region
}
resource "aws_lambda_function" "my_lambda" {
function_name = "myServerlessFunction"
handler = "index.handler"
runtime = "nodejs14.x" # Specify your preferred runtime
role = aws_iam_role.lambda_exec.arn
source_code_hash = filebase64sha256("lambda.zip") # Zip your function code
filename = "lambda.zip" # Path to your zipped function code
}
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" # Basic execution role
}
Code Explanation
- Provider: Specifies AWS as the cloud provider and the region.
- Lambda Function: Defines the properties of your Lambda function, including the handler, runtime, and execution role.
- IAM Role: Assigns a role to the Lambda function that permits it to write logs to CloudWatch.
Step 3: Prepare Your Lambda Code
Create a simple Lambda function in a file named index.js
:
exports.handler = async (event) => {
console.log("Received event:", JSON.stringify(event));
return {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
};
Next, zip your Lambda function:
zip lambda.zip index.js
Step 4: Deploy Your Serverless Application
With your code and configuration files ready, it’s time to deploy your serverless application.
-
Run Terraform Plan: This command lets you preview the changes Terraform will make.
bash terraform plan
-
Apply Changes: Deploy your application by applying the configuration.
bash terraform apply
Confirm the action when prompted by typing yes
.
Step 5: Set Up an API Gateway
To trigger your Lambda function via HTTP, you’ll need to create an API Gateway. Extend your main.tf
file:
resource "aws_api_gateway_rest_api" "my_api" {
name = "my_api"
description = "API Gateway for my serverless application"
}
resource "aws_api_gateway_resource" "my_api_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_api_method" {
rest_api_id = aws_api_gateway_rest_api.my_api.id
resource_id = aws_api_gateway_resource.my_api_resource.id
http_method = "GET"
authorization = "NONE"
}
resource "aws_api_gateway_integration" "my_api_integration" {
rest_api_id = aws_api_gateway_rest_api.my_api.id
resource_id = aws_api_gateway_resource.my_api_resource.id
http_method = aws_api_gateway_method.my_api_method.http_method
integration_http_method = "POST"
type = "AWS_PROXY"
uri = aws_lambda_function.my_lambda.invoke_arn
}
Key Points
- API Gateway Resource: Defines the resource path
/hello
. - Integration: Connects the API Gateway to the Lambda function using AWS_PROXY.
Step 6: Test Your Serverless Application
After deploying your changes with terraform apply
, you can test your API endpoint. Find the API endpoint URL in the AWS Management Console under API Gateway. Use a tool like Postman or cURL to send a GET request:
curl https://<your-api-id>.execute-api.us-east-1.amazonaws.com/prod/hello
You should see a response: {"statusCode":200,"body":"Hello from Lambda!"}
.
Conclusion
Building serverless applications on AWS with Terraform simplifies the deployment process, enabling developers to focus on coding without worrying about infrastructure management. By following this step-by-step guide, you’ve set up a basic serverless application, created a Lambda function, and connected it to an API Gateway.
As you continue to explore the possibilities of serverless architecture, consider incorporating more AWS services, optimizing your code, and troubleshooting potential issues. With Terraform, the journey of managing your infrastructure becomes a breeze, paving the way for scalability and efficiency in your development workflow. Happy coding!