Howard_Roark
Howard_Roark

Reputation: 4326

Referencing Element Of List In Terraform Templated Yaml File

I am trying to pass a map of lists to a templated yaml file and then reference a specific element of that list. I know that this leverages the legacy template_file type, but I am still curious as to why what I am doing does not render. The same logic works fine when I test it via locals.

variable:

variable "my_recipients" {
  description = "Recipients To Identify"
  type        = map(list(string))
  default = {
    abcd = [
      "myrecipientA"
    ],
    zyx = [
      "myrecipientB"
    ]
  }
}

template_file snippet:

data "template_file" "policies" {
  template = myfile.yaml
    recipients_all                    = jsonencode(var.my_recipients)
}

yaml file snippet:

to:
  - ${jsondecode({recipients_all})["zyx"]} #Goal is to get the value myrecipientB

I expect to get the value myrecipientB, but instead I get the error:

Missing key/value separator; Expected an equals sign ("=") to mark the beginning of the attribute value.

Any advice would be appreciated as this seems like a simple idea that should work, and I'm not sure what I am misunderstanding.

Upvotes: 0

Views: 1684

Answers (1)

Byob
Byob

Reputation: 625

I believe the issue might be with how things are defined and passed from terraform to the template. There seemed to be some minor syntax errors on the template itself. Plus, the template file wants the results of the interpolation to be a string so it can be included on the rendered results.

Here's the code that worked for me.

combined terraform code:

variable "my_recipients" {
  description = "Recipients To Identify"
  type        = map(list(string))
  default = {
    abcd = [
      "myrecipientA"
    ],
    zyx = [
      "myrecipientB"
    ]
  }
}

data "template_file" "policies" {
  template = file("myfile.tpl")
  vars = {
    recipients_all                    = jsonencode(var.my_recipients)
  }
}

# For debugging purposes
locals {
    recepients_all_encoded = jsonencode(var.my_recipients)
}

output "recepients_all_encoded" {
    value = local.recepients_all_encoded
}

output "template_content" {
    value = data.template_file.policies.rendered
}

updated template file (myfile.tpl)

to:
  - ${jsondecode(recipients_all)["zyx"][0]}

Results from terraform run

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

recepients_all_encoded = "{\"abcd\":[\"myrecipientA\"],\"zyx\":[\"myrecipientB\"]}"
template_content = <<EOT
to:
  - myrecipientB

EOT

Upvotes: 3

Related Questions