🐶
Terraform

Terraform Input Validation: Restricting to Choices

By Filip on 10/07/2024

Learn how to define input variables in Terraform that accept only specific allowed values, ensuring consistent and validated infrastructure deployments.

Terraform Input Validation: Restricting to Choices

Table of Contents

Introduction

In Terraform, input variables provide flexibility by allowing you to customize deployments. However, without proper validation, these variables can lead to unexpected issues. This guide demonstrates how to restrict input variable values to a predefined set of choices, ensuring consistency and preventing invalid configurations.

Step-by-Step Guide

  1. Enable Variable Validation: Before you can restrict input variables, ensure you have variable validation enabled in your Terraform configuration:

    terraform {
      experiments = [variable_validation]
    }
  2. Define the Variable: Declare your input variable and specify its type. For a list of allowed choices, use the string type:

    variable "environment" {
      type = string
    }
  3. Implement Validation: Within the variable block, add a validation block. This block will contain the logic to enforce the allowed choices:

    validation {
      condition = contains(["dev", "staging", "prod"], var.environment)
      error_message = "Invalid environment. Choose from: dev, staging, prod."
    }
    • We use the contains function to check if the provided value for var.environment exists within the list ["dev", "staging", "prod"].
    • The error_message is displayed if the condition evaluates to false, guiding the user on valid inputs.
  4. Complete Example:

    terraform {
      experiments = [variable_validation]
    }
    
    variable "environment" {
      type = string
      validation {
        condition = contains(["dev", "staging", "prod"], var.environment)
        error_message = "Invalid environment. Choose from: dev, staging, prod."
      }
    }

Now, when you run Terraform, it will verify if the value provided for the environment variable is one of the allowed choices. If not, it will halt execution and display the specified error message.

Code Example

This Terraform code defines a variable named "environment" restricted to "dev", "staging", or "prod" values. It uses variable validation to enforce these choices and provides an example of using this variable when creating an AWS instance.

terraform {
  experiments = [variable_validation]
}

variable "environment" {
  type = string
  description = "Target environment (dev, staging, or prod)"

  validation {
    condition = contains(["dev", "staging", "prod"], var.environment)
    error_message = "Invalid environment. Choose from: dev, staging, prod."
  }
}

# Example usage of the validated variable
resource "aws_instance" "example" {
  ami           = "ami-0c94855a61da8a300" # Replace with your desired AMI
  instance_type = "t2.micro"

  tags = {
    Name = "Example Instance - ${var.environment}"
  }
}

Explanation:

  1. Enable Variable Validation: The terraform { experiments = [variable_validation] } line enables the feature.
  2. Define the Variable: The variable "environment" block declares the variable with type string.
  3. Implement Validation: The validation block enforces the allowed choices ("dev", "staging", "prod") using the contains function. If an invalid value is provided, the error_message is displayed.
  4. Example Usage: The aws_instance resource demonstrates how to use the validated var.environment variable within your Terraform code.

How to Use:

  1. Save the code as a .tf file (e.g., main.tf).
  2. Run terraform init to initialize the working directory.
  3. Try applying the configuration with valid and invalid environment values:
    • Valid: terraform apply -var="environment=dev"
    • Invalid: terraform apply -var="environment=test" (This will fail with the error message).

This example demonstrates how to restrict input variables to a predefined list of choices, ensuring that your Terraform configurations are applied with valid and expected values.

Additional Notes

  • Importance of Variable Validation: Variable validation is crucial for writing robust and reliable Terraform code. It acts as a safety net, preventing misconfigurations from propagating to your infrastructure.
  • Early Error Detection: Validation helps catch errors early in the development cycle, during the terraform plan stage, rather than during deployment, saving time and potential issues.
  • Improved User Experience: Clear error messages within the validation block guide users on providing correct input values, making your Terraform modules more user-friendly.
  • Beyond contains: While this example uses contains, Terraform offers other functions like length, regex, and more for complex validation scenarios.
  • Custom Validation Logic: For advanced use cases, you can write custom validation logic using conditional expressions within the condition block.
  • Variable Validation is Opt-In: Remember that you need to explicitly enable variable validation using experiments = [variable_validation] in your Terraform configuration.
  • Future of Variable Validation: The variable_validation experiment is expected to become a standard feature in future Terraform versions.

By incorporating these notes and the provided code examples, you can leverage variable validation to write cleaner, more maintainable, and error-resistant Terraform code.

Summary

This guide explains how to limit the values users can input for a Terraform variable.

Steps:

  1. Enable Variable Validation: Add the following to your Terraform configuration file:

    terraform {
      experiments = [variable_validation]
    }
  2. Define the Variable: Declare your variable and its type (use string for a list of choices):

    variable "environment" {
      type = string
    }
  3. Implement Validation: Inside the variable block, add a validation block with the logic to enforce allowed choices:

    validation {
      condition = contains(["dev", "staging", "prod"], var.environment)
      error_message = "Invalid environment. Choose from: dev, staging, prod."
    }
    • contains checks if the input value exists in the specified list.
    • error_message guides the user on valid inputs if the condition fails.

Example:

terraform {
  experiments = [variable_validation]
}

variable "environment" {
  type = string
  validation {
    condition = contains(["dev", "staging", "prod"], var.environment)
    error_message = "Invalid environment. Choose from: dev, staging, prod."
  }
}

This configuration ensures that the environment variable can only accept "dev", "staging", or "prod" as values. Any other input will halt execution and display the error message.

Conclusion

By restricting input variable values, you enhance the reliability and predictability of your Terraform deployments. This practice is essential for managing infrastructure at scale and ensuring that your configurations are applied consistently and without errors.

References

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait