Deploying AWS Lambda Function with Terraform

Introduction :

Globally, the business wants a reusable, scalable and cost effective IT solution which is easy to manage with the least overhead.The traditional IT infrastructure model leveraged managing all the underlying software and hardware manually for running the applications.Infrastructure as Code (IaC) solves this problem efficiently.

What is Infrastructure as Code (IaC) and Terraform?

Infrastructure as Code (IaC) solves the above problem by automating the management and provisioning of infrastructure through code.The IaC model allows you to maintain and distribute configurations to all the environments by documenting the configuration information through code.Numerous IaC tools are available in the market which can be suitable for your applications.The blog talks about Terraform which is one of the most popular and widely used IaC in the market.

What is AWS lambda?

AWS lambda is a serverless computing platform which runs the code without provisioning and managing servers in the AWS cloud.Lambda is triggered on events and can be integrated with other AWS services.Users only pay for the time Lambda runs their code which can provide significant cost savings for certain usage patterns like cron jobs and other on-demand tasks.

Create a Hello world Lambda function with Terraform !

Let create a sample Lambda function with Terraform and deploy it to the AWS account.

Step 1 : Installation of Terraform and the AWS CLI on Local Machine

Download and install the Terraform on the local machine.

Download and install the AWS CLI on the local machine.

Step 2 : Create a Lambda function and upload to S3

  • Create a directory in the Root Module {Terraform-Module}/sample-lambda
  • Create a file named sample-lambda.py inside  the folder {Terraform-Module}/sample-lambda and copy the below code in the file.
def lambda_handler(event, context):
    response = {
        'event': event
    }
    return {
        'statusCode': 200,
        'response': response
    }
  • Compress the folder and upload to the S3 Bucket.

Step 3 : Create Terraform Resource :

Creating Lambda resources with Terraform will require creating 3 files as below .The files have different purposes.

  • provider.tf file – Terraform configurations must declare which providers they require.It is good practice to restrict Terraform provider version and define AWS Region Example : AWS
# Set up Terraform provider version 
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.0"
    }
  }
}

# Configure the AWS Provider
provider "aws" {
  region = "us-east-1"
}  
  • lambda_sample.tf file – Defines AWS Lambda function definition in the Terraform code.
locals {
  resource_name_prefix          = "${local.prefix}-simple-lambda"
  lambda_code_path              = "${path.module}/lambdas/simple_lambda"
  lambda_archive_path           = "${path.module}/lambdas/simple_lambda.zip"
  lambda_handler                = "index.lambda_handler"
  lambda_description            = "This is simple Lambda function"
  lambda_runtime                = "python3.9"
  lambda_timeout                = 1
  lambda_concurrent_executions  = -1
  lambda_cw_log_group_name      = "/aws/lambda/${aws_lambda_function.simple_lambda.function_name}"
  lambda_log_retention_in_days  = 1
}

data "archive_file" "simple_lambda_zip" {
  source_dir = local.lambda_code_path
  output_path = local.lambda_archive_path
  type = "zip"
}

data "aws_iam_policy_document" "simple_lambda_assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      identifiers = ["lambda.amazonaws.com"]
      type        = "Service"
    }
  }
}

resource "aws_iam_role" "simple_lambda" {
  name = "${local.resource_name_prefix}-role"
  assume_role_policy = data.aws_iam_policy_document.simple_lambda_assume_role_policy.json
  managed_policy_arns = [
    "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
  ]
  tags = merge(
    {
      Name = "${local.resource_name_prefix}-role"
    },
    local.common_tags
  )
}

resource "aws_lambda_function" "simple_lambda" {
  function_name = "${local.resource_name_prefix}-lambda"
  source_code_hash = data.archive_file.simple_lambda_zip.output_base64sha256
  filename = data.archive_file.simple_lambda_zip.output_path
  description = local.lambda_description
  role          = aws_iam_role.simple_lambda.arn
  handler = local.lambda_handler
  runtime = local.lambda_runtime
  timeout = local.lambda_timeout

  tags = merge(
    {
      Name = "${local.resource_name_prefix}-lambda"
    },
    local.common_tags
  )

  reserved_concurrent_executions = local.lambda_concurrent_executions
}

Step 6 : Deploy the Lambda function :

The command is used to initialize Terraform in the working directory.Command is used to update provider and module versions.

terraform init

The command generates the execution plan for all the changes in the infrastructure that are going to be applied by the terraform.

terraform plan

The command is used to apply all the changes in the configuration as listed in the “terraform plan” command.The command asks you to confirm if you want to proceed with this plan and apply the changes.

terraform apply  -auto-approve

Step 7 : Testing the Lambda function :

The Lambda function can be tested by going to the AWS console and finding the “hello world” function.Go to the function and click on Test.The log output displays all the Lambda invocation details which is used for debugging.

Summary :

Terraform is a powerful tool that can be used to manage your AWS Lambda functions. In this blog post, we’ve covered how to use Terraform to create and deploy a simple AWS Lambda function and how to deploy the AWS Lambda function inside of a VPC. If you’re looking for a way to easily manage your AWS Lambda functions, Terraform is the tool for you.

Leave a Comment

Your email address will not be published.