Terraform Variables
Hard‑coding values in Terraform configurations makes them inflexible. Input variables allow you to parameterize your infrastructure, making configurations reusable across environments (dev, stage, prod).
Declaring a Variable
Use the
variable block. At minimum, provide a name. Optionally add a description, type, and default value.variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t2.micro"
}Using Variables
Reference a variable with
var.<name>:resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = var.instance_type
}Variable Types
Common types:
string, number, bool, list(string), map(string), object, tuple.variable "subnet_ids" {
type = list(string)
default = ["subnet-abc", "subnet-def"]
}
variable "tags" {
type = map(string)
default = {
Environment = "dev"
Project = "demo"
}
}Setting Variable Values
Several ways (from lowest to highest precedence):
- Default value in variable block
- Environment variables (
TF_VAR_name) terraform.tfvarsor*.auto.tfvarsfiles- Command line
-varor-var-file
terraform.tfvars:instance_type = "t3.small"
subnet_ids = ["subnet-123", "subnet-456"]Sensitive Variables
Mark a variable as sensitive to hide its value in logs:
variable "db_password" {
type = string
sensitive = true
}Two Minute Drill
- Variables parameterize configurations.
- Declare with
variableblock, set type and optional default. - Reference with
var.name. - Set values via tfvars files, env vars, or CLI.
Need more clarification?
Drop us an email at career@quipoinfotech.com
