AWS

AWS Lambda Example based on Teraform

CK CK 3788 
Created at  
901 0 0

AWS Lambda is a serverless compute service that lets you run code without provisioning or managing servers. You can upload your code and Lambda will automatically run it in response to events, such as HTTP requests, file uploads, or database changes. This allows you to focus on your code and let AWS handle the infrastructure, scaling, and security. 
 

Here’s a simple example of deploying an AWS Lambda function using Terraform. This example will cover creating a Lambda function, an IAM role for execution, and configuring the function to trigger from an API Gateway endpoint.

 

Example: AWS Lambda with API Gateway

This example will:

  1. Create an AWS Lambda function.
  2. Create an IAM role with necessary permissions for the Lambda function.
  3. Set up an API Gateway to trigger the Lambda function via an HTTP endpoint.

 

Prerequisites

Make sure you have:

  • A zip file with your Lambda function code, which we’ll reference in the example.
  • Basic knowledge of AWS services and Terraform setup.

 

Step 1: Define Variables (variables.tf)

Define any required variables to keep the configuration flexible.

variable "lambda_function_name" {
  default     = "example-lambda-function"
  description = "Name of the Lambda function"
}

variable "lambda_handler" {
  default     = "lambda_function.lambda_handler"
  description = "Handler for the Lambda function"
}

variable "lambda_runtime" {
  default     = "python3.8"
  description = "Runtime environment for Lambda"
}

variable "lambda_role_name" {
  default     = "lambda_execution_role"
  description = "IAM role for Lambda execution"
}

variable "lambda_zip_file" {
  default     = "./lambda_function.zip"
  description = "Path to the zip file containing the Lambda code"
}

 

Step 2: Create the IAM Role for Lambda Execution (main.tf)

The Lambda function needs an execution role that allows it to log to CloudWatch.

resource "aws_iam_role" "lambda_execution_role" {
  name = var.lambda_role_name

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

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

 

Step 3: Create the Lambda Function

Use the aws_lambda_function resource to deploy the Lambda function.

resource "aws_lambda_function" "example_lambda" {
  function_name = var.lambda_function_name
  role          = aws_iam_role.lambda_execution_role.arn
  handler       = var.lambda_handler
  runtime       = var.lambda_runtime

  # Specify the path to the zip file containing the Lambda function code
  filename = var.lambda_zip_file

  # Environment variables (optional)
  environment {
    variables = {
      LOG_LEVEL = "info"
    }
  }
}

 

Step 4: Set Up API Gateway to Trigger the Lambda Function

This will create an API Gateway endpoint that triggers the Lambda function when accessed via HTTP.

# Create the API Gateway REST API
resource "aws_apigatewayv2_api" "lambda_api" {
  name          = "example-api"
  protocol_type = "HTTP"
}

# Integrate the API Gateway with the Lambda function
resource "aws_apigatewayv2_integration" "lambda_integration" {
  api_id           = aws_apigatewayv2_api.lambda_api.id
  integration_type = "AWS_PROXY"
  integration_uri  = aws_lambda_function.example_lambda.invoke_arn
  integration_method = "POST"
  payload_format_version = "2.0"
}

# Create a route to connect API Gateway with Lambda
resource "aws_apigatewayv2_route" "default_route" {
  api_id    = aws_apigatewayv2_api.lambda_api.id
  route_key = "$default"
  target    = "integrations/${aws_apigatewayv2_integration.lambda_integration.id}"
}

# Deploy the API Gateway
resource "aws_apigatewayv2_stage" "api_stage" {
  api_id      = aws_apigatewayv2_api.lambda_api.id
  name        = "$default"
  auto_deploy = true
}

# Grant API Gateway permission to invoke the Lambda function
resource "aws_lambda_permission" "apigw_lambda" {
  statement_id  = "AllowAPIGatewayInvoke"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.example_lambda.function_name
  principal     = "apigateway.amazonaws.com"
  source_arn    = "${aws_apigatewayv2_api.lambda_api.execution_arn}/*/*"
}

 

Step 5: Apply the Terraform Configuration

  1. Run terraform init to initialize the directory.
  2. Run terraform plan to see the resources that will be created.
  3. Run terraform apply and type yes to confirm.

 

After applying, the API Gateway endpoint URL will look something like this:

https://<api-id>.execute-api.<region>.amazonaws.com/

You can invoke the Lambda function by making an HTTP request to this URL (e.g., using curl or a web browser).

 

Summary

  • IAM Role: Allows the Lambda function to log to CloudWatch.
  • Lambda Function: Deploys the code and sets runtime settings.
  • API Gateway: Sets up an HTTP trigger for the Lambda function.

This basic setup deploys a Lambda function with an API Gateway endpoint. For production, consider adding additional security, such as API keys or AWS IAM authorizations.

Tags AWS Lambda Teraform Teraform Example Facebook X
Comments 0
Similar posts
  1. Simple AWS ECS example based on Teraform
    989
  2. Image Moderation Chatbot - a serverless chatbot on AWS that monitors chat channels and removes images suggestive or explicit image
    10,426
  3. Teraform from the scratch
    1,357
  4. Building an AWS SAM(Serverless Application Model) Project
    899
  5. AWS Lambda Code Example based on Python
    333
  6. Messaging Platform with Limited TPS based on the vendor
    198
  1. A Python script to create an EC2 Spot instance using boto3
    1,603
  2. A Python/PHP code to deregister anormalous instaces in Amazon ECS
    1,858
  3. Where to get AWS API Key at AWS Management Console?
    1,071
  4. Understanding Amazon Bedrock Agent for AI-based ChatBot
    644
  5. Media sharing service architecture in AWS
    10,367
  6. Enterprise Data Lake Architecture based on AWS
    10,407
  7. "502 Bad Gateway" Error easy to happen at the combination of nginx and node.js in AWS Elastic Beanstalk
    10,490
  8. How to Set Up and Deploy Containerized Applications with AWS ECS
    10,675
  9. Power of Containerized Deployment with AWS ECS
    10,597
  10. FAISS Already Does ANN... So Why Do Top Teams Still Pay for SageMaker?
    310
  11. Recommended Vector DB Structure for Amazon Bedrock Integration
    390
  12. Product Marketing & Recommendation Architecture in AWS for e-commerce website
    10,737
  13. What cause a 502 bad gateway error in AWS environment?
    444
  14. Check incomplete multipart uploads if AWS S3 storage size is abnormally big huge compared to the origin storage
    11,598
  15. Importing a wild card domain SSL certificate into AWS Certificate Manager
    10,348
  16. Web front-end architecture in AWS for e-commerce website
    366
  17. Web Application Hosting provides the reliable, scalable, secure, and high-performance infrastructure
    10,615
  18. Time series processing architecture in AWS
    10,559
  19. Synchronous online gaming architecutre in AWS - Highly Available, Scalable & Elastic to support Millions of Players
    10,417
  20. Secure and Scalable LAMP Service Architecture in AWS
    10,661
  21. Live streaming / Static Content & Media Service based on AWS
    10,656
  22. Large scale messenger service architecture in AWS - Slack case study
    11,674
  23. Large scale computing based on huge data sets in AWS
    10,610
  24. Financial services grid computing in AWS
    10,354
  25. File synchronization service architecture in AWS
    10,377
  26. Fault Tolerance & High Availability based on multi Availability zones in AWS
    10,809
  27. Disaster recovery solution in AWS for local applications
    11,179
  28. Content Distribution for VOD streaming services in AWS
    10,357
  29. Checkout service architecture in AWS for e-commerce website
    11,010
  30. Batch processing composed of job manager, job store and worker based on AWS
    10,450
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    42
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    36
  3. How do I create animated background for Google Meet?
    21,044
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    252
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    71
  11. Frequency Cap Architecture Overview
    515
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    288
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    232
  16. TPU & GPU Cluster Management Tools
    245
  17. The Concept of Scaffolding in AI Agents
    234
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    259
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    222
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    221
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    257
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    196
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    219
  30. Understanding Data Lineage
    263