我一直在学习 terraform,并且一直在使用仪表板。
我有以下文件来生成仪表板。
resource "aws_cloudwatch_dashboard" "main" {
dashboard_name = "sample_dashboard"
dashboard_body = <<EOF
{
"widgets": [
${templatefile("${path.module}/cpu.tmpl", { ids = aws_instance.web[*].id })},
${templatefile("${path.module}/network.tmpl", { ids = aws_instance.web[*].id })}
]
}
EOF
}
这是CPU模板文件。
{
"type": "metric",
"x": 0,
"y": 0,
"width": 12,
"height": 6,
"properties": {
"metrics": ${jsonencode([for id in ids : ["AWS/EC2","CPUUtilization","InstanceId", "${id}"]])},
"period": 300,
"stat": "Average",
"region": "us-east-1",
"title": "EC2 Instance CPU"
}
}
这里有网络模板文件。
{
"type": "metric",
"x": 12,
"y": 0,
"width": 12,
"height": 6,
"properties": {
"metrics": ${jsonencode([for id in ids :
["AWS/EC2", "NetworkIn", "InstanceId", "${id}"]
])},
"period": 300,
"stat": "Average",
"region": "us-east-1",
"title": "EC2 Instance Network"
}
}
我遇到的问题是当尝试在 for 循环中添加另一个指标时出现错误。
{
"type": "metric",
"x": 12,
"y": 0,
"width": 12,
"height": 6,
"properties": {
"metrics": ${jsonencode([for id in ids :
["AWS/EC2", "NetworkIn", "InstanceId", "${id}"],
["AWS/EC2", "NetworkOut", "InstanceId", "${id}"]
])},
"period": 300,
"stat": "Average",
"region": "us-east-1",
"title": "EC2 Instance Network"
}
}
我收到以下错误。
Call to function "templatefile" failed: ./network.tmpl:9,70-71: Invalid 'for' expression; Extra characters after the end of the 'for' expression..
一如既往地提前感谢您的帮助。
最佳答案
解决该问题的一种方法是 concat您的指标:
{
"type": "metric",
"x": 12,
"y": 0,
"width": 12,
"height": 6,
"properties": {
"metrics": ${jsonencode(concat([for id in ids :
["AWS/EC2", "NetworkIn", "InstanceId", "${id}"]
], [for id in ids :
["AWS/EC2", "NetworkOut", "InstanceId", "${id}"]
]))},
"period": 300,
"stat": "Average",
"region": "us-east-1",
"title": "EC2 Instance Network"
}
}
关于amazon-web-services - Terraform for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63756500/