skwierczyk1
skwierczyk1

Reputation: 63

For_each loop with for expression based on value in map

Since the title is not descriptive enough let me introduce my problem. I'm creating DRY module code for CDN that contains profile/endpoint/custom_domain. Variable cdn_config would hold all necessary/optional parameters and these are created based on the for_each loop.

Variable looks like this:

variable "cdn_config" {
  profiles = {
    "profile_1" = {}
 }
 
 endpoints = {
    "endpoint_1" = {
       custom_domain = {
    }
  }
 }
}

Core of this module is working - in the means that it would create cdn_profile "profile_1" then cdn_endpoint "endpoint_1" will be created and assigned to this profile then cdn_custom_domain will be created and assigned to "endpoint_1" since it's the part of "endpoint_1" map.

Then I realize, what in case I want to create "cdn_custom_domain" only and specify resource ID manually?

I was thinking that adding the optional parameter "standalone" could help, so it would look like this:

variable "cdn_config" {
  profiles = {
    "profile_1" = {}
 }

 endpoints = {
    "endpoint_1" = {
       custom_domain = {
    }
  }
    "endpoint_standalone" = {
       custom_domain = {
         standalone = true
         cdn_endpoint_id = "xxxxx"
   }
  } 
 }
}

Having this "standalone" parameter eq true "endpoint_standalone" map should be totally ignored from looping in the azurerm_cdn_endpoint resource creation.

So far this direction is my only guess, clearly, it's not working - if I add "endpoint_standalone" it complains that not all required parameters are specified so it's surely finding it.

resource "azurerm_cdn_endpoint" "this" {

for_each = {for k in keys(var.cdn_config.endpoints) : k => var.cdn_config.endpoints[k] if lookup(var.cdn_config.endpoints[k],"standalone",null) != "true"}

I would be grateful if you have a solution for this problem.

Upvotes: 2

Views: 3292

Answers (1)

Matthew Schuchard
Matthew Schuchard

Reputation: 28774

You are comparing a bool type to a string type, so the logical comparison will always return false:

for_each = {for k in keys(var.cdn_config.endpoints) : k => var.cdn_config.endpoints[k] if lookup(var.cdn_config.endpoints[k],"standalone",null) != true }

While we are here, we can also improve this for expression:

for_each = { for endpoint, params in var.cdn_config.endpoints : endpoint => params if lookup(params.custom_domain, "standalone", null) != true }

Upvotes: 2

Related Questions