DEV Community

John  Ajera
John Ajera

Posted on

Terraform Validation Rules: Best Practices & Examples

Terraform Validation Rules: Best Practices & Examples

Validation rules in Terraform ensure that variables and inputs meet expected conditions. Here are some common validation patterns with examples.


Table of Contents

  1. String Length Validation
  2. Regex Validation for Email Format
  3. Number Range Validation
  4. Allowed Values (Whitelist)
  5. Disallowed Values (Blacklist)
  6. List Element Validation
  7. Map Key Validation
  8. CIDR Block Validation
  9. Custom Combination Validation
  10. Validation for List Length
  11. String Prefix Validation
  12. Port Number Range Validation
  13. Environment Whitelist Validation
  14. Minimum Resource Count Validation
  15. Disallowed Subnet IP Validation
  16. Map Key Constraint Validation

1. String Length Validation

Ensure that a string variable has a minimum and maximum length.

variable "project_name" {
  type        = string
  description = "Project name for the deployment"
  default     = "project1"
  validation {
    condition     = length(var.project_name) >= 3 && length(var.project_name) <= 10
    error_message = "Project name must be between 3 and 10 characters."
  }
}
Enter fullscreen mode Exit fullscreen mode

2. Regex Validation for Email Format

Validate that a string follows an email format.

variable "admin_email" {
  type        = string
  description = "Administrator email address"
  default     = myemail@domain.com

  validation {
    condition     = can(regex("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$", var.admin_email))
    error_message = "Please provide a valid email address."
  }
}
Enter fullscreen mode Exit fullscreen mode

3. Number Range Validation

Ensure a numeric variable falls within a specified range.

variable "instance_count" {
  type        = number
  description = "Number of instances to create"
  default     = 1

  validation {
    condition     = var.instance_count >= 1 && var.instance_count <= 5
    error_message = "Instance count must be between 1 and 5."
  }
}
Enter fullscreen mode Exit fullscreen mode

4. Allowed Values (Whitelist)

Ensure a variable matches one of the allowed values.

variable "region" {
  type        = string
  description = "AWS deployment region"
  default     = "ap-southeast-2"

  validation {
    condition     = contains(["ap-southeast-1", "ap-southeast-2"], var.region)
    error_message = "Region must be one of ap-southeast-1 or ap-southeast-2."
  }
}
Enter fullscreen mode Exit fullscreen mode

5. Disallowed Values (Blacklist)

Ensure a variable does not match specific disallowed values.

variable "restricted_user" {
  type        = string
  description = "Username for system access"
  default     = "user1"

  validation {
    condition     = !contains(["admin", "root", "superuser"], var.restricted_user)
    error_message = "The username cannot be admin, root, or superuser."
  }
}
Enter fullscreen mode Exit fullscreen mode

6. List Element Validation

Ensure all elements in a list follow a specific format.

variable "allowed_ips" {
  type        = list(string)
  description = "List of allowed IP addresses"
  default     = ["10.1.1.1"]

  validation {
    condition     = alltrue([for ip in var.allowed_ips : can(regex("^\\d{1,3}(\\.\\d{1,3}){3}$", ip))])
    error_message = "Each IP address must be a valid IPv4 format."
  }
}
Enter fullscreen mode Exit fullscreen mode

7. Map Key Validation

Ensure specific keys exist in a map.

variable "environment_settings" {
  type = map(string)
  description = "Environment-specific settings"
  default = {
    "env"    = "production"
    "app"    = "web-app"
    "region" = "ap-southeast-2"
  }

  validation {
    condition     = alltrue([for key in ["env", "app", "region"] : contains(keys(var.environment_settings), key)])
    error_message = "The map must include keys: env, app, and region."
  }
}
Enter fullscreen mode Exit fullscreen mode

8. CIDR Block Validation

Validate that a CIDR block follows the correct pattern.

variable "vpc_cidr_block" {
  type        = string
  description = "CIDR block for the VPC"
  default     = "10.0.0.0/16"

  validation {
    condition     = can(regex("^\\d{1,3}(\\.\\d{1,3}){3}/\\d{1,2}$", var.vpc_cidr_block))
    error_message = "CIDR block must be in the correct format (e.g., 10.0.0.0/16)."
  }
}
Enter fullscreen mode Exit fullscreen mode

9. Custom Combination Validation

Ensure multiple variables follow related rules.

variable "disk_size" {
  type        = number
  description = "Size of the disk in GB"
  default     = 101
}

variable "disk_type" {
  type        = string
  description = "Type of disk storage"
  default     = "premium"

  validation {
    condition     = !(var.disk_type == "premium" && var.disk_size < 100)
    error_message = "Premium disks must be at least 100 GB."
  }
}
Enter fullscreen mode Exit fullscreen mode

10. Validation for List Length

Ensure the list has at least two elements.

variable "backup_servers" {
  type        = list(string)
  description = "List of backup servers"
  default     = ["bkpserver1", "bkpserver2"]

  validation {
    condition     = length(var.backup_servers) >= 2
    error_message = "At least two backup servers must be specified."
  }
}
Enter fullscreen mode Exit fullscreen mode

11. String Prefix Validation

Ensure a string starts with a specific prefix.

variable "resource_name" {
  type = string
  description = "Name of the resource"
  default = "prod-vm"

  validation {
    condition     = startswith(var.resource_name, "prod-")
    error_message = "Resource name must start with 'prod-'."
  }
}
Enter fullscreen mode Exit fullscreen mode

12. Port Number Range Validation

Ensure port numbers are within a valid range.

variable "http_port" {
  type        = number
  description = "Port for HTTP traffic"
  default     = 8080

  validation {
    condition     = var.http_port >= 1024 && var.http_port <= 65535
    error_message = "Port must be between 1024 and 65535."
  }
}
Enter fullscreen mode Exit fullscreen mode

13. Environment Whitelist Validation

Ensure deployment environment matches allowed values.

variable "deploy_env" {
  type = string
  description = "Deployment environment"
  default = "dev"

  validation {
    condition     = contains(["dev", "stage", "prod"], var.deploy_env)
    error_message = "Environment must be one of: dev, stage, prod."
  }
}
Enter fullscreen mode Exit fullscreen mode

14. Minimum Resource Count Validation

Ensure a resource count is above the minimum.

variable "node_count" {
  type        = number
  description = "Number of nodes to deploy"
  default     = 3

  validation {
    condition     = var.node_count >= 3
    error_message = "At least three nodes must be deployed."
  }
}
Enter fullscreen mode Exit fullscreen mode

15. Disallowed Subnet IP Validation

Ensure a subnet IP isn't from a restricted list.

variable "subnet_ip" {
  type        = string
  description = "Subnet IP address"
  default     = "10.0.1.0/24"

  validation {
    condition     = !contains(["192.168.1.0/24", "10.0.0.0/16"], var.subnet_ip)
    error_message = "Subnet IP cannot be from restricted ranges."
  }
}
Enter fullscreen mode Exit fullscreen mode

16. Map Key Constraint Validation

Ensure specific keys exist in a configuration map.

variable "app_config" {
  type        = map(string)
  description = "Application configuration map"
  default = {
    "name"       = "my_app"
    "version"    = "1.0.0"
    "owner"      = "team@myapp.com"
    "deployment" = "production"
    "region"     = "us-west-2"
  }

  validation {
    condition     = alltrue([for key in ["name", "version", "owner"] : contains(keys(var.app_config), key)])
    error_message = "The app configuration must include keys: name, version, and owner."
  }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Terraform's validation rules provide a robust way to enforce best practices, prevent misconfigurations, and simplify debugging. Use these
examples as a reference for implementing secure, reliable infrastructure deployments.

Let me know if you'd like additional validation patterns! 🚀

Top comments (0)