Input Variables
Imagine you’re designing a Lego set. If every piece is glued together, you can only build one fixed model. But if you keep the pieces adjustable, you can reuse them to create endless designs.
In Terraform, input variables are those adjustable pieces. Instead of hardcoding values like instance types or regions, you define variables that make your configuration dynamic, reusable, and adaptable across environments.
What are Input Variables?
- Input variables are parameters that allow you to customize Terraform configurations without editing the code directly.
- They make your
.tffiles reusable across multiple environments (dev, staging, prod).
Declaring Variables
Variables are declared in a variables.tf file or directly in your configuration:
variable "instance_type" {
description = "Type of EC2 instance"
type = string
default = "t2.micro"
}
Using Variables
You reference variables inside resource definitions:
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = var.instance_type
}
Here, var.instance_type pulls the value from the variable declaration.
Assigning Values
Variables can be assigned in multiple ways:
- Default Value: Defined in the variable block
- Command Line:
terraform apply -var="instance_type=t2.small" - Variable Files: Create
terraform.tfvarsor*.auto.tfvars - Environment Variables:
TF_VAR_instance_type=t2.small
Types of Variables
- String:
"t2.micro" - Number:
2 - Bool:
true - List:
["t2.micro", "t2.small"] - Map:
{ dev = "t2.micro", prod = "t2.large" }
Hands‑On Lab / Demo
Lab: Parameterizing EC2 Instance
- Run:
terraform plan→ shows instance type from variableterraform apply→ provisions EC2 with default type- Override with CLI:
terraform apply -var="instance_type=t2.small"
Update main.tf:
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = var.instance_type
}
Create variables.tf:
variable "instance_type" {
description = "Type of EC2 instance"
type = string
default = "t2.micro"
}
Pro Tips & Best Practices
- Keep variables organized in a separate
variables.tffile. - Use descriptive names and add
descriptionfor clarity. - Avoid hardcoding sensitive values - use environment variables or secret managers.
- Use
terraform.tfvarsfor environment‑specific values. - Validate variable types to prevent errors.
Summary & Cheatsheet
- Input Variables = Parameters for flexibility.
- Declare → Reference → Assign.
- Ways to assign: Default, CLI,
.tfvars, environment variables. - Types: String, Number, Bool, List, Map.
Quick mnemonic: Variables = Flexibility, Reuse, Control
The Hackers Notebook
Input variables transform Terraform from a static script into a dynamic, reusable framework. They allow you to adapt configurations across environments without rewriting code, making your infrastructure scalable and professional.
