Let's think about this for a second
If you hardcode `instance_type = "t3.micro"` in your config, you'd have to manually edit the code every time you switch environments (dev vs prod). Using an Input Variable (`variable "name" { type = ... }`) instead lets you supply the value at run time — via a command-line flag, a `.tfvars` file, an environment variable, or a default value. Specifying a variable's `type` (string, number, bool, list, map, object) means Terraform will catch a mistyped value with an error before applying.
Let's connect this to a real scenario
If you define `variable "instance_type" { type = string; default = "t3.micro" }` and reference it in a resource block as `instance_type = var.instance_type`, you can override the value with `terraform apply -var="instance_type=t3.large"` (or a `.tfvars` file) — this lets a single config file handle small instances for dev and large instances for prod.
Let's look at an example
variable "instance_type" {
description = "EC2 instance size"
type = string
default = "t3.micro"
}
variable "environment" {
type = string
}
resource "aws_instance" "web" {
instance_type = var.instance_type
tags = {
Environment = var.environment
}
}$ terraform apply -var="environment=staging"
var.instance_type
EC2 instance size
Enter a value: (uses default "t3.micro" if left blank)5-minute try-it
Define 2 variables (instance_type, environment) and run `terraform plan`, passing a value with the `-var` flag — try both the default value and an override.
A quick word of caution
If you write sensitive values (passwords, API keys) in a `.tfvars` file, add it to `.gitignore` so it never gets committed to your git repository.