5-deploying-serverless-functions-on-aws-lambda-with-terraform.html

Deploying Serverless Functions on AWS Lambda with Terraform

In today’s fast-paced digital landscape, building scalable applications rapidly is essential. This is where serverless architectures come into play, allowing developers to focus on writing code without worrying about the underlying infrastructure. AWS Lambda, Amazon’s serverless compute service, enables you to run code in response to events without provisioning or managing servers. In this article, we will explore how to deploy serverless functions on AWS Lambda using Terraform, a powerful infrastructure as code (IaC) tool.

What is AWS Lambda?

AWS Lambda allows you to run code in response to specific events, such as HTTP requests via API Gateway, file uploads to S3, or updates in DynamoDB. With Lambda, you only pay for the compute time you consume, making it an economical choice for many applications.

Key Benefits of AWS Lambda

  • Cost-effective: Pay only for the compute time you use.
  • Scalable: Automatically scales up or down based on the number of requests.
  • Event-driven: Integrates seamlessly with other AWS services.
  • No server management: Focus on coding, not infrastructure.

What is Terraform?

Terraform is an open-source tool for building, changing, and versioning infrastructure safely and efficiently. Using a declarative configuration language (HCL), you can define and provision your infrastructure across various cloud providers, including AWS. This allows for repeatable and consistent deployments.

Why Use Terraform for AWS Lambda?

  • Infrastructure as Code: Manage infrastructure in a structured and versioned manner.
  • Automation: Streamlines the deployment process, reducing human error.
  • Modularity: Easily manage complex infrastructures by breaking them into modules.

Step-by-Step Guide to Deploying AWS Lambda Functions with Terraform

Prerequisites

Before we begin, ensure you have the following:

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

Step 1: Setting Up Your Project

Create a new directory for your Terraform project:

mkdir lambda-terraform-example
cd lambda-terraform-example

Create a file named main.tf inside this directory. This file will contain all the necessary Terraform configurations.

Step 2: Writing the Terraform Configuration

In your main.tf, start by defining the provider and the AWS region:

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

Next, create an IAM role for your Lambda function that grants it the necessary permissions to execute:

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

Step 3: Writing the Lambda Function

Create a simple Lambda function. For this example, let’s create a Python function that returns a greeting message. Create a directory named lambda_function and add a file named app.py:

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

Step 4: Packaging the Lambda Function

To deploy your function, you need to package it into a zip file. Run the following command in your terminal:

cd lambda_function
zip function.zip app.py
cd ..

Step 5: Uploading the Lambda Function Code

Add the Lambda function resource to your main.tf:

resource "aws_lambda_function" "example_function" {
  function_name = "example_lambda_function"
  role          = aws_iam_role.lambda_role.arn
  handler       = "app.lambda_handler"
  runtime       = "python3.8"  # Change based on your Python version
  filename      = "lambda_function/function.zip"

  source_code_hash = filebase64sha256("lambda_function/function.zip")
}

Step 6: Deploying with Terraform

Now that your Terraform configuration is complete, you can initialize your Terraform workspace and apply your configuration:

terraform init
terraform apply

When prompted, type yes to confirm the changes. Terraform will provision the Lambda function along with the IAM role.

Step 7: Testing Your Lambda Function

Once deployed, you can test your Lambda function using the AWS Management Console or the AWS CLI. To invoke it via the AWS CLI, run the following command:

aws lambda invoke --function-name example_lambda_function response.json

This command will create a file named response.json containing the output from your function. You should see the greeting message in this file.

Troubleshooting Common Issues

  • Permissions Errors: Ensure that your IAM role has the correct permissions attached.
  • Deployment Failures: Check the Terraform output for error messages, and ensure your Lambda function code is packaged correctly.
  • Timeouts: Adjust the timeout settings in your Terraform configuration if your function takes longer to execute.

Conclusion

Deploying serverless functions on AWS Lambda using Terraform is a powerful way to manage your cloud infrastructure. With the ability to define your infrastructure as code, you can ensure repeatable and consistent deployments. By following the steps outlined in this guide, you can quickly get a serverless application up and running, ready to scale as your needs grow. Dive into the world of serverless computing and enjoy the benefits of reduced operational overhead and increased agility!

SR
Syed
Rizwan

About the Author

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