deploying-a-serverless-application-on-aws-using-terraform.html

Deploying a Serverless Application on AWS Using Terraform

In today's fast-paced digital landscape, deploying applications efficiently and cost-effectively is critical for developers and businesses alike. Serverless architecture has emerged as a popular solution, allowing developers to focus on writing code instead of managing servers. In this article, we will explore how to deploy a serverless application on AWS using Terraform, a powerful Infrastructure as Code (IaC) tool.

What is Serverless Architecture?

Serverless architecture enables developers to build and run applications without having to manage the underlying infrastructure. With serverless, you only pay for the resources you use, making it a cost-effective solution for various applications. AWS Lambda is a key service that allows you to run your code in response to events without provisioning or managing servers.

Use Cases for Serverless Applications

  • Web Applications: Quickly develop and deploy scalable web applications.
  • Data Processing: Process large volumes of data in real time with minimal overhead.
  • APIs: Build RESTful APIs that scale automatically based on demand.
  • IoT Applications: Handle events from numerous IoT devices effortlessly.

What is Terraform?

Terraform is an open-source tool that allows you to define and provision infrastructure using code. It simplifies the management of cloud resources through declarative configuration files. With Terraform, you can automate the deployment of serverless applications on AWS, ensuring consistency and reducing the risk of human error.

Prerequisites

Before we dive into the deployment process, ensure you have the following:

  • An AWS account.
  • Terraform installed on your local machine. You can download it from the Terraform website.
  • Basic knowledge of AWS services, particularly AWS Lambda and API Gateway.

Setting Up Your Project

Let’s create a simple serverless application that responds to HTTP requests. We’ll follow these steps:

  1. Create a new directory for your project.
  2. Initialize a new Terraform configuration.

Step 1: Create a Project Directory

Open your terminal and run the following commands:

mkdir my-serverless-app
cd my-serverless-app

Step 2: Initialize Terraform

Create a file named main.tf in your project directory:

provider "aws" {
  region = "us-east-1" # Change to your preferred region
}

Step 3: Define the Lambda Function

Next, we’ll add our Lambda function. Create a directory called lambda and a file named hello.js inside it:

mkdir lambda
touch lambda/hello.js

Add the following code to hello.js:

exports.handler = async (event) => {
    return {
        statusCode: 200,
        body: JSON.stringify('Hello, World!'),
    };
};

Step 4: Update main.tf for Lambda and API Gateway

Now, we need to update main.tf to define our Lambda function and expose it via API Gateway:

resource "aws_lambda_function" "hello" {
  function_name = "hello_function"
  handler       = "hello.handler"
  runtime       = "nodejs14.x"
  role          = aws_iam_role.lambda_exec.arn
  filename      = "lambda/hello.zip"

  source_code_hash = filebase64sha256("lambda/hello.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_api_gateway_rest_api" "api" {
  name        = "HelloAPI"
  description = "API for Hello World Lambda Function"
}

resource "aws_api_gateway_resource" "hello" {
  rest_api_id = aws_api_gateway_rest_api.api.id
  parent_id   = aws_api_gateway_rest_api.api.root_resource_id
  path_part   = "hello"
}

resource "aws_api_gateway_method" "hello" {
  rest_api_id   = aws_api_gateway_rest_api.api.id
  resource_id   = aws_api_gateway_resource.hello.id
  http_method   = "GET"
  authorization = "NONE"
}

resource "aws_lambda_permission" "allow_api_gateway" {
  statement_id  = "AllowAPIGatewayInvocation"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.hello.function_name
  principal     = "apigateway.amazonaws.com"

  source_arn = "${aws_api_gateway_rest_api.api.execution_arn}/*/*"
}

Step 5: Package Your Lambda Function

Before deploying, we need to package the Lambda function:

zip -r lambda/hello.zip lambda/hello.js

Step 6: Deploy the Application

Now that everything is set up, it’s time to deploy your application. Run the following commands in your terminal:

terraform init
terraform apply

This will initialize Terraform and prompt you to confirm the changes. Type yes to proceed. Terraform will create the necessary resources in your AWS account.

Step 7: Test Your API

Once the deployment is complete, note the API Gateway endpoint URL displayed in the output. Test it using curl or your web browser:

curl https://<api-id>.execute-api.us-east-1.amazonaws.com/prod/hello

You should receive a response:

{"message": "Hello, World!"}

Troubleshooting Common Issues

  • Permission Denied: Ensure that your IAM role has the necessary permissions for Lambda execution.
  • Lambda Timeout: Increase the timeout setting in the Lambda function resource if your function takes longer to execute.
  • Incorrect API Endpoint: Double-check the API Gateway URL for typos.

Conclusion

Deploying a serverless application on AWS using Terraform not only simplifies infrastructure management but also enhances scalability and reduces costs. By following the steps outlined in this guide, you have successfully created a serverless application that can respond to HTTP requests. As you continue to explore serverless architecture, consider experimenting with more complex use cases and integrating other AWS services to unlock further potential.

With Terraform's robust capabilities, your infrastructure can evolve alongside your application, making it easier than ever to manage resources in the cloud. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.