如何将 AWS 警报 ARN 收集到 Terraform 中的字符串中以用于 CloudWatch 仪表板创建 JSON?

How to collect AWS alarm ARNs into a string in Terraform to use in a CloudWatch Dashboard creation JSON?

我正在使用 Terraform 创建一组 CloudWatch 警报,如下所示:

resource "aws_cloudwatch_metric_alarm" "lambda_concurrent_executions" {
  for_each = toset(var.function_names)

  alarm_name          = "${each.key}-concurrent-executions"
  alarm_description   = "The number of function instances that are processing events."
  namespace           = "AWS/Lambda"
  metric_name         = "ConcurrentExecutions"
  comparison_operator = "GreaterThanOrEqualToThreshold"
  statistic           = "Sum"
  period              = "60"
  evaluation_periods  = "1"
  threshold           = "100"

  treat_missing_data = "ignore"

  dimensions = {
    FunctionName = each.key
  }

  alarm_actions = var.alarm_actions
  ok_actions    = var.alarm_actions
}

所以它使用 for_each 函数名称列表。

接下来,我需要创建一个 CloudWatch 仪表板。它显然是通过提供具有相关名称 (documentation) 的 JSON 创建的:

resource "aws_cloudwatch_dashboard" "main" {
  dashboard_name = "my-dashboard"

  dashboard_body = <<EOF
{
    "widgets": [
        {
            "type": "alarm",
            "x": 0,
            "y": 0,
            "width": 12,
            "height": 6,
            "properties": {
                "title": "Alarms",
                "alarms": [
                    "arn:aws:cloudwatch:eu-west-1:167170067742:alarm:mylambda-concurrent-executions",
                    "arn:aws:cloudwatch:eu-west-1:167170067742:alarm:mylambda-concurrent-executions-2",
                    "arn:aws:cloudwatch:eu-west-1:167170067742:alarm:mylambda-concurrent-executions-3",
                    "arn:aws:cloudwatch:eu-west-1:167170067742:alarm:mylambda-concurrent-executions-4",
   
/// ... and so on
}
EOF
}

我如何收集变量中创建的警报 ARN 并将它们插入仪表板 JSON?

您需要对 aws_cloudwatch_metric_alarm 资源进行 for 循环。

我用以下方法模拟了你的设置:

variable "function_names" {
  type    = list(string)
  default = ["fun-1", "fun-2", "fun-3"]
}

resource "null_resource" "lambda_concurrent_executions" {
  for_each = toset(var.function_names)

  triggers = {
    function_name = each.key
  }
}

然后像这样的东西使我能够遍历 for_each 生成的资源:

join(", ", [for i in null_resource.lambda_concurrent_executions : format("\"%s\"", i.id)])

因此对于您的示例,您需要警报 ARN 的部分将变为:

"alarms": [${join(", ", [for a in aws_cloudwatch_metric_alarm.lambda_concurrent_executions : format("\"%s\"", a.arn)])}]

(顺便说一句。它也应该与 splat expression 一起使用,但我只能让它与传统的 for 循环一起使用。)