尝试使用 terraform 为 AWS cloudwatch 仪表板创建多个小部件,我不想继续复制粘贴?

问题描述 投票:0回答:1
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"
        }
      }
    ]
  })
}

我正在尝试迭代小部件部分,而不是一次又一次地复制和粘贴整个块。希望能参考一份清单。关于如何实现这个的任何想法?

amazon-web-services terraform amazon-cloudwatch
1个回答
0
投票

这是使用 字符串模板

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

另请参阅:Terraform JSON 生成资源:aws_cloudwatch_dashboard

© www.soinside.com 2019 - 2024. All rights reserved.