Lesson 2 of 4 ยท Terraform Core Concepts

Variables and validation

Variable types and validation rules make a configuration safer to reuse. A good variable describes the shape of an input and rejects values that would make the infrastructure unclear or invalid before a cloud provider is contacted.

Example

variable "environment" {
  type = string

  validation {
    condition     = contains(["dev", "test", "prod"], var.environment)
    error_message = "Use dev, test, or prod."
  }
}

Step by step

  1. Choose a type that matches the input.
  2. Use a descriptive variable name.
  3. Validate only meaningful constraints.
  4. Explain how to correct a rejected value.

Common mistakes to avoid

  • Using string variables for every value.
  • Writing an error message that does not tell the learner what is accepted.