I do have this vms variable (cannot change this):
variable vms {
description = "Individual VM settings, like ip address and master/worker"
type = map(any)
default = null
}
I want to fill it with values from other (list)variables with ipaddresses and a calculated master = true/false.
I want to create the following map:
vms = {
m1 = {
ip_address = "172.16.201.1"
master = true
w1 = {
ip_address = "172.16.201.2"
master = false
How do I create this in Terraform? If this is possible, next to create, how do I add a m3 for example to the just created map?
Thanks!
Instead of declaring your variable as a generic map
:
variable vms {
description = "Individual VM settings, like ip address and master/worker"
type = map(any)
default = null
}
Consider declaring your variable as a map
of objects, as following:
variable "vms" {
description = "Individual VM settings, like ip address and master/worker"
type = map(object({
ip_address = string
master = bool
}))
default = {}
}
This will ensure that you don't declare variables with invalid properties (e.g. foo
) or values (e.g. master = 123456
).
You can then set your variable as follows:
vms = {
"m1" = {
ip_address = "172.16.201.1"
master = true
}
"w1" = {
ip_address = "172.16.201.2"
master = false
}
"m3" = {
ip_address = "172.16.201.3"
master = false
}
}
Full working example:
# main.tf
variable "vms" {
description = "Individual VM settings, like ip address and master/worker"
type = map(object({
ip_address = string
master = bool
}))
default = {
"m1" = {
ip_address = "172.16.201.1"
master = true
}
"w1" = {
ip_address = "172.16.201.2"
master = false
}
"m3" = {
ip_address = "172.16.201.3"
master = false
}
}
}
output "m1" {
value = var.vms["m1"]
description = "m1 VM settings"
}
output "w1" {
value = var.vms["w1"]
description = "w1 VM settings"
}
output "m3" {
value = var.vms["m3"]
description = "m3 VM settings"
}
Running terraform plan
:
Changes to Outputs:
+ m1 = {
+ ip_address = "172.16.201.1"
+ master = true
}
+ m3 = {
+ ip_address = "172.16.201.3"
+ master = false
}
+ w1 = {
+ ip_address = "172.16.201.2"
+ master = false
}