Help with transforming two vars with local (tf 0.12.8)

I have two vars:
map(list(string))

tree = {
  core = ["fks", "nkz", "fksb"]
  leaf = ["bar", "real]
}

map(string)

env_branch = {
  development = "dev"
  production = "prod"
}

The result should look like this:

acc_branch = {
  fks = "master"
  nkz = "master"
  fksb = "master"
  bar = "dev"
  real = "dev"
}

In my locals I would like to do something like this:

locals {
    acc_branch_pairs = flatten([
        for acc in values(var.tree): {
          if acc == var.tree["core"]
              acc = acc
              branch = var.env_branch["production"]
          else
              acc = acc
              branch = var.env_branch["development"]
        }
    ])
}

Not sure how to proceed with IF-ELSE statements when using for loops in tf. Any suggestion would be appreciated.

Hi @legokid,

In Terraform, conditionals are represented using the conditional operator because Terraform is expression-based, not statement-based.

For example,

locals {
  acc_branch_pairs = flatten([
    for acc in values(var.tree) : {
      acc    = acc
      branch = var.env_branch[
        acc == var.tree["core"] ?
        "production" :
        "development"
      ]
    }
  ])
}

I didn’t quite follow what you were trying to do with those input variables and so I expect the above isn’t exactly what you wanted, but hopefully the conditional syntax example is enough to help you figure out the rest of the story.

1 Like