Today I Learned: Terraform variable validation

Brendan Thompson • 20 April 2021

As of Terraform 0.13.0 it is now possible to run a level of validation over your input variables to ensure they match what you'd expect them to be. There are some limitations to this, which I wont go into right now. Today I groked how it to deal with more complex validations scenarios.

If you had a module that made a call to a resource where one of it's fields accepted a list() and you wanted to ensure that only a subset of the options that are actually available are allowed to be passed into the module. This can be done using validation, there isn't a clean way to deal with this in the current implementation of validation but the below is something that certainly works.

I have removed the majority of the config for the defined resource as we don't overly care about that. The point we care about most is ensuring that only NFSv3 and NFSv4.1 are allowed to be passed into the module, another option that is allowed is CIFS but we don't want to allow it.

resource "azurerm_netapp_volume" "this" {
  name                = "netapp-volume"


  protocols           = var.protocols

variable "protocols" {
  description = "List of protocols to be enabled for this NetApp volume"
  type        = list(string)

  validation {
    condition = length([
      for p in var.protocols : true
      if contains(["NFSv3", "NFSv4.1"], p)
    ]) == length(var.protocols)
    error_message = "One of more of the passed in protocols is not allowed."

By using the above validation clause you can see it is simple to do this sort of validation using maths.