variable "aws_instance_list" {
type = list
default = ["i-07dd009cf6a72720b","i-047101ccb46330773"]
}
resource "aws_cloudwatch_dashboard" "main" {
dashboard_name = "my-dashboard"
dashboard_body = jsonencode({
widgets = [
{
type = "metric"
x = 0
y = 0
width = 12
height = 6
properties = {
metrics = [
[
"AWS/EC2",
"CPUUtilization",
"InstanceId",
"i-07dd009cf6a72720b" #want this to change for each loop from the list
]
]
period = 300
stat = "Average"
region = "us-east-1"
title = "EC2 Instance CPU"
}
}
]
})
}
我正在尝试迭代小部件部分,而不是一次又一次地复制和粘贴整个块。希望能参考一份清单。关于如何实现这个的任何想法?
这是使用 字符串模板 和
jsonencode
的相同演示。希望这有帮助!
# providers
terraform {
required_providers {
local = {
source = "hashicorp/local"
version = "2.4.1"
}
}
}
variable "aws_instance_list" {
type = list(string)
default = ["i-07dd009cf6a72720b","i-047101ccb46330773"]
}
# Output widgets JSON
# for s in var.aws_instance_list :
output "all_widgets" {
value = jsonencode(
[ for i in var.aws_instance_list :
{
type = "metric"
x = 0
y = 0
width = 12
height = 6
properties = {
metrics = [
[
"AWS/EC2",
"CPUUtilization",
"InstanceId",
"${i}" #want this to change for each loop from the list
]
]
period = 300
stat = "Average"
region = "us-east-1"
title = "EC2 Instance CPU"
}
}
]
)
}
显示输出:
terraform output -raw all_widgets
。