Input Variables

Input variables make configurations reusable by parameterizing values like region and instance size.

Syntaxvariable "region" { type = string default = "us-east-1" }

Input variables are the parameters of your configuration. Instead of hard-coding us-east-1 everywhere, declare a variable and reference it, so the same code can build different environments.

Declaring a variable

Use a variable block with an optional type, default, and description. Reference it as var.name.

Setting values

Values can come from defaults, -var flags, .tfvars files, or environment variables prefixed with TF_VAR_.

Example

Example · hcl
variable "instance_type" {
  type        = string
  default     = "t3.micro"
  description = "EC2 instance size for the web server"
}

resource "aws_instance" "web" {
  ami           = "ami-0c02fb55956c7d316"
  instance_type = var.instance_type
}

When to use it

  • A module author defines an instance_type variable so callers can choose t3.micro for dev and m5.large for production without editing module code.
  • A team sets TF_VAR_environment=staging in CI so the same Terraform code provisions staging resources with different names than production.
  • An engineer uses a variable with a default value so the configuration works out of the box in local development without requiring any tfvars file.

More examples

Variable with default value

Declares a string variable with a default and uses it in a resource, allowing the caller to override without editing the resource block.

Example · hcl
variable "instance_type" {
  description = "EC2 instance type for the web server"
  type        = string
  default     = "t3.micro"
}

resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = var.instance_type
}

Required variable (no default)

Defines a required variable with no default and marks it sensitive so Terraform redacts the value in plan and log output.

Example · hcl
variable "db_password" {
  description = "Master password for the RDS instance"
  type        = string
  sensitive   = true
}

resource "aws_db_instance" "app" {
  engine   = "postgres"
  password = var.db_password
  # other args...
}

Override variable via CLI flag

Shows two ways to override a variable at runtime: the -var flag and the TF_VAR_ environment variable convention.

Example · bash
# Pass a variable at the command line
terraform plan -var="instance_type=t3.small"

# Or use the TF_VAR_ environment variable convention
export TF_VAR_instance_type=t3.large
terraform apply

Discussion

  • Be the first to comment on this lesson.