Understand how to create flexible, reusable Terraform configurations using input variables, type constraints, and validation rules.

What Will You Learn? #

Variables let you parameterize Terraform configurations so they can be used across different environments without changing code. This section covers variable declaration, the type system, validation, and the various ways to pass variable values.

Articles in This Section #

ArticleMain Topic
What is a Variable?The concept of input variables and their role in configurations
Type & ValidationType constraints (string, number, list, map, object) and custom validation
File & EnvironmentPassing values via .tfvars, environment variables, and CLI flags

Variable Priority #

flowchart TD
    A["1. -var flag<br/>terraform apply -var='name=value'"] --> B["2. .tfvars file<br/>terraform.tfvars"]
    B --> C["3. .auto.tfvars<br/>*.auto.tfvars"]
    C --> D["4. TF_VAR_ env var<br/>export TF_VAR_name=value"]
    D --> E["5. Default value<br/>default = 'value'"]
    E --> F["6. Interactive prompt<br/>Terraform asks"]

    style A fill:#ffcdd2
    style B fill:#ffe0b2
    style C fill:#fff9c4
    style D fill:#c8e6c9
    style E fill:#b3e5fc
    style F fill:#e1bee7

Type System #

flowchart LR
    subgraph Primitive
        S["string<br/>'hello'"]
        N["number<br/>42, 3.14"]
        B["bool<br/>true, false"]
    end

    subgraph Collection
        L["list(string)<br/>['a', 'b', 'c']"]
        M["map(number)<br/>{a=1, b=2}"]
        S2["set(string)<br/>['a', 'b']"]
    end

    subgraph Complex
        O["object({...})<br/>Structured data"]
        T["tuple([...])<br/>Mixed types"]
    end

    Primitive --> Collection --> Complex

    style Primitive fill:#e3f2fd
    style Collection fill:#e8f5e9
    style Complex fill:#fff3e0

Validation Example #

variable "instance_type" {
  type        = string
  description = "EC2 instance type"

  validation {
    condition     = can(regex("^t3\\.", var.instance_type))
    error_message = "Instance type must be from the t3 family."
  }
}

After understanding variables, learn about Output to know how to expose information from the Terraform configuration.

About | Author | Content Scope | Editorial Policy | Privacy Policy | Disclaimer | Contact