简体   繁体   English

遍历 Terraform object 列表变量并输出字符串值

[英]Iterating through a Terraform object list variable and outputting string value

could use some guidance here.可以在这里使用一些指导。

I have the following list variable that holds two string values (name, short_name) for many US States:我有以下列表变量,其中包含许多美国州的两个字符串值(名称、短名称):

variable "states" {
  type = list(object({
  name = string
  short_name = string
  }))
  description = "State List"
  default = [
  {
    name = "New Jersey"
    short_name = "nj"
  },
  {
    name = "Michigan"
    short_name = "mi"
  ]
  }

I need to iterate through this list and output each index for the "short_name" string into a generic code block in my common.tfvars file.我需要遍历此列表和 output 将“short_name”字符串的每个索引放入我的 common.tfvars 文件中的通用代码块中。

The code block looks something like this and contains only strings:代码块看起来像这样并且只包含字符串:

generic_code_block = [
 "Stateofnj"
 "Stateofmi"
]

I want to adjust this code block so only one line of code needs to be written and it will iterate through the list for the short_name string value.我想调整此代码块,因此只需要编写一行代码,它将遍历 short_name 字符串值的列表。

Is this possible for a generic code block where a resource is not being created?这对于未创建资源的通用代码块是否可行?

I imagine a concept similar to this could work but I'm not exactly sure how to put it together.我想象一个类似于此的概念可以工作,但我不确定如何将它组合在一起。

generic_code_block = [
 "Stateof" + for_each = toSet(var.States.short_name) + "
]

Would appreciate any help thank you.将不胜感激任何帮助谢谢。

This can be accomplished by a simple for loop:这可以通过一个简单for循环来完成:

variable "states" {
  type = list(object({
    name       = string
    short_name = string
  }))
  description = "State List"
  default = [
    {
      name       = "New Jersey"
      short_name = "nj"
    },
    {
      name       = "Michigan"
      short_name = "mi"
    }
  ]
}

locals {
  generic_code_block = [
    for state in var.states: "Stateof${state.short_name}"
  ]
}

You can use the local variable as such:您可以这样使用局部变量:

output "generic_code_block " {
  value = local.generic_code_block
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM