Input Variables
Crumb's configuration hard-codes crumb-prod-assets and t3.micro. To build a staging copy you would have to edit the files, and then edit them back. Input variables turn those fixed values into parameters.
The rule
Declare it with variable, use it as var, supply it per run.
A variable block declares a parameter:
variable "environment" {
type = string
description = "Deployment environment, such as staging or prod"
}
variable "instance_type" {
type = string
description = "Size of the web server"
default = "t3.micro"
}Useful arguments:
type— what kind of value is allowed (next lesson).description— what it is for; tools and teammates read this.default— the value used if none is given. No default means required.sensitive = true— hide the value in plan and apply output.nullable = false— refusenullas a value.
Resources read them with the var. prefix:
resource "aws_s3_bucket" "assets" {
bucket = "crumb-${var.environment}-assets"
}
resource "aws_instance" "web" {
ami = "ami-0123456789abcdef0"
instance_type = var.instance_type
}Supplying a value on the command line:
terraform plan -var="environment=staging"If a required variable gets no value, an interactive run asks for it:
var.environment
Deployment environment, such as staging or prod
Enter a value:In automation, -input=false turns that prompt into an error, which is what you want in a pipeline.
Variables are fixed for a run: you cannot assign to var.environment inside the configuration. Some names are reserved and cannot be used for variables, including count, for_each, source, version, depends_on, lifecycle and providers.
The shortcut
Scan for "what would differ between two copies?" Each answer becomes a variable. Things that are the same everywhere stay as literals.
Compare staging and prod
Differences: the environment name, the server size. Same: the region, the AMI for now.
The trap: turning every value into a variable "for flexibility". Each one is something a user must understand; parameterise what really varies.
Drills
Answer fast — trust the rule.
How does a resource read the variable instance_type?
What makes a variable required?
A required variable has no value and you run terraform plan -input=false. What happens?
Which command sets environment for a single run?
Remember
variable "name" { ... }declares;var.namereads; no default means required.- Shortcut: what would differ between two copies? Those are your variables.
- Trap: too many variables make a configuration harder to use, not easier.
