Apply validation in your IaC templates with Terraform and Azure Bicep

Apply validation in your IaC templates with Terraform and Azure Bicep

When writing Terraform Modules that you intend to share with your team or customers so they can consume them and create infrastructure it is common that you will write some base code and accept some input variables.

Input variables let you customize the modules to make the deployment fit the use-case deploying it.

A helpful way to ensure everything works correctly is to build in some validation for the input variables that require it to ensure your module deployments are successful. This is helpful if you have some type constraints or other rule you wish the consumer to follow when deploying your module.

This can be achieved with both Terraform and Azure Bicep.

Azure Bicep

@allowed([
  'swedencentral'
  'westeurope'
])
param location string

The following ensures users cannot deploy a template into a location that is not allowed. Assume we have a policy that only allows the above locations, we can further enforce this in our template using the @allowed keyword.

You can also go further and really help the user of the template understand by supplying them with important information before they try and deploy since that is a nice thing of you to do to save them time:

@description('''
Storage account name restrictions:
- Storage account names must be between 3 and 24 characters in length and may contain numbers and lowercase letters only.
- Your storage account name must be unique within Azure. No two storage accounts can have the same name.
''')
@minLength(3)
@maxLength(24)
param storageAccountName string

We can also set integer constraints like this:

@minValue(1)
@maxValue(12)
param month int

Terraform

We can do the same things here, as an example we may define a location variable as such:

variable "location" {
  type = string
  validation {
    condition     = contains(["swedencentral", "westeurope"], var.location)
    error_message = "Location must be either swedencentral or westeurope"
  }

}

resource "azurerm_resource_group" "this" {
  name     = "rg-prod-sc-validation"
  location = var.location
}

And if I supply westus in my deployment Terraform will throw an error:

Reference

Parameters in Bicep files - Azure Resource Manager
Describes how to define parameters in a Bicep file.

About me

About me
If you have landed on my page you will have already understood my passion for tech, but obviously there is more to life than that. Here I will try and outline a few of my other hobbies. Strength training I am a person who loves to move around and challenge