Variables in Terraform: My learnings.

Published: (December 28, 2025 at 06:41 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

Introduction

Terraform variables allow you to store values that can be reused throughout your configuration. There are two categories:

  • Input variables – values you provide to a configuration.
  • Output variables – values produced after terraform apply.

Input Variables

Input variables let you parameterize your configuration (e.g., instance type, region, instance count).

variable "example" {
  type        = string   # optional
  default     = "value"  # optional
  description = "A description of the variable"
}

Output Variables

Output variables expose information after a run, such as an EC2 instance’s public IP.

output "example" {
  value       = aws_instance.example.public_ip
  description = "The public IP of the instance"
}

Data Types in Terraform

Terraform supports primitive and complex data types.

Primitive Data Types

TypeDescription
stringArbitrary text, e.g., "us-east-1"
numberInteger or floating‑point values, e.g., 2
boolBoolean values true or false

Complex Data Types

List

Ordered collection of values of the same type.

variable "regions" {
  type    = list(string)
  default = ["ap-south-1", "us-east-1", "us-west-1"]
}

Set

Unordered collection of unique values of the same type.

variable "unique_regions" {
  type    = set(string)
  default = ["ap-south-1", "us-east-1", "us-west-1"]
}

Map

Key‑value pairs where keys are strings and values share a common type.

variable "tags" {
  type = map(string)
  default = {
    name        = "ec2_instance"
    description = "ec2 instance for running the backend"
    env         = "prod"
  }
}

Tuple

Ordered collection with a fixed length that can contain values of different types. Tuples are immutable.

variable "network_addresses" {
  type    = tuple([string, string])
  default = ["192.168.1.2", "192.168.1.1"]
}

Object

Structured type with named attributes, each potentially having a different type.

variable "user" {
  type = object({
    name  = string
    age   = number
    email = string
  })
  default = {
    name  = "Rohan"
    age   = 20
    email = "rohan@gmail.com"
  }
}

Conclusion

Terraform variables simplify configurations by avoiding hard‑coded literals and enabling reuse of values across modules and resources.

Back to Blog

Related posts

Read more »