Dynamic map with multiple values

Is it possible to have multiple values in map? I have this dynamic map but I don’t how to call it.

variable “MWName” {

type = map

default = {

    dev = {"itops-dv", "dev-reboot"}

    uat = {"itops-ut", "uat-reboot"}


}

}

variable “environment” {

type = string

}

output “MWName” {

value = "Location is ${var.environment} and the maintenance window name is ${lookup(var.MWName(0), "${var.environment}")}"

}

It’s not 100% clear to me what you are trying to do, and the formatting of your post appears broken.

However, taking just this part:

default = {
    dev = {"itops-dv", "dev-reboot"}
    uat = {"itops-ut", "uat-reboot"}
}

The above is not valid. {} indicate maps or objects and therefore should have name-value pairs within, which you do at the top level. But the values you are assigning to dev and uat are within {} but are not valid objects or maps, and appear to be lists.
Lists (or sets) are indicated by the use of [].
Therefore, to rewrite the above as a map of lists it would be:

default = {
    dev = ["itops-dv", "dev-reboot"]
    uat = ["itops-ut", "uat-reboot"]
}

Once you have that in place then you can address the values as:
MWName["key"][index]

Below is a code snippet you should be able to drop into an empty directory in a main.tf file and play with. Using terraform plan/apply to get the outputs.

variable "MWName" {
  type = map(any)
  default = {
    dev = ["itops-dv", "dev-reboot"]
    uat = ["itops-ut", "uat-reboot"]
  }
}


output "MWName" {
  value = var.MWName
}
output "MWName_dev" {
  value = var.MWName["dev"]
}
output "MWName_dev_0" {
  value = var.MWName["dev"][0]
}
output "MWName_dev_1" {
  value = var.MWName["dev"][1]
}

Another point of note is the type for the input variable. As you can see above, I have set the type to map(any), which works in this case, but is generally bad practice. See :Type Constraints - Configuration Language | Terraform | HashiCorp Developer

As stated in the documentation:

Warning: any is very rarely the correct type constraint to use. Do not use any just to avoid specifying a type constraint . Always write an exact type constraint unless you are truly handling dynamic data.

So in this case, if the input is not going to be dynamic (as it pertains to the types) and will always be a map containing lists of strings, then this would be better expressed as:

variable "MWName" {
  type = map(list(string))
)
...

Hope that helps!

Happy Terraforming

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.