Validating Map Variables

Greetings.

I think I’m looking at something that can’t yet be done, but I have, at times had challenges interpreting the documentation so i figured I’d check the community.

I have a map variable that is expecting one of two maps that contain keys with lists of strings as values.

IE:

{
   a: ["1","k","foo"]
   b: ["2"]
}

I have a bool that is set that tells me which of these two maps it should expect and two local lists containing the valid keys:

What I want to do is have the validation look at the map, and verify the 1) the key is available in the list and 2) verify the value is a list of strings

I’m looking for something that I think would look like this

locals {
  lista = [ "a", "b", "c" ]
  listb = ["b","c","d" ]

  maplabels = {
   lista = "list A"
   listb = "list B"
}

variable "uselista" {
  default=true
 description = "use lista or listb"
}

variable "mymap" {
  # Should take care of test #2.
  type = map(list(sting))

  dynamic {
    for_each = var.mymap
    content {
        validation {
           condition = can(index( var.uselista ? local.lista : local.listb,each.key) )
           error = "${each.key} is not valid key for map type ${local.maplabels[ var.uselista ? "lista":"listb"]}. Verify var.uselista is correct."
        }
      }
   }
}

Is there anything roughly like this, or an active feature request to +1 here? Thanks.

You’re right that this isn’t possible at the moment. Variable validation blocks can only refer to the variable being validated, not other variables. It’s also not possible to use functions inside the error message.

Here are the existing feature requests to :+1: for those two issues:

If you haven’t seen it, you may find the recently-added alltrue function helpful for validating list membership. This won’t allow a custom error message, nor can you use an input variable as the list, but maybe you can still make use of it!