Schedule AWS Lambda Functions Using Terraform
Dec 13th, 2023Here’s a small Terraform module that wraps the CloudWatch Events plumbing needed to schedule a Lambda. Useful for periodic data processing, backups, or anything else that needs to run on a cron.
Usage — trigger the Lambda lambda-function-name at 3 AM UTC every day:
module "schedule-lambda-update-reporting" {
source = "../path/to/modules/schedule-lambda"
function_name = "lambda-function-name"
schedule_expression = "cron(0 3 * * ? *)"
}
Variables
function_name: the Lambda function to schedule.schedule_expression: a cron or rate expression.
Module code
Pin Terraform and the AWS provider:
terraform {
required_version = ">= 1.5"
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 4.67.0"
}
}
}
Look up the target Lambda by name using the aws_lambda_function data source:
data "aws_lambda_function" "this" {
function_name = var.function_name
}
Create a CloudWatch Event Rule with the schedule (see AWS docs on schedule expressions):
resource "aws_cloudwatch_event_rule" "this" {
name = "schedule-${var.function_name}"
schedule_expression = var.schedule_expression
}
Link the rule to the Lambda with an aws_cloudwatch_event_target:
resource "aws_cloudwatch_event_target" "this" {
target_id = "event-target-${var.function_name}"
rule = aws_cloudwatch_event_rule.this.name
arn = data.aws_lambda_function.this.arn
}
Finally, give the Event Rule permission to invoke the Lambda:
resource "aws_lambda_permission" "lambda-update-reporting" {
action = "lambda:InvokeFunction"
function_name = var.function_name
principal = "events.amazonaws.com"
source_arn = aws_cloudwatch_event_rule.this.arn
}