From ab6d849a9581445c4d67d8835f441f36858920c1 Mon Sep 17 00:00:00 2001
From: Adar Nimrod <nimrod@shore.co.il>
Date: Fri, 30 Apr 2021 21:56:39 +0300
Subject: [PATCH] Schedule per function.

There's a limit of 5 targets per rule. So rule per function it is.
---
 functions.tf |  2 +-
 triggers.tf  | 23 ++++++++++++-----------
 2 files changed, 13 insertions(+), 12 deletions(-)

diff --git a/functions.tf b/functions.tf
index 9a2613d..0ba165e 100644
--- a/functions.tf
+++ b/functions.tf
@@ -185,7 +185,7 @@ resource "aws_lambda_permission" "cloudwatch" {
   statement_id  = "AllowExecutionFromCloudWatch"
   action        = "lambda:InvokeFunction"
   principal     = "events.amazonaws.com"
-  source_arn    = local.cloudwatch_rule_arn
+  source_arn    = local.cloudwatch_rule_arns[count.index]
   function_name = local.function_names[count.index]
   qualifier     = local.function_alias_names[count.index]
 }
diff --git a/triggers.tf b/triggers.tf
index ca835a7..e08e5ec 100644
--- a/triggers.tf
+++ b/triggers.tf
@@ -10,31 +10,32 @@ output "rate" {
 }
 
 resource "aws_cloudwatch_event_rule" "schedule" {
-  name                = local.Name
-  description         = "Schedule to trigger ${local.module} functions in ${local.env}."
+  count               = length(local.function_names)
+  name                = local.function_names[count.index]
+  description         = "Schedule to trigger ${local.function_names[count.index]} functions in ${local.env}."
   schedule_expression = "rate(${var.rate} minutes)"
   tags                = local.common_tags
 }
 
 locals {
-  cloudwatch_rule_arn  = aws_cloudwatch_event_rule.schedule.arn
-  cloudwatch_rule_name = aws_cloudwatch_event_rule.schedule.name
+  cloudwatch_rule_arns  = aws_cloudwatch_event_rule.schedule.*.arn
+  cloudwatch_rule_names = aws_cloudwatch_event_rule.schedule.*.name
 }
 
-output "cloudwatch_rule_arn" {
-  description = "ARN of the CloudWatch schedule rule."
-  value       = local.cloudwatch_rule_arn
+output "cloudwatch_rule_arns" {
+  description = "List of ARNs of the CloudWatch schedule rules."
+  value       = local.cloudwatch_rule_arns
 }
 
-output "cloudwatch_rule_name" {
-  description = "Name of the CloudWatch schedule rule."
-  value       = local.cloudwatch_rule_name
+output "cloudwatch_rule_names" {
+  description = "List of names of the CloudWatch schedule rules."
+  value       = local.cloudwatch_rule_names
 }
 
 resource "aws_cloudwatch_event_target" "schedule" {
   count = length(local.function_alias_arns)
   arn   = local.function_alias_arns[count.index]
-  rule  = local.cloudwatch_rule_name
+  rule  = local.cloudwatch_rule_names[count.index]
   depends_on = [
     aws_lambda_permission.cloudwatch,
   ]
-- 
GitLab