Use Terraform to set up a Lambda function triggered by a scheduled event source

AWS Lambda functions can be triggered by scheduled events, such as cron jobs, using Amazon EventBridge (formerly CloudWatch Events). Terraform makes it easy to set up this integration.
Prerequisites
- An AWS account with appropriate permissions.
- Terraform installed on your system.
Steps to Set Up a Lambda Function with a Scheduled Event
Step 1: Write the Lambda Function Code
Create a simple Python script for the Lambda function. Save it as lambda_function.py:
def lambda_handler(event, context):
print("Scheduled event triggered")
return {
'statusCode': 200,
'body': 'Success'
}
Step 2: Create a Terraform Configuration
Define the resources needed for the Lambda function and the scheduled event.
resource "aws_iam_role" "lambda_role" {
name = "lambda_execution_role"
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_policy" {
role = aws_iam_role.lambda_role.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}
resource "aws_lambda_function" "example" {
filename = "lambda_function.zip"
function_name = "example_lambda"
role = aws_iam_role.lambda_role.arn
handler = "lambda_function.lambda_handler"
runtime = "python3.9"
source_code_hash = filebase64sha256("lambda_function.zip")
}
resource "aws_cloudwatch_event_rule" "schedule" {
name = "example-schedule"
schedule_expression = "rate(5 minutes)"
}
resource "aws_cloudwatch_event_target" "lambda_target" {
rule = aws_cloudwatch_event_rule.schedule.name
target_id = "lambda"
arn = aws_lambda_function.example.arn
}
resource "aws_lambda_permission" "allow_cloudwatch" {
statement_id = "AllowExecutionFromCloudWatch"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.example.function_name
principal = "events.amazonaws.com"
source_arn = aws_cloudwatch_event_rule.schedule.arn
}
Step 3: Deploy the Configuration
Zip the Lambda function code:
zip lambda_function.zip lambda_function.pyInitialize Terraform:
terraform initApply the configuration:
terraform apply
Step 4: Verify the Setup
Check the AWS Management Console to ensure the Lambda function and scheduled event are set up correctly. The function should trigger every 5 minutes.
Best Practices
- Use environment variables to configure your Lambda function dynamically.
- Monitor your Lambda function with Amazon CloudWatch Logs.
- Use Terraform modules to organize your code for reusability.
By following these steps, you can efficiently set up a Lambda function triggered by a scheduled event using Terraform.
Try it hands-on
Run the commands from this article in the browser. Nothing to install.
Terraform Basics Simulator
Learn Terraform basics in an interactive browser lab. Read and edit the HCL config, run init, validate, plan, apply, and destroy, and watch state react to your edits. A free, hands-on way to learn infrastructure as code with no AWS account.
Terraform State Puzzle
Fix broken Terraform state without destroying production. Eight puzzles with real Terraform output: a rename that would replace a database, an import that forces replacement, a stale lock, drift, count index shifts and more. Choose between moved, import and removed blocks and the state commands.
We earn commissions when you shop through the links below.
Svix
Webhooks as a service
Svix Dispatch sends your webhooks for you: retries with exponential backoff, signed payloads, idempotency keys, and a delivery log your customers can see.
Atomsized
AWS platform engineering and GitOps
Design and automation for reliable AWS and Kubernetes platforms, safer delivery workflows, and preview and UAT environments your engineers can understand and own.
DigitalOcean
Cloud infrastructure for developers
Simple, reliable cloud computing designed for developers
DevDojo
Developer community & tools
Join a community of developers sharing knowledge and tools
SMTPfast
Developer-first email API
Send transactional and marketing email through a clean REST API. Detailed logs, webhooks, and embeddable signup forms in one dashboard.
QuizAPI
Developer-first quiz platform
Build, generate, and embed quizzes with a powerful REST API. AI-powered question generation and live multiplayer.
Want to support DevOps Daily and reach thousands of developers?
Become a SponsorFound an issue?
Related Posts
Also worth your time on this topic
Specifying an API Gateway Endpoint with a Variable in Terraform
Learn how to dynamically specify an API Gateway endpoint with a variable in Terraform for flexible configurations.
Terraform State Management
What is Terraform state, why is it important, and how do you manage state in a team environment?
mid
Terraform Repository Structure Checklist
Best practices for organizing and structuring your Terraform projects for maintainability and scalability.
30-45 minutes