How to correctly use each.value in for_each in terraform?

二次信任 提交于 2021-01-05 07:23:44

问题


I am trying to create a files for each user with the projects assigned to them as content of the file. I amunable to get the "${each.value}" as it is a list of strings. Any way around this please?

locals {
  data = {
    "project1" = {
      user_assigned           = ["user1", "user2", "user3"]
     }
    "project2" = {
      user_assigned           = ["user2", "user3", "user4"]
     }
  }


`
resource "local_file" "foo" {
  for_each = transpose(zipmap(keys(local.data), values(local.data)[*].user_assigned))
  content  = "${each.value}"
  filename = "${each.key}"
}

Error:

  on test.tf line 85, in resource "local_file" "foo":
  85:   content  = "${each.value}"
    |----------------
    | each.value is list of string with 2 elements

回答1:


The content must be string, but in your case it is a list, e.g. ["project1", "project2"]. One way to convert it to string is through jsonencode:

resource "local_file" "foo" {
  for_each = transpose(zipmap(keys(local.data), values(local.data)[*].user_assigned))
  content  = jsonencode(each.value)
  filename = each.key
}


来源:https://stackoverflow.com/questions/65556325/how-to-correctly-use-each-value-in-for-each-in-terraform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!