Variable data bloc depending on a variable

Hello all,

I’m kind of new to terraform and I was wondering how we can build a map based on a variable. I wonder if this id doable.
Imagine the following scneario:

locals {
  foo = toset( ["value1", "value2"] )
}


data "template_file" "files" {
  for_each = local.foo
  template = file("${path.module}/${each.key}.json")
}

Later, I wanted to use it this way: data.template_file.files[“value1”].rendered
This is an easy example. Because, I would like to use the files in another scenario where the key will be passed as parameter depending on a variable.

Unfortunately, this doesn’t seems to work. So, I was wondering, how can I achieve this? Do I have to create a template_file for as much values that I have in my original list? Can’t this be dynamic?

Any suggestion is welcome.

Regards,

Could you share the terraform error?
There’s also a native templatefile() function in terraform. Maybe it resolves the your error?

locals {
  #foo = toset( ["value1", "value2"] )
  foo = toset( ["file1", "file2"] )
}

data "template_file" "files" {
  for_each = local.foo
  template = file("${path.module}/${each.key}.json")
}

output "files" {
  value = [ for content in data.template_file.files : content.rendered ]
}

output "file1" {
  value = data.template_file.files["file1"].rendered
}

output "functionfiles" {
  value = [ for inputfile in local.foo : templatefile("${inputfile}.json", {}) ]
}

output "functionfilesmap" {
  value = { for inputfile in local.foo : inputfile => templatefile("${inputfile}.json", {}) }
}



## terraform plan
% terraform plan

Changes to Outputs:
  + file1            = jsonencode(
        {
          + contentkey1 = "this is file1"
        }
    )
  + files            = [
      + jsonencode(
            {
              + contentkey1 = "this is file1"
            }
        ),
      + jsonencode(
            {
              + contentkey2 = "this is file2"
            }
        ),
    ]
  + functionfiles    = [
      + jsonencode(
            {
              + contentkey1 = "this is file1"
            }
        ),
      + jsonencode(
            {
              + contentkey2 = "this is file2"
            }
        ),
    ]
  + functionfilesmap = {
      + file1 = jsonencode(
            {
              + contentkey1 = "this is file1"
            }
        )
      + file2 = jsonencode(
            {
              + contentkey2 = "this is file2"
            }
        )
    }

Thank you very much. It’s my mistake. You’re right I should have read the message better :frowning: Sorry for this.