Quantcast
Channel: Terraform - HashiCorp Discuss
Viewing all articles
Browse latest Browse all 11429

Conditionally create resources when a for_each loop is applied

$
0
0

Hello,

I have a problem, as show in the title when I use this inside a dynamic block it works:

dynamic "frontend_ip_configuration" {
    for_each = length(keys(var.frontend_conf_private)) > 0 ? [1] : []

    content {
    ...
    }
}

But, if I use the same strategy in a resource, by example:

resource "azurerm_firewall_policy" "firewall_policy_child" {
  for_each = var.type == "child" ? [1] : []
 
  name                = var.name
  resource_group_name = var.resource_group_name
  location            = var.location
}

I received this error:

Error: Invalid for_each argument
│ 
│   on modules\firewall_policy\firewall_policy.tf line 27, in resource "azurerm_firewall_policy" "firewall_policy_child":
│   27:   for_each = var.type == "child" ? [1] : []
│     ├────────────────
│     │ var.type is a string
│
│ The given "for_each" argument value is unsuitable: the "for_each" argument must be a map, or set of strings, and you have provided a value of type list of string.
╵

As I see in the documentation, for_each read only maps and sets, if I use the function toset() in the resource I solved the problem but my doubt is, why it works in dynamic and not in resource?

I’m using terraform:

$ terraform --version
Terraform v1.7.4
on windows_amd64

2 posts - 2 participants

Read full topic


Viewing all articles
Browse latest Browse all 11429

Trending Articles