Invoke Lambda with Cloudwatch Event Rule | Terraform

Timam
1 min readJun 30, 2021

--

I needed to invoke lambda from an Cloudwatch Event rule. With the following code, I created a lambda function.
Note: data.archive_file.awesome-lambda and aws_iam_role.awesome-lambda is not covered here.

resource "aws_lambda_function" "awesome-lambda" {
function_name = "awesome-lambda"
filename = data.archive_file.awesome-lambda.output_path
runtime = "python3.8"
handler = "awesome-lambda.lambda_handler
role = aws_iam_role.awesome-lambda.arn
source_code_hash = data.archive_file.awesome-lambda.output_base64sha256
timeout = 30
memory_size = 128
}

I have created an Cloudwatch Event Rule with following code

resource "aws_cloudwatch_event_rule" "cloudwatch-rule" {
name = "cloudwatch-rule"
description = "Alarms based on Autoscaling events"
event_pattern = jsonencode({
"detail-type": ["EC2 Instance Launch Successful", "EC2 Instance Terminate Successful"],
"source": ["aws.autoscaling"],
"detail": {
"AutoScalingGroupName": [
"my-dumb-autoscale-gro"]
}
})
}

It should work right ? Unfortunately it is missing permission. To fix permission issue, I wrote following code and it starts working, cheers.

resource "aws_lambda_permission" "awesome-lambda-perm" {
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.awesome-lambda.function_name
principal = "events.amazonaws.com"
source_arn = aws_cloudwatch_event_rule.cloudwatch-rule.arn
}

--

--

Timam
Timam

Written by Timam

Command Engineer, HTML Programmer

No responses yet