简体   繁体   中英

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.

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.

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:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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