From 3787c795ed49063eaff0db4ed4ff2c0b93ab8775 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Taveira=20Ara=C3=BAjo?= Date: Mon, 13 Mar 2023 11:44:35 -0700 Subject: [PATCH] fix(cloudwatch_metrics): revert to cron expression PR #62 fixed our schedule expression to fire at the correct cadence, but subtly changed the time at which the rule would trigger. The use of the `rate` function ensures a rule will trigger at regular intervals from rule creation. Given the nature of the data we are collecting, we want rules to trigger aligned to fixed time boundaries (e.g. every minute, every hour). This commit reintroduces a correct cron expression. --- modules/cloudwatch_metrics/main.tf | 12 +++++++++++- modules/cloudwatch_metrics/variables.tf | 4 ++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/modules/cloudwatch_metrics/main.tf b/modules/cloudwatch_metrics/main.tf index fb64fda..a90ebd3 100644 --- a/modules/cloudwatch_metrics/main.tf +++ b/modules/cloudwatch_metrics/main.tf @@ -36,10 +36,20 @@ resource "aws_iam_role_policy_attachment" "this" { policy_arn = aws_iam_policy.this.arn } + + +locals { + cron_expression = coalesce( + var.interval >= 60 && var.interval < 60 * 60 ? "*/${var.interval / 60} * * * ? *" : "", # minutely + var.interval >= 60 * 60 && var.interval < 24 * 60 * 60 ? "0 */${var.interval / 60 / 60} * * ? *" : "", # hourly + var.interval >= 24 * 60 * 60 ? "0 0 */${var.interval / 24 / 60 / 60} * ? *" : "", # daily + ) +} + resource "aws_cloudwatch_event_rule" "trigger" { name_prefix = var.eventbridge_name_prefix description = "Periodically trigger Observe Lambda to collect CloudWatch metrics" - schedule_expression = var.interval == 60 ? "rate(1 minute)" : "rate(${var.interval / 60} minutes)" + schedule_expression = "cron(${local.cron_expression})" event_bus_name = var.eventbridge_schedule_event_bus_name } diff --git a/modules/cloudwatch_metrics/variables.tf b/modules/cloudwatch_metrics/variables.tf index 4fee4ed..50fb6dc 100644 --- a/modules/cloudwatch_metrics/variables.tf +++ b/modules/cloudwatch_metrics/variables.tf @@ -35,8 +35,8 @@ variable "interval" { nullable = false default = 300 validation { - condition = var.interval >= 60 && var.interval <= 10800 - error_message = "interval must be in [60, 10800] (1 minute to 3 hours)" + condition = (var.interval >= 60 && var.interval <= 60 * 60) || (var.interval >= 60 * 60 && var.interval <= 24 * 60 * 60 && var.interval % (60 * 60) == 0) + error_message = "interval must be minutely, up to an hour, or hourly, up to a day" } }