Custom variable validation, a practical example

Custom variable validation is my new go-to killer feature. Introduced as a language experiment in late 0.12, from Terraform 0.13 it is now production-ready! This enables us to write a definition of what we want our input variables to, and give send out a proper warning.

At first, you might ask why bother? If the user inputs something that can’t be deployed, wouldn’t Terraform fail? Sure, but for a failure to happen we actually have to run the code, use the provider to get the error back. This takes time, or even worse it might actually try to deploy and time out, which takes even more time.

Creating Azure Storage Account

One example that comes to mind is deploying Azure storage accounts. When deploying storage accounts, there are some rules for what you can name it. Its name must be unique, be between 3 and 24 characters in length, and may only contain lowercase letters and numbers. The first one, Azure will have to check for us but the others are pretty static.

Here is my example, which also can be found in my Azure examples git-repository.

variable "storage_account_name" {
  type    = string
  validation {
    condition     = (
                    length(var.storage_account_name) > 2 && 
                    length(var.storage_account_name) < 25 && 
                    can(regex("[a-z.*]|[0-9]", var.storage_account_name))
                    )
    error_message = "Storage account names must be between 3 and 24 characters in length and may contain numbers and lowercase letters only."
  }
}

Note, we are using the && chain operator to build our conditions. In this case, it means that it will run the next line, only if the last one didn’t fail. In plain English, you would read this as;

If the length of the string is greater than 2, and the length of the string is less than 25, and the string only has lowercase letters and numbers, return true.

If anyone of the tests fails, return the error message you have defined.

In my tests, the error is returned in around 0.7 seconds. This is compared to 5, 6, and even 7 seconds when trying to deploy and getting the error back from Azure.

https://robstr.dev/images/posts/307-measure-command.png

Roberth Strand's Picture

About Roberth Strand

Cloud consultant working primarily with Microsoft Azure, automation and infrastructure.

Tromsø, Norway https://robstr.dev

Comments