4-how-to-deploy-a-serverless-application-using-aws-lambda-and-terraform.html

How to Deploy a Serverless Application Using AWS Lambda and Terraform

In today’s fast-paced digital landscape, businesses seek efficient and scalable solutions for their applications. Serverless architecture, particularly through AWS Lambda, has revolutionized application deployment. Coupled with Terraform, an Infrastructure as Code (IaC) tool, developers can automate the provisioning of AWS resources effortlessly. In this article, we’ll walk you through deploying a serverless application using AWS Lambda and Terraform, complete with code snippets, step-by-step instructions, and actionable insights.

What is AWS Lambda?

AWS Lambda is a serverless computing service that automatically manages the compute resources required for your applications. With Lambda, you can run code without provisioning or managing servers, allowing you to focus on writing your application code. Lambda supports multiple programming languages, including Node.js, Python, Java, and Go, making it a versatile choice for developers.

Key Benefits of AWS Lambda

  • Cost-Effective: Pay only for the compute time you consume.
  • Scalability: Automatically scales your application by running code in response to events.
  • Flexibility: Integrates seamlessly with other AWS services and third-party APIs.

What is Terraform?

Terraform is an open-source IaC tool created by HashiCorp that allows you to define and provision infrastructure using a declarative configuration language. With Terraform, you can version control your infrastructure, collaborate with teams, and automate the deployment process.

Key Benefits of Terraform

  • Infrastructure as Code: Define infrastructure using code, making it easier to manage and replicate.
  • Multi-Cloud Support: Manage resources across various cloud providers.
  • State Management: Terraform keeps track of the current state of your infrastructure, ensuring consistency.

Use Case: Creating a Serverless REST API

In this example, we will create a simple serverless REST API that responds to HTTP requests using AWS Lambda, API Gateway, and DynamoDB for data storage. We’ll use Terraform to manage our infrastructure.

Step 1: Setting Up Your Environment

Before we begin, ensure you have the following installed:

  • AWS CLI
  • Terraform
  • A text editor (Visual Studio Code, Sublime Text, etc.)
  • An AWS account with appropriate permissions

Step 2: Create a New Terraform Project

  1. Create a new directory for your project:

bash mkdir serverless-api cd serverless-api

  1. Initialize a Terraform project:

bash terraform init

  1. Create a main.tf file in your project directory. This file will define your infrastructure.

Step 3: Defining the Infrastructure

Here’s a basic main.tf configuration to set up AWS Lambda, API Gateway, and DynamoDB:

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

resource "aws_dynamodb_table" "my_dynamodb_table" {
  name         = "MyTable"
  billing_mode = "PAY_PER_REQUEST"
  hash_key     = "id"

  attribute {
    name = "id"
    type = "S"
  }
}

resource "aws_iam_role" "lambda_role" {
  name = "lambda_execution_role"

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

resource "aws_iam_policy_attachment" "lambda_policy" {
  name       = "lambda_policy_attachment"
  roles      = [aws_iam_role.lambda_role.name]
  policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}

resource "aws_lambda_function" "my_lambda_function" {
  function_name = "MyLambdaFunction"
  s3_bucket     = "<your-s3-bucket>"
  s3_key        = "<your-lambda-zip-file>"
  handler       = "index.handler"
  runtime       = "nodejs14.x"
  role          = aws_iam_role.lambda_role.arn
}

resource "aws_api_gateway_rest_api" "my_api" {
  name = "MyAPI"
}

resource "aws_api_gateway_resource" "my_resource" {
  rest_api_id = aws_api_gateway_rest_api.my_api.id
  parent_id   = aws_api_gateway_rest_api.my_api.root_resource_id
  path_part   = "items"
}

resource "aws_api_gateway_method" "my_method" {
  rest_api_id   = aws_api_gateway_rest_api.my_api.id
  resource_id   = aws_api_gateway_resource.my_resource.id
  http_method   = "GET"
  authorization = "NONE"
}

resource "aws_api_gateway_integration" "my_integration" {
  rest_api_id = aws_api_gateway_rest_api.my_api.id
  resource_id = aws_api_gateway_resource.my_resource.id
  http_method = aws_api_gateway_method.my_method.http_method
  integration_http_method = "POST"
  type = "AWS_PROXY"
  uri = aws_lambda_function.my_lambda_function.invoke_arn
}

resource "aws_api_gateway_deployment" "my_deployment" {
  rest_api_id = aws_api_gateway_rest_api.my_api.id
  stage_name  = "prod"
}

Step 4: Deploying Your Infrastructure

  1. Run the following command to validate your Terraform configuration:

bash terraform validate

  1. Apply the configuration to create the resources:

bash terraform apply

Confirm the action with yes when prompted.

Step 5: Writing the Lambda Function

Create a new directory named lambda and add an index.js file with the following code:

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();

exports.handler = async (event) => {
    const params = {
        TableName: 'MyTable',
        Item: {
            id: '1',
            name: 'Item 1'
        }
    };

    try {
        await docClient.put(params).promise();
        return {
            statusCode: 200,
            body: JSON.stringify('Item added successfully!'),
        };
    } catch (error) {
        return {
            statusCode: 500,
            body: JSON.stringify('Error: ' + error.message),
        };
    }
};

Step 6: Packaging and Uploading Your Lambda Function

  1. Zip your Lambda function:

bash zip -r lambda.zip lambda/

  1. Upload the zip file to your specified S3 bucket.

Step 7: Testing Your API

  1. Go to the AWS API Gateway console.
  2. Find your API and click on the "Invoke URL" to test your endpoint.

Troubleshooting Tips

  • Ensure your AWS credentials are correctly configured in your AWS CLI.
  • Check IAM role permissions if your Lambda function fails due to access issues.
  • Review CloudWatch logs for Lambda function execution issues.

Conclusion

Deploying a serverless application using AWS Lambda and Terraform simplifies the process of managing infrastructure while allowing you to focus on your application code. With the right tools and a clear understanding of the setup process, you can build scalable and efficient applications that respond to user demands in real time. Start experimenting with your serverless applications today and unlock the full potential of cloud computing!

SR
Syed
Rizwan

About the Author

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