Terraform Tutorial — Declaring Variables
The variable block declares an input variable. A well-declared variable includes a type, description, and optionally a default value.
The variable Block
variable "region" {
type = string
default = "us-east-1"
description = "AWS region where all resources will be created"
}
| Attribute | Required? | Purpose |
|---|---|---|
type |
Recommended | The data type (string, number, list, etc.) |
default |
Optional | Value used if no other value is provided |
description |
Recommended | Human-readable explanation (shown in docs and prompts) |
sensitive |
Optional | Hides the value in plan and output |
nullable |
Optional | Whether null is an acceptable value |
validation |
Optional | Custom validation rules |
Variables Without Defaults
If a variable has no default, Terraform requires you to provide a value:
variable "environment" {
type = string
description = "Deployment environment (dev, staging, prod)"
}
If you run terraform plan without providing this value:
var.environment
Deployment environment (dev, staging, prod)
Enter a value:
Terraform prompts interactively. In CI/CD, this causes the pipeline to hang — always provide values via .tfvars or environment variables.
Using Variables in Resources
Reference variables with the var. prefix:
variable "instance_type" {
type = string
default = "t3.micro"
}
variable "environment" {
type = string
default = "dev"
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = var.instance_type
tags = {
Environment = var.environment
}
}
When to Use Defaults
| Scenario | Use Default? |
|---|---|
| Value is the same 90% of the time | ✅ Yes — set the common value as default |
| Value must be explicitly chosen (environment name, project name) | ❌ No — force the user to provide it |
| Sensitive value (password, API key) | ❌ No — never put secrets in defaults |
Variable File Organization
By convention, all variable declarations go in variables.tf:
# variables.tf
variable "region" {
type = string
default = "us-east-1"
description = "AWS region"
}
variable "environment" {
type = string
description = "Deployment environment"
}
variable "project_name" {
type = string
default = "myapp"
description = "Project name used in resource naming"
}
This makes it easy for teammates to see all inputs at a glance.
What’s Next?
You’ve declared variables. Now let’s learn the multiple ways to provide values — .tfvars files, CLI flags, and environment variables.