Search code examples
terraformcloudflare

Multiple zone ids from cloudflare_zones in terraform


So i have a terraform variable type list(string) that is called zones and contains

zones = [
  "example.com",
  "example2.com",
  "example3.com",
  ...
]

and i m using data cloudflare_zones resource to fetch all zones info

data "cloudflare_zones" "zones" {
  for_each = toset(var.zones)
  filter {
    name = each.value
  }
}

Output for each of the zones

data.cloudflare_zones.zones["example.com"]
{
  "filter" = tolist([
    {
      "account_id" = ""
      "lookup_type" = "exact"
      "match" = ""
      "name" = "example.com"
      "paused" = false
      "status" = ""
    },
  ])
  "id" = "9f7xxx3xxxx"
  "zones" = tolist([
    {
      "id" = "e13xxxx"
      "name" = "example.com"
    },
  ])
}

To fetch the zone id you need to parse data.cloudflare_zones as below:

data.cloudflare_zones.zones["example.com"].zones[0].id

What i want to create then is a variable that will be an object with all the zones names as keys and zone ids ad values, so i can use them in other resources.
For Example:

zones_ids = 
{
  "example.com" = "xxxzone_idxxx",
  "example2.com" = "xxxzone_id2xxx",
  "example3.com" = "xxxzone_id3xxx",
  ...
}

I would like to achieve this inside locals block

locals {
... 
}

Solution

  • That should be easy:

    locals {
      zones_ids = { for k,v in data.cloudflare_zones.zones: k => v.zones[0].id }
    }
    

    Or alternatively:

    locals {
      zones_ids = { for k,v in data.cloudflare_zones.zones: v.zones[0].name => v.zones[0].id }
    }