Search code examples
amazon-web-servicesterraformamazon-cloudwatchterraform-provider-awsamazon-cloudwatchlogs

Terraform create a Cloudwatch rule with multiple targets


From the Terraform docs - https://www.terraform.io/docs/providers/aws/r/cloudwatch_event_target.html

I don't see an option to map multiple targets to the same Cloudwatch rule. It only takes an arn field which accepts one resource. I'm trying to map 5 Lambdas to the same Cloudwatch rule. Does Terraform support this?

EDIT: How can I attach only 5 lambdas? If I've created 15 lambdas, I want to attach 5 each to 3 cloudwatch rules.


Solution

  • Got it working! I had to divide the count of the rules by 5 when I assigned targets to rules. This is roughly what it looks like:

    resource "aws_cloudwatch_event_rule" "arule" {
      count       = "${ceil(length(var.lambda_arns) / 5.0)}"  // Needs to be 5.0 to force float computation
      name        = "${var.rule_name}${format("-%d", count.index)}"
      is_enabled  = true
    }
    
    resource "aws_cloudwatch_event_target" "atarget" {
      depends_on = ["aws_cloudwatch_event_rule.arule"]
      count = "${length(var.lambda_arns)}"
      rule  = "${aws_cloudwatch_event_rule.arule.*.name[count.index / 5]}"
      arn   = "${var.lambda_arns[count.index]}"
    }
    

    I created the event rules based on the number of lambdas (i.e., if there are 10 lambdas, 2 rules are created).

    I created the targets based on number of lambdas (i.e., if there are 10 lambdas, 10 targets are created).

    I assigned the targets proportionally among the rules by dividing the count.index by 5 (the same logic used to determine the count of rules).