Terraform
AWS Lambda
Scheduled Events
Infrastructure as Code
Cloud Automation

Use terraform to set up a lambda function triggered by a scheduled event source

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

AWS Lambda is a popular serverless compute service that allows users to run code without provisioning or managing servers. Often, there is a need to make these functions execute on a regular schedule, such as processing daily reports or cleaning up resources at midnight. This is where AWS CloudWatch Events or Amazon EventBridge Scheduled Events come in handy. Terraform, an Infrastructure as Code (IaC) tool, can simplify the process of deploying a Lambda function with a scheduled event trigger. This article will walk through setting up this configuration using Terraform.

Prerequisites

Before proceeding, ensure you have the following:

  • An AWS account.
  • Terraform installed on your local machine.
  • Basic understanding of AWS services, particularly Lambda and CloudWatch.
  • Familiarity with Terraform syntax and workflow.

Terraform Setup

Step 1: Provider Configuration

First, configure the AWS provider. This lets Terraform know that you'll be provisioning AWS resources.

hcl
1provider "aws" {
2  region = "us-west-2" // Specify your preferred region
3}
4

Step 2: Define the Lambda Function

Create the Lambda function. Here, you'll need a zip file containing your function code and any dependencies.

hcl
1resource "aws_lambda_function" "my_lambda" {
2  filename         = "lambda_function_payload.zip" // The zip file containing your function code
3  function_name    = "MyScheduledLambda"           // A descriptive name for your function
4  role             = aws_iam_role.lambda_exec.arn  // IAM role that AWS Lambda can assume
5  handler          = "index.handler"               // The method in your code that is invoked
6  runtime          = "nodejs14.x"                  // Runtime environment for the Lambda
7
8  source_code_hash = filebase64sha256("lambda_function_payload.zip")  // Helps in identifying if function code has changed
9}

Step 3: Define IAM Role and Policy

Create the necessary IAM role and attach policies to allow Lambda execution.

hcl
1resource "aws_iam_role" "lambda_exec" {
2  name = "lambda-basic-exec-role"
3
4  assume_role_policy = {
5    Version = "2012-10-17"
6    Statement = [
7      {
8        Action = "sts:AssumeRole"
9        Effect = "Allow"
10        Principal = {
11          Service = "lambda.amazonaws.com"
12        }
13      }
14    ]
15  }
16}
17
18resource "aws_iam_policy_attachment" "lambda_basic_execution" {
19  name       = "attach-lambda-basic-exec"
20  roles      = [aws_iam_role.lambda_exec.name]
21  policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
22}

Step 4: Set Up the Scheduled Event

To schedule a Lambda function, you can use a CloudWatch Events rule to trigger it. Create a rule for your desired schedule using cron or rate expressions.

hcl
1resource "aws_cloudwatch_event_rule" "every_minute" {
2  name                = "EveryMinuteRule"
3  schedule_expression = "rate(1 minute)" // This runs the function every minute
4}
5
6resource "aws_cloudwatch_event_target" "lambda_target" {
7  rule      = aws_cloudwatch_event_rule.every_minute.name
8  target_id = "MyLambdaFunction"
9  arn       = aws_lambda_function.my_lambda.arn
10}

Step 5: Allow Event Source Invocation

Grant the CloudWatch Events permission to invoke the Lambda function.

hcl
1resource "aws_lambda_permission" "allow_cloudwatch" {
2  statement_id  = "AllowCloudWatchInvoke"
3  action        = "lambda:InvokeFunction"
4  function_name = aws_lambda_function.my_lambda.function_name
5  principal     = "events.amazonaws.com"
6  source_arn    = aws_cloudwatch_event_rule.every_minute.arn
7}

Deploying with Terraform

  1. Initialize Terraform:
bash
   terraform init

This step downloads the necessary provider plugins.

  1. Preview Changes:
bash
   terraform plan

This command provides an overview of what resources will be created.

  1. Apply Configuration:
bash
   terraform apply

Confirm the action to have Terraform provision the resources.

Cleanup

To ensure cost efficiency and destruction of all resources that were created, run the following command:

bash
terraform destroy

Summary Table

Key ComponentDescriptionExamples
AWS ProviderConfigures access to AWS servicesprovider "aws" { region = "us-west-2" }
IAM Role & PoliciesGrants necessary permissions for Lambda to executeVarious resources like aws_iam_role, aws_iam_policy_attachment
Lambda FunctionCode and configuration for the serverless functionSpecified using aws_lambda_function
CloudWatch Event RuleSchedules the function executionDefined with aws_cloudwatch_event_rule
Event PermissionsAllows CloudWatch Events to invoke the Lambda functionManaged via aws_lambda_permission

Conclusion

Using Terraform to set up a Lambda function with a scheduled event source simplifies the process of staying infrastructure as code-centric. This methodology ensures your infrastructure is versioned and repeatable, proved by its documented configuration, as seen in the provided example. Once understood, this process can easily be tailored to other serverless frameworks or integrated into more complex AWS deployments. Terraform’s declarative approach allows infrastructure scalability and flexibility, streamlining operations and management.


Course illustration
Course illustration

All Rights Reserved.