0
0
Terraformcloud~5 mins

Comments in HCL in Terraform - Commands & Configuration

Choose your learning style9 modes available
Introduction
When writing Terraform code, you often need to add notes or explanations to make your code easier to understand. Comments let you do this without affecting how Terraform runs your code.
When you want to explain why a resource is configured a certain way.
When you need to temporarily disable a line of code without deleting it.
When you want to leave reminders for yourself or others about future changes.
When you want to clarify complex expressions or variable usage.
When you want to document the purpose of a module or resource block.
Config File - main.tf
main.tf
terraform {
  required_version = ">= 1.0"
}

# This is a single line comment explaining the provider block
provider "aws" {
  region = "us-east-1"  # Inline comment about the region
}

/*
This is a
multi-line comment
explaining the resource below
*/
resource "aws_s3_bucket" "example" {
  bucket = "my-example-bucket"
  acl    = "private"
}

The # symbol starts a single-line comment. Anything after it on the same line is ignored by Terraform.

The /* ... */ syntax is used for multi-line comments that can span several lines.

Comments can be placed on their own line or at the end of a line of code (inline comments).

Commands
This command formats the Terraform file to standard style, ignoring comments but keeping them intact for readability.
Terminal
terraform fmt main.tf
Expected OutputExpected
main.tf
This command checks the Terraform configuration for syntax errors and validates that comments do not affect the code execution.
Terminal
terraform validate
Expected OutputExpected
Success! The configuration is valid.
Key Concept

If you remember nothing else from this pattern, remember: comments help explain your Terraform code without changing how it works.

Common Mistakes
Using incorrect comment syntax like // instead of # or /* */
Terraform's HCL does not recognize // as a comment, causing syntax errors.
Use # for single-line comments and /* */ for multi-line comments.
Placing comments inside strings or resource arguments incorrectly
Comments inside strings are treated as text, not comments, which can cause unexpected behavior.
Place comments outside strings and resource argument values.
Summary
Use # for single-line comments and /* */ for multi-line comments in Terraform HCL files.
Comments do not affect how Terraform runs your code but make it easier to understand.
Validate your configuration with terraform validate to ensure comments are correctly placed.