Terraform Variable Block: Types, Syntax & Examples

Published: 2025-08-04
8 min read
Share:

If you've ever deployed the same Terraform configuration across development, staging, and production environments, you've probably faced the challenge of managing different values without duplicating code. That's exactly what the Terraform Variable Block solves.

Variables allow you to separate configuration values from infrastructure logic, making Terraform code easier to reuse, maintain, and scale. Whether you're creating a simple EC2 instance or building reusable modules for multiple teams, variable blocks are a core part of every Terraform project.

Before continuing, it's helpful to understand the basics of HashiCorp Configuration Language (HCL) since Terraform variables are declared using HCL syntax.

What Is a Terraform Variable Block?

A Terraform Variable Block is used to declare input variables that can be referenced throughout a Terraform configuration.

Instead of hardcoding values directly inside resources, variables allow you to define configurable inputs that can be overridden for different environments.

A variable block can contain several optional arguments:

  • type — Defines the expected data type.
  • default — Provides a fallback value.
  • description — Documents the purpose of the variable.
  • validation — Applies custom validation rules.

Terraform Variable Block Syntax

A basic variable block looks like this:

variable "instance_type" {
  description = "EC2 instance type"
  type        = string
  default     = "t3.micro"
}

The value can later be referenced anywhere in the configuration using:

var.instance_type

If you're new to variable consumption, check out this guide on using variables in Terraform.

Common Terraform Variable Types

Terraform supports multiple data types to help validate inputs and reduce configuration errors.

String Variables

String variables store text values and are among the most commonly used variable types.

variable "region" {
  type        = string
  description = "AWS region"
  default     = "us-east-1"
}

Common use cases include:

  • AWS regions
  • Resource names
  • Environment names
  • Domain names

Number Variables

Number variables support both integers and floating-point values.

variable "instance_count" {
  type    = number
  default = 3
}

Typical use cases include:

  • Instance counts
  • Port numbers
  • CPU allocations
  • Scaling thresholds

Boolean Variables

Boolean variables store either true or false.

variable "enable_monitoring" {
  type    = bool
  default = true
}

Boolean values are commonly used for:

  • Feature flags
  • Optional resources
  • Conditional deployments

Production Tip

Always define a variable type explicitly. Terraform allows variables without a type constraint, which defaults to any, but strong typing catches mistakes during terraform plan before they become deployment issues.

Working with Collections: List, Map, and Set Variables

For small projects, strings and numbers may be enough. As your infrastructure grows, collection types become essential for managing groups of related values.

List Variables

Lists store ordered collections of values.

variable "prefixes" {
  type    = list(string)
  default = ["Mr", "Mrs", "Dr"]
}

Access list elements using their index:

var.prefixes[1]

Output:

Mrs

Map Variables

Maps store data as key-value pairs.

variable "file_content" {
  type = map(string)

  default = {
    statement1 = "We love automation."
    statement2 = "Terraform makes infrastructure predictable."
  }
}

Access values using the key:

var.file_content["statement2"]

Maps are commonly used for:

  • Environment-specific settings
  • Resource tagging
  • Application configuration

Set Variables

Sets store unique values without duplicates.

variable "unique_tags" {
  type    = set(string)
  default = ["web", "db", "cache"]
}

Terraform automatically removes duplicate values from a set.

Sets are useful when:

  • Order doesn't matter
  • Duplicate values should be prevented
  • Managing unique resource identifiers

Modeling Structured Data with Object and Tuple Variables

As Terraform projects become more modular, you'll often need to pass complex data structures into modules.

Object Variables

Objects allow you to define structured data with multiple attributes and explicit types.

variable "cat_profile" {
  type = object({
    name         = string
    color        = string
    age          = number
    food         = list(string)
    favorite_pet = bool
  })

  default = {
    name         = "Tom"
    color        = "Brown"
    age          = 7
    food         = ["fish", "chicken", "turkey"]
    favorite_pet = true
  }
}

In production environments, object variables are frequently used to pass:

  • Networking configuration
  • Application settings
  • Resource tagging standards
  • Module configuration

Tuple Variables

Tuples store ordered values where each position has a predefined type.

variable "pet_details" {
  type    = tuple([string, number, bool])
  default = ["cat", 7, true]
}

The values must follow the exact type order defined in the tuple.

For example:

["cat", 7, true]

is valid, while:

[7, "cat", true]

would fail validation.

Combining Type Constraints for Strong Validation

Terraform allows type constraints to be nested for stricter validation.

Examples include:

list(number)
map(string)
set(bool)

These constraints help catch invalid input values during planning instead of after deployment.

Terraform validates variable types before resource creation, reducing runtime failures and improving infrastructure reliability.

Variable Validation Example

Beyond type constraints, Terraform also supports custom validation rules.

variable "port" {
  type = number

  validation {
    condition     = var.port >= 1 && var.port <= 65535
    error_message = "Port must be between 1 and 65535."
  }
}

This prevents invalid values from being used during execution.

Validation blocks are particularly useful when:

  • Restricting environment names
  • Validating CIDR ranges
  • Enforcing naming standards
  • Preventing unsupported instance types

According to the official Terraform Language Documentation, validation rules help catch incorrect user input before Terraform attempts to provision infrastructure.

Real-World Terraform Variable Block Example

A common pattern is using variables to customize infrastructure across environments without changing the core configuration.

variables.tf

variable "environment" {
  type = string
}

variable "instance_type" {
  type = map(string)

  default = {
    dev  = "t3.micro"
    prod = "t3.large"
  }
}

main.tf

resource "aws_instance" "web" {
  ami           = "ami-1234567890abcdef0"
  instance_type = var.instance_type[var.environment]
}

With this approach:

  • Development can use smaller instances.
  • Production can use larger instances.
  • The same codebase can support multiple environments.

This pattern becomes even more powerful when building reusable Terraform modules, where variables serve as the interface between module users and module logic.

How Terraform Variable Values Are Assigned

Terraform can receive variable values from multiple sources.

Common methods include:

Default Values

variable "region" {
  default = "us-east-1"
}

Terraform Variable Files

Example terraform.tfvars:

region = "us-west-2"

Command-Line Arguments

terraform apply -var="region=us-west-2"

Environment Variables

export TF_VAR_region=us-west-2

Understanding variable precedence is important when managing multiple environments and automation pipelines.

Best Practices for Terraform Variable Blocks

Follow these practices when working with variables:

  • Always define a type constraint.
  • Add meaningful descriptions.
  • Use validation for critical inputs.
  • Avoid unnecessary use of any.
  • Store reusable variables in variables.tf.
  • Use .tfvars files for environment-specific values.
  • Keep variable names descriptive and consistent.
  • Design variables with module reusability in mind.

If you're building reusable infrastructure, consider pairing variables with Terraform output variables to create clean interfaces between modules and consumers.

You can also browse community module examples on the Terraform Registry to see how experienced practitioners structure variable definitions.

Frequently Asked Questions (FAQs)

What is a variable block in Terraform?

A variable block declares an input variable that can be referenced throughout a Terraform configuration. It allows values to be customized without modifying resource definitions directly.

What types of variables does Terraform support?

Terraform supports string, number, bool, list, map, set, object, and tuple types. It also supports nested type constraints such as list(string) and map(number).

Can I create variables without specifying a type?

Yes. Terraform allows variables without a type constraint, which defaults to any. However, explicitly defining types is considered a best practice because it provides validation and reduces configuration errors.

What is the difference between a list and a set?

A list maintains element order and allows duplicate values. A set is unordered and automatically removes duplicates.

When should I use object variables?

Object variables are ideal when multiple related values need to be grouped together. They are commonly used in Terraform modules to pass structured configuration such as networking, tagging, or application settings.

Can Terraform validate variable values?

Yes. Terraform supports validation blocks that allow you to define custom rules and error messages. Validation helps prevent invalid inputs before infrastructure is created or modified.

Final Thoughts

Most Terraform projects begin with a few simple variables. As configurations grow, variable blocks become the foundation for reusable modules, environment-specific customization, and safer infrastructure deployments.

By combining type constraints, validation rules, and structured data types, you can create Terraform configurations that are easier to maintain, scale, and share across teams.

For a deeper understanding of the Terraform ecosystem, explore related guides on using variables in Terraform, Terraform output variables, Terraform modules, and Terraform Registry modules.

Free Engineering ToolsNEW

8 free, 100% client-side tools for developers — no signup, no data uploads.

Explore all tools