Struggling with for_each conditional expression

Hi,

I am trying to use for_each with a condition and struggling to make this work.

I have a YAML file that looks like this:

applications:
  application1:
    name:               "App1"
    standardapp:  true
  application2:
    name:               "App2"
    standardapp:  false
  application3:
    name:               "App3"
    standardapp:  true

I then bring that into Terraform via a locals variable:

locals {
  yaml_apps = yamldecode(file("${path.root}/config/applications_config.yaml"))
}

Now I want to create a policy but only if standardapps = true but I am struggling with the for_each expression for this. The closest I have gotten is:

resource "azurerm_policy_definition" "pol_def" {
  for_each                  = {
    for app, values in local.yaml_apps : app => values
    if values.standardapp == true
  }
 <removed additional attributes for brevity>
}

This brings up the error:

│ Error: Unsupported attribute
│
│   on main.tf line 123, in resource "azurerm_policy_definition" "pol_def":
│  123:     if values.standardapp == true
│
│ Can't access attributes on a primitive-typed value (string).
╵
Operation failed: failed running terraform plan (exit 1)

Can anyone help me to understand what I am doing wrong?

Hi @gary.kirton,

Your example won’t result in quite the same error you’re showing, but the root cause may be the same.

If you look at the yaml source (or print the value to an output or console for inspection) your local.yaml_apps is an object with a single applications attribute. I think you meant to start your for_each expression with:

for app, values in local.yaml_apps.applications