Reputation: 11
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.
Upvotes: 1
Views: 3601
Reputation: 16805
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
}
Upvotes: 1