9-how-to-deploy-serverless-functions-on-aws-with-terraform.html

How to Deploy Serverless Functions on AWS with Terraform

In the ever-evolving world of cloud computing, serverless architecture has emerged as a game changer. It allows developers to focus on writing code without worrying about server management. Amazon Web Services (AWS) Lambda is a popular serverless framework that runs your code in response to events, automatically managing the compute resources required. When combined with Terraform, a powerful Infrastructure as Code (IaC) tool, deploying AWS Lambda functions becomes a breeze. In this article, we will explore how to deploy serverless functions on AWS with Terraform, diving into definitions, use cases, and actionable insights.

What is Serverless Computing?

Serverless computing allows developers to build and run applications without managing servers. It abstracts server management and dynamically allocates resources based on demand. Key benefits of serverless computing include:

  • Scalability: Automatically scales your application by running code in response to events.
  • Cost Efficiency: Pay only for the compute time you consume, with no charge when your code isn't running.
  • Reduced Operational Overhead: Focus on writing code rather than managing infrastructure.

Why Use Terraform?

Terraform is an open-source tool that allows you to define your infrastructure as code using a declarative configuration language. It automates the provisioning and management of cloud resources, making it an excellent choice for deploying serverless applications. Benefits include:

  • Version Control: Track changes to your infrastructure over time.
  • Reusability: Write reusable modules to streamline deployments.
  • Multi-Cloud Management: Manage resources across different cloud providers.

Use Cases for AWS Lambda

AWS Lambda is ideal for a wide range of applications, including:

  • Data Processing: Process data in real-time from sources like S3 or Kinesis.
  • Web Applications: Run backend logic for web apps without provisioning servers.
  • APIs: Build serverless RESTful APIs using API Gateway and Lambda.
  • Automation: Automate tasks such as backups and notifications based on triggers.

Getting Started with Terraform and AWS Lambda

Prerequisites

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

  • An AWS account
  • Terraform installed on your local machine
  • AWS CLI configured with your credentials

Step 1: Create Your Lambda Function

First, create a simple Node.js Lambda function. Here’s the sample code for a function that returns a greeting:

index.js

exports.handler = async (event) => {
    const name = event.name || "World";
    return {
        statusCode: 200,
        body: JSON.stringify(`Hello, ${name}!`),
    };
};

Step 2: Initialize Your Terraform Project

Create a new directory for your Terraform project and initialize it:

mkdir my_lambda_project
cd my_lambda_project
terraform init

Step 3: Create a Terraform Configuration File

Create a file named main.tf in your project directory. This file will define your AWS resources, including the Lambda function, IAM role, and API Gateway.

main.tf

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

resource "aws_iam_role" "lambda_role" {
  name = "lambda_basic_execution"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = "sts:AssumeRole"
        Principal = {
          Service = "lambda.amazonaws.com"
        }
        Effect = "Allow"
        Sid    = ""
      },
    ]
  })
}

resource "aws_lambda_function" "my_lambda" {
  function_name = "my_lambda_function"
  runtime       = "nodejs14.x"
  role          = aws_iam_role.lambda_role.arn
  handler       = "index.handler"

  source_code_hash = filebase64sha256("index.zip")

  # Package the code as a ZIP file
  filename = "index.zip"
}

resource "aws_api_gateway_rest_api" "api" {
  name        = "my_api"
  description = "API for my Lambda function"
}

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

resource "aws_api_gateway_method" "get" {
  rest_api_id   = aws_api_gateway_rest_api.api.id
  resource_id   = aws_api_gateway_resource.greeting.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.greeting.id
  http_method             = aws_api_gateway_method.get.http_method
  integration_http_method = "POST"
  type                    = "AWS_PROXY"
  uri                     = aws_lambda_function.my_lambda.invoke_arn
}

output "invoke_url" {
  value = "${aws_api_gateway_rest_api.api.execution_arn}/greeting"
}

Step 4: Package Your Lambda Function

Before deploying, you need to package your function code into a ZIP file. Run the following command:

zip index.zip index.js

Step 5: Deploy Your Infrastructure

Now that everything is set up, deploy your infrastructure with Terraform:

terraform apply

When prompted, type yes to confirm the deployment. Terraform will create your resources on AWS.

Step 6: Test Your Lambda Function

Once the deployment is complete, Terraform will output the API Gateway URL. You can test your Lambda function with a simple curl command:

curl -X GET "<invoke_url>?name=YourName"

You should receive a response like:

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

Troubleshooting Tips

  • Permissions Issues: Ensure your IAM Role has the necessary permissions. You may need to attach additional policies.
  • Code Errors: Check the Lambda function logs in CloudWatch for any runtime errors.
  • Deployment Failures: Use terraform plan to review changes before applying, and check the console for detailed error messages.

Conclusion

Deploying serverless functions on AWS using Terraform is a powerful way to streamline your infrastructure management. By following the steps outlined in this guide, you can leverage the benefits of serverless computing without the hassle of managing servers. Whether you're building a simple API or processing data in real-time, AWS Lambda and Terraform provide a robust solution for modern application deployment. Start experimenting with your own Lambda functions today and unlock the full potential of serverless architecture!

SR
Syed
Rizwan

About the Author

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