Search code examples
jsonautomationterraformzabbix

Iterate over Json using Terraform


Hi & thank you in advance :)

I have a json file with data that needs to added to Zabbix as hosts.

{
    "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"
        }
    ]
}

I'm not sure how I would go about looping over this file using terraform. I have been able to loop over host name, but not sure how to use this on the remaining fields.

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"]
}

I would like to add "host, ip, groups & templates"

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

Solution

  • You were almost there. Don't point to host.name in locals var. Use directly host as shown below.

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

    Then, you can iterate over hosts list & fetch attributes like below..

    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]
    }