Terraform Variables and Outputs
Learn how to parameterize Terraform with input variables and expose values with outputs.
Terraform becomes reusable and environment-friendly when you separate what changes from what stays the same.
- Variables = inputs (things you set)
- Outputs = values you export (things you read)
Learning outcomes
By the end you’ll know:
- how to define variables (type, default, validation)
- how to pass variables into root modules / modules
- how to create outputs for inspection and wiring modules together
1) Input variables
Simple variable
variable "aws_region" {
type = string
default = "us-east-1"
}
Read it like:
provider "aws" {
region = var.aws_region
}
Required variable (no default)
variable "project_name" {
type = string
}
Provide it via CLI:
terraform apply -var "project_name=my-app"
Or with a variable file:
terraform apply -var-file=dev.tfvars
Example dev.tfvars:
project_name = "my-app"
aws_region = "us-east-1"
2) Variable types (practical)
Terraform types help validation and editor hints.
List
variable "allowed_cidrs" {
type = list(string)
default = ["203.0.113.0/24", "198.51.100.0/24"]
}
Map
variable "tags" {
type = map(string)
default = {
owner = "platform"
env = "dev"
}
}
Object
variable "vpc" {
type = object({
cidr_block = string
enable_dns = bool
})
default = {
cidr_block = "10.0.0.0/16"
enable_dns = true
}
}
3) Variable validation
Example:
variable "environment" {
type = string
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "environment must be dev, staging, or prod"
}
}
4) Outputs
Outputs expose values from your configuration.
Simple output
output "bucket_name" {
value = aws_s3_bucket.example.bucket
}
Output with description and sensitive value (concept)
output "db_password" {
description = "Database password (sensitive)"
value = aws_db_instance.example.password
sensitive = true
}
Inspect outputs
After apply:
terraform output
5) Module inputs and outputs
If you have a module, you pass variables into it.
Example root calling a module:
module "vpc" {
source = "./modules/vpc"
cidr_block = "10.0.0.0/16"
tags = {
owner = "platform"
}
}
Module outputs can be consumed by the caller:
output "vpc_id" {
value = module.vpc.vpc_id
}
Rule of thumb: a module should “export” the few values that other stacks/modules need.
6) Cleanup reminder
terraform destroy Frequently Asked Questions
When should I use a variable vs an output?
Use variables to parameterize your configuration (inputs). Use outputs to expose values from your resources/modules to callers (or to root modules / other tools).
Why do modules usually accept variables?
Modules should be reusable. Variables let you configure what the module creates without editing the module’s internal code.