Home > Mobile >  Conditional update of key values in a terraform variable
Conditional update of key values in a terraform variable

Time:03-18

I am trying to create a variable by loading in data from some JSON files. I have the below code which looks like it should work, but I bump into a strange error on the conditional line. example.json

{
  "title": "Group",
  "description": "",
  "tags": [
    "test1:test1",
    "type:test2"
  ]
}

main.tf

locals {
  default_tags = ["testtag:test value"]
  my_path = "${path.module}/environments/${var.environment}/json/"
  temp_config = flatten([
    for my_file in fileset("${local.my_path}", "*.json") : [
      for k, v in jsondecode(file("${local.my_path}/${my_file}")) : {
        key = k
        value = k == "tags" ? concat(v, local.default_tags): v
      }
    ]
  ])
}

output "output" {
  value = local.temp_config
}

my error:

Error: Inconsistent conditional result types
│
│   on mytest.tf line 8, in locals:
│    8:         value = k == "tags" ? concat(v, local.default_tags): v
│     ├────────────────
│     │ local.default_tags is tuple with 1 element
│
│ The true and false result expressions must have consistent types. The given expressions are tuple and tuple, respectively.

This error is pretty confusing. Has anyone has a similar issue?

CodePudding user response:

It seems like in this context Terraform's type inference is not successfully finding an automatic solution to how to make the true and false arms of the conditional have the same type.

In situations like this, Terraform can often give better error messages (or, in an ideal world, select a working solution directly) if you add more information about your intent. In this case, it seems like your intent is for this value attribute to be a list of strings, and so one extra hint you could give Terraform is to explicitly mark both sides of the conditional as being lists using the tolist function:

        value = k == "tags" ? tolist(concat(v, local.default_tags)) : tolist(v)

With these extra tolist calls, Terraform should either correctly understand that you intend to produce a list of strings in both cases, or should return an error explaining why it's possible to treat one or both of those expressions as a list of strings.

  • Related