You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Variables make your Terraform configuration flexible and reusable. Outputs expose values from your infrastructure for use by other configurations or scripts. This lesson covers input variables, output values, local values, and variable files.
An input variable is declared with the variable block:
variable "region" {
description = "The AWS region to deploy into"
type = string
default = "eu-west-2"
}
variable "instance_count" {
description = "Number of instances to create"
type = number
default = 1
}
variable "enable_monitoring" {
description = "Whether to enable detailed monitoring"
type = bool
default = false
}
| Argument | Required | Purpose |
|---|---|---|
description | No (recommended) | Documents the variable's purpose |
type | No (recommended) | Constrains the variable type |
default | No | Default value if none is provided |
validation | No | Custom validation rules |
sensitive | No | Hides the value in plan output |
nullable | No | Whether the variable can be null |
variable "name" { type = string }
variable "count" { type = number }
variable "enabled" { type = bool }
variable "availability_zones" {
type = list(string)
default = ["eu-west-2a", "eu-west-2b"]
}
variable "tags" {
type = map(string)
default = {
Environment = "development"
Team = "platform"
}
}
variable "ports" {
type = set(number)
default = [80, 443]
}
variable "instance_config" {
type = object({
instance_type = string
ami = string
monitoring = bool
})
default = {
instance_type = "t3.micro"
ami = "ami-0c55b159cbfafe1f0"
monitoring = false
}
}
Variables can be set in multiple ways, listed by precedence (highest to lowest):
| Method | Example |
|---|---|
| Command-line flag | terraform apply -var="region=us-east-1" |
| Variable file flag | terraform apply -var-file="prod.tfvars" |
terraform.tfvars | Automatically loaded |
*.auto.tfvars | Automatically loaded (alphabetical order) |
| Environment variable | export TF_VAR_region=us-east-1 |
| Default value | Defined in the variable block |
| Interactive prompt | Terraform asks if no value is provided |
region = "eu-west-2"
instance_count = 3
enable_monitoring = true
export TF_VAR_region="eu-west-2"
export TF_VAR_instance_count=3
Add custom validation rules to catch errors early:
variable "environment" {
type = string
description = "Deployment environment"
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.