Search code examples
amazon-web-servicesaws-lambdaterraformaws-event-bridge

Why isn't my Event Bridge rule executing my Lambda function?


I am trying to create an Event Bridge rule that will run my Lambda function every 30 mins. I based my code on this answer I found here on SO Use terraform to set up a lambda function triggered by a scheduled event source

Here is my terraform code:

monitoring/main.tf:

...

module "cloudwatch_event_rule" {
  source = "./cloudwatch_event_rule"
  extra_tags = local.extra_tags
}

module "lambda_function" {
  source = "./lambda_functions"
  extra_tags = local.extra_tags
  alb_names = var.alb_names
  slack_webhook_url = var.slack_webhook_url
  environment_tag = local.environment_tag
}

module "cloudwatch_event_target" {
  source = "./cloudwatch_event_target"
  lambda_function_arn = module.lambda_function.detect_bad_rejects_on_alb_lambda_arn
  cloudwatch_event_rule_name = module.cloudwatch_event_rule.cloudwatch_event_rule_name
  extra_tags = local.extra_tags
}

monitoring/lambda_functions/main.tf:

resource "aws_lambda_function" "detect_bad_rejects_on_alb" {
  filename         = var.filename
  function_name    = var.function_name
  role             = aws_iam_role.detect_bad_reject_on_alb.arn
  handler          = var.handler
  source_code_hash = filebase64sha256(var.filename)
  runtime          = var.runtime
  timeout          = var.timeout
  environment {
      ...    
  }

}

monitoring/cloudwatch_event_rule/main.tf

resource "aws_cloudwatch_event_rule" "event_rule" {
    name = var.rule_name
    description = var.description
    schedule_expression = var.schedule_expression
    tags = ...
}

monitoring/cloudwatch_event_rule/variables.tf

...

variable "schedule_expression" {
  type = string
  default = "rate(30 minutes)"
}

...

monitoring/cloudwatch_event_target/main.tf

resource "aws_cloudwatch_event_target" "event_target" {
  arn   = var.lambda_function_arn
  rule  = var.cloudwatch_event_rule_name
  input = var.input
}

This ends up creating the lambda function and the event bridge rule with my lambda function as its target with the schedule expression "rate(30 minutes)" but the lambda function is never executed? What am I doing wrong?


Solution

  • From what you posted is seems that you are not adding permissions for invocations. Your code does not show creation of aws_lambda_permission with proper rules. So you should add such permissions so that EventBridge can invoke your function (example):

    resource "aws_lambda_permission" "event-invoke" {
        statement_id = "AllowExecutionFromCloudWatch"
        action = "lambda:InvokeFunction"
        function_name = var.function_name
        principal = "events.amazonaws.com"
        source_arn = module.cloudwatch_event_rule.cloudwatch_event_rule_arn
    }
    

    Make sure source_arn correctly points to the ARN of your event rule.