Module 4: Terraform Configuration

Lesson 4.3: Variables and Outputs

Input variables

HCL
variable "environment" {
  type        = string
  description = "Deployment environment."
  default     = "dev"  # no default → required
  nullable    = false  # passing null uses the default instead
  sensitive   = false  # true → redacted in CLI output
  ephemeral   = false  # true → never written to state or plan (Lesson 4.8)

  validation {         # Lesson 4.7
    condition     = contains(["dev", "stage", "prod"], var.environment)
    error_message = "environment must be dev, stage, or prod."
  }
}

A variable with no default is required. Terraform prompts for it interactively, or errors if you pass -input=false.

Variable precedence

Sources are applied in this order, and later sources override earlier ones:

Order Source Notes
0 default in the variable block Lowest priority
1 Environment variable TF_VAR_<name> Name is case-sensitive
2 terraform.tfvars Loaded automatically
3 terraform.tfvars.json Loaded automatically
4 *.auto.tfvars / *.auto.tfvars.json Loaded automatically, in lexical filename order
5 -var and -var-file on the command line Processed in the order given. The last one wins. Highest priority.

Outputs

HCL
output "url" {
  description = "Public URL of the web container."
  value       = "http://localhost:${docker_container.web.ports[0].external}"
}

output "db_password" {
  value     = var.db_password
  sensitive = true # required when value derives from a sensitive value
}

Root module outputs:

  • terraform output with no arguments shows <sensitive> for sensitive outputs. Naming one output (terraform output NAME), or using -json or -raw, prints the value in plaintext. Ephemeral values are never shown, because they aren't stored.
  • Values are stored in state.

Child module outputs become module.<name>.<output> in the parent. Outputs also accept depends_on and precondition.