Format Variable and Output Blocks

Format Terraform variable declarations with types, defaults, descriptions, and validation rules. Also covers output blocks with descriptions and value expressions.

Variables & Outputs

Detailed Explanation

Formatting Variables and Outputs

Variable and output blocks are the interface of a Terraform module. Clean formatting makes the module's API immediately understandable to consumers.

Variable Block Examples

variable "environment" {
  description = "Deployment environment name"
  type        = string
  default     = "development"

  validation {
    condition     = contains(["development", "staging", "production"], var.environment)
    error_message = "Environment must be development, staging, or production."
  }
}

variable "vpc_config" {
  description = "VPC configuration settings"
  type = object({
    cidr_block         = string
    enable_nat_gateway = bool
    single_nat_gateway = bool
    azs                = list(string)
  })
  default = {
    cidr_block         = "10.0.0.0/16"
    enable_nat_gateway = true
    single_nat_gateway = false
    azs                = ["us-east-1a", "us-east-1b", "us-east-1c"]
  }
}

variable "tags" {
  description = "Common tags applied to all resources"
  type        = map(string)
  default     = {}
}

Output Block Examples

output "vpc_id" {
  description = "The ID of the VPC"
  value       = aws_vpc.main.id
}

output "private_subnet_ids" {
  description = "List of private subnet IDs"
  value       = aws_subnet.private[*].id
}

output "database_endpoint" {
  description = "RDS instance endpoint"
  value       = aws_db_instance.main.endpoint
  sensitive   = true
}

Formatting Conventions

  • Attribute order: description first, then type, then default, then validation
  • Aligned equals: All top-level attributes within a variable or output block are aligned
  • Complex types: object({}) and list() type definitions have their fields indented and aligned
  • Default values: Complex defaults mirror the type structure with consistent indentation
  • Sensitive outputs: The sensitive = true flag is aligned with other attributes

Use Case

Defining the public interface of Terraform modules, making it clear what inputs are required, what types they accept, and what the module produces as outputs.

Try It — Terraform HCL Formatter

Open full tool