Deploying AWS Lambda Using Terraform – Step-by-Step Guide

Introduction

AWS Lambda allows you to run code without provisioning or managing servers. In this guide, we’ll walk through how to deploy a simple AWS Lambda function using Terraform. We’ll cover everything from writing the function, creating IAM roles, packaging the code, and deploying with Terraform — all in a beginner-friendly way.

Project Structure

First, create the following directory layout:

lambda-example/
├── main.tf               # Main Terraform configuration
├── outputs.tf            # To output function name
└── lambda_function/
    └── lambda_function.py # Your Python Lambda code

Step 1: Writing the Lambda Function

In lambda_function/lambda_function.py path:

def handler(event, context):
    return {
        'statusCode': 200,
        'body': 'Hello from Lambda!'
    }

This is a basic function that returns an HTTP 200 response with a message. The event and context parameters are provided by AWS when the function is invoked.

Step 2: Define AWS Provider in Terraform

In main.tf, start with your provider configuration:

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

This tells Terraform to work with AWS in the us-east-1 region.

Step 3: Create IAM Role for Lambda

Lambda functions need permissions to interact with other AWS services. We create an IAM Role and attach a policy.

IAM Role creation block:

resource "aws_iam_role" "lambda_exec_role" {
  name = "lambda_exec_role"
  assume_role_policy = jsonencode({
    Version = "2012-10-17",
    Statement = [{
      Effect = "Allow",
      Principal = {
        Service = "lambda.amazonaws.com"
      },
      Action = "sts:AssumeRole"
    }]
  })
}
  • assume_role_policy: This is known as the trust policy. It defines who can assume the role — in our case, lambda.amazonaws.com.

  • This is essential so Lambda can act as the IAM role when it runs your function.

Attach a Basic Execution Policy

resource "aws_iam_role_policy_attachment" "lambda_logs" {
  role       = aws_iam_role.lambda_exec_role.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}

This policy gives Lambda permissions to:

  • Write logs to CloudWatch

  • Help with monitoring and debugging

Step 4: Package Your Code

Terraform doesn’t automatically zip your Lambda code. We use the archive_file data source to zip it.

data "archive_file" "lambda_zip" {
  type        = "zip"
  source_dir  = "${path.module}/lambda_function"
  output_path = "${path.module}/lambda_function.zip"
}

This zips the folder and creates lambda_function.zip, which AWS Lambda can read.

Step 5: Create the Lambda Function in Terraform

resource "aws_lambda_function" "my_lambda" {
  function_name = "MySampleLambda"
  role          = aws_iam_role.lambda_exec_role.arn
  handler       = "lambda_function.handler"
  runtime       = "python3.9"
  filename      = data.archive_file.lambda_zip.output_path
  source_code_hash = data.archive_file.lambda_zip.output_base64sha256
}
  • function_name: Name in AWS

  • role: IAM role for permissions

  • handler: Entry point (filename.function)

  • runtime: Language version

  • filename: Path to ZIP

  • source_code_hash: Triggers update if code changes

Step 6: Output Lambda Function Name

In outputs.tf:

output "lambda_function_name" {
  value = aws_lambda_function.my_lambda.function_name
}

This prints the function name after deployment — useful for scripting and validation.

Step 7: Terraform Workflow

terraform init    # Downloads providers and sets up state
terraform plan    # Shows what will be created
terraform apply   # Deploys the infrastructure

After a successful apply, Terraform will output the Lambda function name.

Terraform init:

After applied terraform apply:

Lambda Function Created in Console Via after terraform apply:

Function Execution:

Logs from CloudWatch:

After applied terrafrom destroyed :

Lambda Function got removed from console:

Final Thoughts

Using Terraform to manage Lambda functions makes deployments repeatable and version-controlled. With a clear understanding of IAM roles, policies, and packaging — you’re well on your way to building production-ready serverless applications.

0
Subscribe to my newsletter

Read articles from Onkar Vilas Kotmire directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Onkar Vilas Kotmire
Onkar Vilas Kotmire