[英]Terraform error when trying to get count.index from var, error [count.index is 3 local.metric_names is object with 4 attributes]
我想要做的是在 Cloud Watch 上使用存儲在列表中的警報名稱和指標名稱創建警報。
為alarm_name和metric_name做一個通知。
主文件
locals {
alarm_names = { for x in var.alarm_names_list : x.name => x }
}
locals {
metric_names = { for x in var.metric_names_list : x.name => x }
}
resource "aws_cloudwatch_metric_alarm" "ec2_cpu" {
count = length(local.alarm_names)
alarm_name = "${local.alarm_names[count.index].name}-${var.name_instance_outout}"
comparison_operator = "GreaterThanOrEqualToThreshold"
evaluation_periods = "2"
metric_name = local.metric_names[count.index].name
namespace = "AWS/EC2"
period = "120" #seconds
statistic = "Average"
threshold = "80"
alarm_description = "This metric monitors ec2 cpu utilization"
insufficient_data_actions = []
dimensions = {
InstanceId = var.ec2_id_output
}
}
變量.tf
variable "metric_names_list" {
type = list(object({
name = string
}))
default = [
{
name = "CPUUtilization"
},
{
name = "DiskReadOps"
},
{
name = "NetworkIn"
},
{
name = "NetworkOut"
}
]
}
variable "alarm_names_list" {
type = list(object({
name = string
}))
default = [
{
name = "cpu-utilization-duk-test"
},
{
name = "memory-utilization"
},
{
name = "network-inbound"
},
{
name = "network-outbound"
}
]
}
我做了 2 個本地人,我不知道是否有可能將 2 個 for_each 循環分開而不是嵌套,因為我將始終在列表中為 alarm_name 和 metric_name 擁有相同數量的項目,所以我想我會讓它像這樣工作。
最初我只將變量作為 type = list(string) 放置,我想如果我把它們作為這個 list(object) 我會避免這個錯誤,但不幸的是它仍然出現。 波紋管是完整的錯誤輸出。
│ Error: Invalid index
│
│ on modules/cloudwatch/main.tf line 31, in resource "aws_cloudwatch_metric_alarm" "ec2_cpu":
│ 31: metric_name = local.metric_names[count.index].name
│ ├────────────────
│ │ count.index is 0
│ │ local.metric_names is object with 4 attributes
│
│
│ on modules/cloudwatch/main.tf line 31, in resource "aws_cloudwatch_metric_alarm" "ec2_cpu":
│ 31: metric_name = local.metric_names[count.index].name
│ ├────────────────
│ │ count.index is 3
│ │ local.metric_names is object with 4 attributes
│
│ The given key does not identify an element in this collection value. An object only supports looking up attributes by name, not by numeric index.
您的local.alarm_names
和local.alarm_names
是地圖,而不是list
。 要將它們更改為list
,它應該是:
locals {
alarm_names = [ for x in var.alarm_names_list : x.name ]
}
locals {
metric_names = [ for x in var.metric_names_list : x.name ]
}
然后
resource "aws_cloudwatch_metric_alarm" "ec2_cpu" {
count = length(local.alarm_names)
alarm_name = "${local.alarm_names[count.index]}-${var.name_instance_outout}"
comparison_operator = "GreaterThanOrEqualToThreshold"
evaluation_periods = "2"
metric_name = local.metric_names[count.index]
namespace = "AWS/EC2"
period = "120" #seconds
statistic = "Average"
threshold = "80"
alarm_description = "This metric monitors ec2 cpu utilization"
insufficient_data_actions = []
dimensions = {
InstanceId = var.ec2_id_output
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.