Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading