Schedule AWS Lambda Functions Using Terraform

Managing AWS Lambda functions efficiently is crucial for modern cloud architectures. In this post, we’ll show how to make a simple homemade Terraform module that simplifies the scheduling of AWS Lambda functions using CloudWatch Events. This approach is particularly useful for tasks like periodic data processing, automated backups, or any other operation that requires regular execution.

Below is a basic usage example, where the module is configured to trigger an AWS Lambda function named 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

The module utilizes two variables:

  • function_name: The name of the Lambda function to be scheduled.
  • schedule_expression: A cron or rate expression that defines the schedule.

These variables offer flexibility, allowing for easy integration into various workflows.

Module code

The module fixes versions of Terraform and AWS prodiver, ensuring compatibility with the latest AWS features and best practices.

terraform {
  required_version = ">= 1.5"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 4.67.0"
    }
  }
}

First, retrieve details of an existing AWS Lambda function from its name using the aws_lambda_function data source. This step ensures that the module targets the correct Lambda function for scheduling.

data "aws_lambda_function" "this" {
  function_name = var.function_name
}

Next, create a CloudWatch Event Rule. This rule defines when the Lambda function should be triggered. The schedule_expression variable allows for flexible scheduling configurations (see AWS documentation for expressions).

resource "aws_cloudwatch_event_rule" "this" {
  name                = "schedule-${var.function_name}"
  schedule_expression = var.schedule_expression
}

Then create a aws_cloudwatch_event_target resource linking the created Event Rule to the Lambda function. It specifies the Lambda function as the target for the events generated based on the defined schedule.

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
}

Lastly, for the CloudWatch Event Rule to invoke the Lambda function, the correct permissions must be set. This is accomplished through the aws_lambda_permission resource.

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
}

Complete code

Here is the complete code for the module

Comments