使用 Terraform 迭代 Json

Iterate over Json using Terraform

您好,提前谢谢您:)

我有一个 json 文件,其中包含需要作为主机添加到 Zabbix 的数据。

{
    "hosts": [{
            "name": "test1",
            "ip": "8.8.8.8",
            "link_templates": "ICMP Ping",
            "host_groups": "api_imported"
        },
        {
            "name": "test2",
            "ip": "1.1.1.1",
            "link_templates": "ICMP Ping",
            "host_groups": "api_imported"
        }
    ]
}

我不确定如何使用 terraform 遍历此文件。我已经能够遍历主机名,但不确定如何在其余字段上使用它。

terraform {
  required_providers {
    zabbix = {
      source = "claranet/zabbix"
      version = "0.2.0"
    }
  }
}

provider "zabbix" {
  user       = var.user
  password   = var.password
  server_url = var.server_url
}

locals {
  user_data = jsondecode(file("host.json"))
  hostname = [for host in local.user_data.hosts : host.name]
}


output "host" {
    value = local.hostname
}

resource "zabbix_host" "zabbix" {
  for_each = toset(local.hostname)
  host = "127.0.0.1"
  name = each.value
  interfaces {
    ip = "127.0.0.1"
    main = true
  }
  groups = ["Linux servers"]
  templates = ["ICMP Ping"]
}

我想添加“主机、IP、组和模板”

Changes to Outputs:
  + host = [
      + "test1",
      + "test2",
    ]

你快到了。不要在 locals 变量中指向 host.name。如下图直接使用host

locals {
  user_data = jsondecode(file("host.json"))
  hosts = [for host in local.user_data.hosts : host]
}

output "hosts" {
  value = local.hosts
}

然后,您可以像下面这样遍历 hosts 列表和获取属性..

resource "zabbix_host" "zabbix" {
  for_each = {
    for host in local.hosts : host.name => host
  }
  host = "127.0.0.1"
  name = each.value.name
  interfaces {
    ip = each.value.ip
    main = true
  }
  groups = ["Linux servers"]
  templates = [each.value.link_templates]
}