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

Deploying Serverless Applications on AWS with Terraform

In the ever-evolving landscape of cloud computing, serverless architectures are gaining significant traction. This model allows developers to build and run applications without the hassle of managing servers, letting them focus on writing code. AWS Lambda, part of Amazon Web Services, is a popular choice for deploying serverless applications. But how can we automate and streamline the deployment process? Enter Terraform, an open-source infrastructure as code (IaC) tool that simplifies provisioning and managing cloud infrastructure.

In this article, we'll explore the synergy between AWS Lambda and Terraform, providing you with actionable insights, code snippets, and step-by-step instructions to deploy serverless applications efficiently.

What is Serverless Computing?

Serverless computing is a cloud computing execution model where the cloud provider dynamically manages the allocation and provisioning of servers. In this model, you only pay for the compute time you consume—no charges when your code isn't running. This paradigm offers several advantages:

  • Cost-Effective: Pay only for what you use.
  • Scalable: Automatically scales with the demand.
  • Reduced Management: Focus on writing code rather than managing servers.

Why Use Terraform for Serverless Deployment?

Terraform, created by HashiCorp, allows you to define infrastructure using high-level configuration languages. Its primary advantages include:

  • Infrastructure as Code: Version control your infrastructure.
  • Multi-Cloud Support: Deploy across various cloud providers seamlessly.
  • Modularity: Organize your infrastructure in reusable components.

By combining AWS Lambda with Terraform, you can automate the deployment process, ensuring consistent and repeatable configurations.

Use Case: A Simple Serverless Application

Let’s walk through deploying a simple serverless application using AWS Lambda and Terraform. Our application will respond to HTTP requests and return a message.

Prerequisites

  • AWS account
  • Terraform installed on your machine
  • Basic knowledge of AWS services and Terraform syntax

Step 1: Set Up Your Project Directory

Create a new directory for your Terraform project:

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

Step 2: Create a Lambda Function

First, let's create a simple Lambda function. Create a file named app.js in your project directory:

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

Step 3: Write Terraform Configuration

Create a file named main.tf in your project directory. This file will contain the necessary Terraform configuration for deploying your Lambda function.

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

resource "aws_lambda_function" "hello_lambda" {
  function_name = "HelloLambda"
  runtime       = "nodejs14.x"
  role          = aws_iam_role.lambda_exec.arn
  handler       = "app.handler"

  source_code_hash = filebase64sha256("app.zip")

  # Package the Lambda function
  filename = "app.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_lambda_permission" "allow_api_gateway" {
  statement_id  = "AllowExecutionFromAPIGateway"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.hello_lambda.function_name
  principal     = "apigateway.amazonaws.com"
}

Step 4: Package Your Lambda Function

Before deploying, package your Lambda function into a ZIP file. Run the following command in your terminal:

zip app.zip app.js

Step 5: Initialize and Apply Terraform

Now it's time to deploy your application. Run the following commands in your terminal:

# Initialize Terraform
terraform init

# Apply the configuration
terraform apply

Terraform will prompt you to confirm the changes. Type yes and hit Enter. This will create the Lambda function and IAM role on AWS.

Step 6: Set Up API Gateway (Optional)

To make your Lambda function accessible via HTTP, set up an API Gateway. You can add the following resource block to your main.tf:

resource "aws_api_gateway_rest_api" "api" {
  name        = "HelloAPI"
  description = "API for Hello Lambda"
}

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" "get" {
  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_api_gateway_integration" "lambda" {
  rest_api_id = aws_api_gateway_rest_api.api.id
  resource_id = aws_api_gateway_resource.hello.id
  http_method = aws_api_gateway_method.get.http_method

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

Step 7: Deploy and Test

After adding the API Gateway configuration, run terraform apply again. Once completed, navigate to the AWS API Gateway console to find the endpoint URL.

You can test the function by sending a GET request using tools like Postman or cURL:

curl https://{your_api_id}.execute-api.us-east-1.amazonaws.com/prod/hello

You should see the response: Hello from AWS Lambda!.

Troubleshooting Common Issues

  • Permission Errors: Ensure your IAM roles have the correct permissions.
  • Deployment Failures: Check for syntax errors in your Terraform configuration.
  • Function Errors: Use AWS CloudWatch logs to troubleshoot Lambda execution issues.

Conclusion

Deploying serverless applications on AWS with Terraform not only simplifies your workflow but also enhances your development speed. By following the steps outlined in this guide, you can set up a basic serverless application, allowing you to focus on building features rather than managing infrastructure. As you gain more experience, consider exploring advanced features like versioning, environments, and state management to further optimize your deployments. 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.