6-deploying-serverless-applications-on-aws-with-terraform.html

Deploying Serverless Applications on AWS with Terraform

In today’s fast-paced development landscape, serverless computing has emerged as a powerful paradigm that allows developers to focus on writing code without worrying about managing servers. Amazon Web Services (AWS) provides a robust serverless architecture that scales automatically and charges only for the compute time consumed. When combined with Terraform, an infrastructure as code tool, deploying serverless applications becomes streamlined and efficient. In this article, we'll explore how to deploy serverless applications on AWS using Terraform, providing you with actionable insights, coding examples, and best practices.

What is Serverless Computing?

Serverless computing allows developers to build and run applications without managing the underlying infrastructure. In a serverless model, developers write code and deploy it to a cloud provider, which automatically handles resource provisioning, scaling, and maintenance. AWS Lambda is the primary service for running serverless applications on AWS, allowing you to execute code in response to events without provisioning or managing servers.

Key Benefits of Serverless Computing

  • Cost-Effective: Pay only for the compute time used.
  • Scalable: Automatically scales based on demand.
  • Reduced Operational Overhead: No need to manage server infrastructure.
  • Faster Time to Market: Focus on writing code rather than managing resources.

Introduction to Terraform

Terraform is an open-source tool that allows you to define infrastructure as code using a declarative configuration language. With Terraform, you can manage a wide variety of cloud services, including AWS, with ease. It simplifies the process of provisioning, updating, and maintaining resources, making it an ideal companion for deploying serverless applications.

Why Use Terraform for AWS Serverless Applications?

  • Version Control: Easily track changes to your infrastructure code.
  • Reusability: Modularize your configurations for easy reuse.
  • Collaboration: Facilitate collaboration among team members through code.

Setting Up Your Environment

Before we dive into deploying a serverless application, let’s set up our environment. Ensure you have the following prerequisites:

  • AWS Account: Sign up for an AWS account if you don’t have one.
  • Terraform Installed: Download and install Terraform from the official website.
  • AWS CLI Installed: Install the AWS Command Line Interface and configure it with your AWS credentials.

Configure AWS CLI

Run the following command to configure your AWS credentials:

aws configure

You'll be prompted to enter your AWS Access Key ID, Secret Access Key, region, and output format.

Creating a Simple Serverless Application

Let’s create a simple serverless application using AWS Lambda and API Gateway that responds to HTTP requests. We'll use Terraform to provision the necessary resources.

Step 1: Create the Project Structure

Create a new directory for your Terraform project:

mkdir aws-serverless-app
cd aws-serverless-app

Create the following files in your project directory:

  • main.tf
  • lambda_function.py
  • variables.tf

Step 2: Write Your Lambda Function

In lambda_function.py, write a simple Python function that returns a greeting message:

def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': 'Hello, World!'
    }

Step 3: Define Your Terraform Configuration

In main.tf, define the AWS Lambda function and the API Gateway:

provider "aws" {
  region = "us-east-1"
}

resource "aws_lambda_function" "hello_world" {
  function_name = "hello_world"
  handler       = "lambda_function.lambda_handler"
  runtime       = "python3.8"
  role          = aws_iam_role.lambda_exec.arn

  # Package the lambda function
  filename      = "lambda_function.zip"
  source_code_hash = filebase64sha256("lambda_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_api_gateway_rest_api" "api" {
  name        = "HelloWorldAPI"
  description = "API for Hello World Lambda Function"
}

resource "aws_api_gateway_resource" "hello_resource" {
  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_method" {
  rest_api_id   = aws_api_gateway_rest_api.api.id
  resource_id   = aws_api_gateway_resource.hello_resource.id
  http_method   = "GET"
  authorization = "NONE"
}

resource "aws_api_gateway_integration" "hello_integration" {
  rest_api_id = aws_api_gateway_rest_api.api.id
  resource_id = aws_api_gateway_resource.hello_resource.id
  http_method = aws_api_gateway_method.hello_method.http_method

  integration_http_method = "POST"
  type                     = "AWS_PROXY"
  uri                      = aws_lambda_function.hello_world.invoke_arn
}

resource "aws_api_gateway_deployment" "api_deployment" {
  rest_api_id = aws_api_gateway_rest_api.api.id
  stage_name  = "prod"
}

Step 4: Create the Lambda Deployment Package

Before deploying your application, you need to create a deployment package for your Lambda function. Run the following command to zip the function:

zip lambda_function.zip lambda_function.py

Step 5: Initialize and Deploy with Terraform

Now that everything is set up, you can initialize and deploy your serverless application using Terraform:

  1. Initialize Terraform: bash terraform init

  2. Plan the Deployment: bash terraform plan

  3. Apply the Deployment: bash terraform apply

Confirm the action by typing yes when prompted.

Step 6: Test Your API

After a successful deployment, you will receive the API Gateway endpoint. You can test your application by sending a GET request to the endpoint:

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

You should see the following response:

{
  "statusCode": 200,
  "body": "Hello, World!"
}

Troubleshooting and Best Practices

  • IAM Roles: Ensure that the IAM role has the necessary permissions for Lambda to execute.
  • Logging: Enable AWS CloudWatch Logs to troubleshoot any issues with your Lambda function.
  • Version Control: Use Terraform modules to maintain reusable code and better organize your configurations.

Conclusion

Deploying serverless applications on AWS using Terraform allows you to take full advantage of the benefits of serverless computing while maintaining control over your infrastructure. By following this guide, you have created a simple serverless application that responds to HTTP requests, showcasing the power of AWS Lambda and Terraform.

With serverless architecture becoming increasingly popular, mastering these tools will enable you to build efficient, scalable, and cost-effective applications. 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.