BudiBadu Logo
Samplebadu

Terraform by Example: Input Validation

1.x

Input validation ensures your variables meet specific criteria. This code example demonstrates using custom validation rules with regex and list checks.

Code

variable "image_id" {
  type        = string
  description = "The id of the machine image (AMI) to use for the server."

  validation {
    condition     = length(var.image_id) > 4 && substr(var.image_id, 0, 4) == "ami-"
    error_message = "The image_id value must be a valid AMI id, starting with "ami-"."
  }
}

variable "environment" {
  type        = string
  description = "Deployment environment"
  
  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "Environment must be one of: dev, staging, prod."
  }
}

Explanation

Input validation is a proactive measure to catch configuration errors early, before any resources are provisioned. By defining custom validation rules within the validation block, you can enforce strict constraints on variable values, ensuring they adhere to organizational standards and security policies.

Each validation block requires a condition argument, which is an expression that must evaluate to true, and an error_message that explains why the input failed. If the condition returns false, Terraform halts execution and displays the error message, preventing invalid data from propagating through your infrastructure.

You can leverage Terraform's built-in functions like length, substr, contains, and regex to build robust validation logic. This is commonly used to enforce naming conventions (e.g., starting with "ami-"), restrict inputs to a specific set of allowed values (e.g., "dev", "prod"), or validate IP address formats.

Code Breakdown

2
type = string defines the expected data type for the variable.
3
description provides context for users and documentation.
5-8
validation block defines the rules for the variable.
6
condition checks if the string starts with "ami-".
7
error_message provides feedback to the user on failure.
16
contains(...) checks if the value is in the allowed list.