So we take a variable such as var.node_name and allow the users to input as many node names to build out the vms using for_each. But now we have to add availability zones as an option, the regions we work in azure allow 1,2,3. We need to find a way to assign one zone per vm and if they create more than 3 vms to cycle through the numbers, if that makes sense.
variable "node_name" {}
variable "av_zones" {}
locals {
name = split(",", var.node_name)
}
module "winvm_module" {
for_each = toset(local.name)
source = "../modules/winvm_module"
node_name = each.key
av_zones = var.av_zones
}
I found this article “Using some loop with count and for_each. Availability zones and server count” that looks like I could use range maybe.
locals {
# (I renamed the zones to letters so that they'd
# be more distinct from the instance indices.)
zones = ["a", "b", "c"]
instance_idxs = range(var.itemcount)
instances = flatten([
for z in local.zones : [
for i in local.instance_idxs : {
zone = z
index = i
}
]
])
}
In the example here is there a way to get the range in var.node_names?
So I tried the for expression in the for_each loop with
instances = flatten([
for n in local.name : [
for z in local.av_zones : {
name = n
zone = z
}
]
])
output "instances" {
value = [ for n in local.instances : n ]
}
Though the output I’m getting is
instances = [
+ {
+ name = “Server01”
+ zone = 1
},
+ {
+ name = “Server01”
+ zone = 2
},
+ {
+ name = “Server01”
+ zone = 3
},
+ {
+ name = “Server02”
+ zone = 1
},
+ {
+ name = “Server02”
+ zone = 2
},
+ {
+ name = “Server02”
+ zone = 3
},
I guess what I really want is what I could get out of count with zones if I did something like this in the module.
zone = element(var.av_zones, (count.index))
However I want to try to use for_each so I’ll keep trying and post anything if I find an answer.
I ran into some luck and found a way to get this done.
instance = {for i, server_name in local.name : server_name => {
node_name = server_name
zone = element(var.av_zones, i)
}
}
Then
module “winvm_module” {
for_each = local.instance
source = “…/modules/winvm_module”
node_name = each.value.node_name
av_zones = [each.value.zone]
}
Hope this helps someone out trying to do the same or similar.
Source - https://stackoverflow.com/questions/62862887/terraform-looping-with-for-each