Create validation for map(string)

Hello!

I am new to terraform and trying to figure out how we can create a validation on a variable where type is map(string) and we do not know the key names in advance.

Suppose we have a variable definition like:
variable "myvar" { type = map(string) default = {}
And suppose we define it like this in main.tf:
myvar = {"key1" : "val1", "key2":"val2"}
Now, I want to create a validation to check that the key always contains a string “key”.

How can I do it? Is it possible? I can’t find any relevant documentation.

NOTE: I am using this var in a “for_each” which only supports maps and sets of strings e.g.
resource "myresource" "map" { for_each = var.myvar a = each.key b = each.value

This might be a starting point:

variable "mymap" {
  type = map(string)

  validation {
    condition = alltrue(
       [for obj in keys(var.mymap) : can(regex("^key.*",obj))]
    )
    error_message = "Each map key should include key string."
  }

  #default = {"key1" = "val1"}
  default = {"key1" = "val1", "key2" = "val2"}
  #default = {"okey1" = "val1", "key2" = "val2"}
  #default = {"ok1" = "val1", "key2" = "val2"}
}

Thanks heaps! Do you have any links to relevant documentation which explains this behaviour? Eg. Why are you using “alltrue”? And what structure can contains have? I’m finding it a little hard to find the documentation.

I’m using the terraform functions documentation. However the key is combining different functions properly. Therefore I’m following this discussion group or watch sometimes in reddit for interesting approaches and certainly ask when help is needed.

Awesome, Thankyou heaps :slight_smile:

Cheers,
Steve

Please excuse any typos!

| tbugfinder
January 18 |

  • | - |

I’m using the terraform functions documentation. However the key is combining different functions properly. Therefore I’m following this discussion group or watch sometimes in reddit for interesting approaches and certainly ask when help is needed.