DEV Community

Akanksha
Akanksha

Posted on

Multiple rule to one target in terraform

Hi , I have created three cloduwatch event rules and want to assign to one lambda function as target. Can anyone help me with the code how to do it in terraform.

Top comments (1)

Collapse
 
rolfstreefkerk profile image
Rolf Streefkerk • Edited

The basic setup of linking an event to a lambda (1 or more) is like this:

The cloudwatch event rule

resource "aws_cloudwatch_event_rule" "_" {
  name                = "${local.resource_name_prefix}-${var.event_rule_name}"
  description         = var.event_rule_description
  schedule_expression = var.schedule_expression
  is_enabled          = var.is_enabled
}
Enter fullscreen mode Exit fullscreen mode

For each lambda you will have to set the two resources below (aws_cloudwatch_event_target and aws_lambda_permission):

resource "aws_cloudwatch_event_target" "_" {
  rule      = aws_cloudwatch_event_rule._.name
  target_id = var.lambda_function_name
  arn       = var.lambda_function_arn
}
Enter fullscreen mode Exit fullscreen mode

Permission to allow cloudwatch event to execute the Lambda:

resource "aws_lambda_permission" "_" {
  statement_id  = "AllowExecutionFromCloudWatch"
  action        = "lambda:InvokeFunction"
  function_name = var.lambda_function_arn
  principal     = "events.amazonaws.com"
  source_arn    = aws_cloudwatch_event_rule._.arn
}
Enter fullscreen mode Exit fullscreen mode

That's it