I want to create a map like this:
variable "test" {
type = map(any)
default = {
param1 = "sdfsdf",
param2 = "sdfsfd",
param3 = {
mylist = [
"aaaaa",
"bbbbb",
"ccccc"
]
}
I get this error:
This default value is not compatible with the variable's type constraint: all
map elements must have the same type.
Does that mean I haven defined the var right or Terraform just doesn't allow this?
What you've encountered here is the difference in the Terraform language between collection types and structural types.
"Map" is a collection type kind, and a map value is any number of elements each identified by an arbitrary string but all values of the same type.
In your case it sounds like you want to declare that you need a set of specific attributes, each of which has its own type constraint. Fixed structures with an individual type for each element are represented by structural types, and "object" is the structural type kind that is most similar to a map.
The following is an object type constraint that would accept the example value you included in your question:
variable "test" {
type = object({
param1 = string
param2 = string
param3 = object({
mylist = list(string)
})
})
}
If you want to allow the caller to set an arbitrary number of keys in param3 and they will all be lists of strings then you could instead set that one to be a map of lists of strings:
variable "test" {
type = object({
param1 = string
param2 = string
param3 = map(list(string))
})
}
In most cases the module will expect a particular data type and would fail if the given value is not of that type, in which case it's helpful to write out that type in full to give guidance to the person calling the module and allow Terraform to validate the value. However, in some cases you really do want to just accept any arbitrary value -- for example, if you intend to just JSON encode the value and send it verbatim to the argument of a resource -- and so in that case you can set the type constraint to any, which will accept any type of value at all:
variable "test" {
type = any
}
In this case, Terraform will not check the incoming value at all, and so your module shouldn't make any assumptions about its type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With