Terraform:循环遍历复杂对象的列表



我想循环浏览两个警报对象的列表,如下所示进行配置——问题是如何通过循环每个警报度量列表来动态生成metric_query块。。

locals{
prefix = terraform.workspace
alarm_WithExpression = [
{ "name" : "XXX",
"expression" : "m1/m2",
"metrics" : [
{ "id" : "m1", "name" : "YYYY", "statistic" : "Sum", "period" : 21600 },
{ "id" : "m2", "name" : "ZZZZZ" ,"statistic" : "Sum", "period" : 21600 }
],
"threshold" : 0.2,
"comparison_operator" : "LessThanThreshold",
"period" : 21600,
"data_points" : 2,
"treat_missing_data" : "notBreaching"
},
{ "name" : "AAAA",
"expression" : "m1/(m2-m3)",
"metrics" : [
{ "id" : "m1", "name" : "BBBB", "statistic" : "Sum", "period" : 21600 },
{ "id" : "m2", "name" : "CCCC", "statistic" : "Sum", "period" : 21600 },
{ "id" : "m3", "name" : "DDDD", "statistic" : "Sum", "period" : 21600 }
],
"threshold" : "0.2",
"comparison_operator" : "LessThanThreshold",
"period" : 21600,
"data_points" : 2,
"treat_missing_data" : "notBreaching"
}
]
}

以下是度量警报声明:

resource "aws_cloudwatch_metric_alarm" "metrics-withExpression_alarm" {
for_each            = local.prefix == "production" ? {} : {for index,m in local.alarm_WithExpression : index => m}
alarm_name          = "${local.prefix}-${each.value.name}"
comparison_operator = each.value.comparison_operator
evaluation_periods  = each.value.period
threshold           = each.value.threshold
treat_missing_data  = each.value.treat_missing_data
datapoints_to_alarm = each.value.data_points
metric_query {
id          = "e"
expression  = each.value.expression
return_data = "true"
}
# loop inside list of metrics ??
dynamic "metric_query" {
for_each = {for index,k in local.alarm_WithExpression.metrics : index => k}
content {
id = each.value.id
metric {
metric_name = each.value.name
namespace   = "${local.prefix}-metrics"
period      = each.value.period
stat        = each.value.statistic
}
}
}
}

我得到这个计划错误:

╷
│ Error: Unsupported attribute
│ 
│   on cloudwatch-alarms.tf line 177, in resource "aws_cloudwatch_metric_alarm" "metrics-withExpression_alarm":
│  177:     for_each = {for index,k in local.alarm_WithExpression.metrics : index => k}
│     ├────────────────
│     │ local.alarm_WithExpression is tuple with 2 elements
│ 
│ This value does not have any attributes.
╵
ERROR: 1

如何循环浏览每个警报指标列表?

您的问题是这个部分:

local.alarm_WithExpression.metrics

给你一些背景。local.alarm_WithExpression是一个列表。该列表没有metrics属性,因此.metrics没有提供您想要的内容。

我相信你的目标可以通过使用他们所说的splat表达式来实现,即

local.alarm_WithExpression[*].metrics

它可以用通俗的英语理解为:

对于local.alarm_withExpression中的每个对象,取其metrics属性

您可以像下面的一样实现这一点

dynamic "metric_query" {
for_each = each.value.metrics
content {
id = metrics.value["id"]
metric {
metric_name = metrics.value["name"]
namespace   = "${local.prefix}-metrics"
period      = metrics.value["period"]
stat        = metrics.value["statistic"]
}
}
}

相关内容

  • 没有找到相关文章