Comments and Formatting in HCL
You'll learn how to document your Terraform code with comments and automatically format it for consistency across your team.
Why Comments and Formatting Matter
When writing infrastructure code, clarity is everything. You might understand your configuration today, but what about in six months? What about your teammates? Comments help explain the why behind your code, while consistent formatting makes it readable at a glance—like having clean handwriting versus messy scribbles.
Single-Line Comments
In HCL, use # or // to add a single-line comment:
# This is a comment explaining the purpose
resource "aws_instance" "web" {
ami = "ami-12345678" // Ubuntu 22.04 LTS
instance_type = "t2.micro"
}
Both styles work identically—choose one and stick with it for consistency.
Multi-Line Comments
For longer explanations, wrap text between /* and */:
/*
This configuration creates a production web server
with specific security requirements defined by
our compliance team in document SEC-2024-01.
*/
resource "aws_instance" "web" {
ami = "ami-12345678"
instance_type = "t2.micro"
}
Automatic Formatting with terraform fmt
Terraform includes a built-in formatter that standardizes indentation, spacing, and alignment. Run this command in your configuration directory:
terraform fmt
It automatically fixes formatting issues, ensuring your entire team's code looks uniform. Think of it as an auto-correct for infrastructure code—it catches spacing mistakes and aligns everything perfectly.
Key Takeaway: Use # or // for single-line comments, /* */ for multi-line notes, and always run terraform fmt before committing code to maintain professional, readable configurations.