DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Infrastructure as Code: How Automation Evolved to Power AI Workloads
  • Policy-as-Code for Terraform in Regulated Environments
  • The Open Source Climate Stack: Essential GitHub Repos Powering the Decarbonization Movement
  • Automatic Code Transformation With OpenRewrite

Trending

  • Optimizing Databricks Spark Pipelines Using Declarative Patterns
  • YOLOv5 PyTorch Tutorial
  • Design Patterns for GenAI Creative Systems in Advertising
  • A Comprehensive Guide to Prompt Engineering
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. How to Add Comments in Terraform Code

How to Add Comments in Terraform Code

The types of comments in Terraform, how to use them effectively, and best practices for writing clear, concise annotations.

By 
Mariusz Michalowski user avatar
Mariusz Michalowski
·
Feb. 06, 25 · Tutorial
Likes (0)
Comment
Save
Tweet
Share
5.0K Views

Join the DZone community and get the full member experience.

Join For Free

In Terraform, comments are lines or sections of code that are ignored during execution but are useful for providing context, explanations, or notes within the code. They ensure team members can quickly grasp the purpose and functionality of configurations, reducing confusion and improving efficiency. 

In this article, we’ll cover the types of comments in Terraform, how to use them effectively, and best practices for writing clear, concise annotations.

Types of Comments in Terraform

There are two main types of comments in Terraform. They are used to annotate the configuration by providing context and explanations:

  1. Single-line comments. Start with # or // and are used for brief explanations or disabling specific lines of code.
  2. Multi-line comments. Enclosed in a comment block between /* and */ and are used for longer explanations or commenting out blocks of code.

Regardless of type, comments are ignored by the Terraform parser and do not affect the actual execution of the code. 

When using custom tooling or integrations, you may encounter references to /// comments. These are not officially supported as part of Terraform's syntax but are sometimes utilized in specialized workflows.

For example, some documentation generation tools or linters may interpret lines beginning with /// as markers for extracting structured documentation, similar to how certain programming languages use triple-slash comments.

When to Use Terraform Comments

Comments should enhance understanding and collaboration without cluttering the codebase. Here are some common scenarios when you should include comments in your configurations:

  • Explain the purpose. Describe the purpose of a resource, variable, or module to provide context.
  • Document assumptions. Highlight assumptions made during the configuration.
  • Mark TODOs. Use comments to note areas that need further attention or future updates (e.g., # TODO: Add monitoring).
  • Provide references. Link to documentation or ticket numbers related to the code.
  • Versioning. Comment on the configuration to reflect the Terraform or provider version compatibility.

How to Add Single-Line Comments in Terraform Files

Single-line comments are added in Terraform code using the # or // symbols. Both styles are supported, and you can use them interchangeably, depending on your preference. 

Note: Using # is considered the default comment style and is more commonly used in Terraform configurations. It is the standard style in most Terraform examples and documentation.

Let’s see some examples.

Single-line and inline comments using the hash symbol:

Plain Text
 
# Define an AWS EC2 instance
resource "aws_instance" "example" {
  ami           = "ami-12345678"  # Amazon Machine Image ID
  instance_type = "t2.micro"      # Instance type
}


Single-line and inline comments using double slashes:

Plain Text
 
// Define an AWS S3 bucket
resource "aws_s3_bucket" "example" {
  bucket = "example-bucket-name"  // Name of the S3 bucket
  acl    = "private"              // Access control list for the bucket
}


Inline comments can follow any valid Terraform configuration line. Ensure there is a space between the code and the comment for readability.

How to Add Multiline Comments in Terraform Files

For multi-line comments, Terraform supports standard block comments using the /* ... */ syntax. Everything between /* and */ is treated as a comment, similar to multi-line comments in many programming languages like Java or C.

For example:

Plain Text
 
/*
  This is a multiline comment in Terraform.

  Use this to document:
  - Configuration details
  - Explanation of resources
  - Notes for other team members

  Block comments are clean and versatile.
*/
resource "aws_instance" "example" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"
}


Alternatively, you can use the # symbol at the beginning of each line for multiline comments. While this isn't a true "block comment," it works for multiple lines.

Plain Text
 
# This is a multiline comment in Terraform.
# Use this format when you prefer single-line hash comments:
# - Each line starts with a hash (#).
# - Provides clear separation for each line.


Multiline comments are particularly useful for temporarily commenting out sections of your Terraform code or providing detailed documentation directly in your configuration files.

Best Practices for Commenting in Terraform Code

Follow the best practices below to create clear, maintainable, and professional Terraform configurations.

  • Standardize comment style. Use a consistent format for comments across your infrastructure to improve readability and reduce confusion when working with large teams.
  • Avoid over-commenting. Too many comments, especially redundant ones, can clutter the codebase and reduce readability.
  • Avoid overusing inline comments. Excessive inline comments can break code flow and make configurations harder to read. Use inline comments sparingly and only for clarifications that are immediately relevant.
  • Avoid commenting sensitive information. Comments may inadvertently expose passwords, API keys, or other sensitive details, leading to security vulnerabilities. Avoid including sensitive information in comments or configuration files. Use environment variables or secret management tools instead.
  • Focus on intent. Terraform code is typically self-explanatory. Comments should add value by explaining why the configuration exists, not how it works. Focus on explaining the reasoning behind design choices, constraints, or any non-obvious decisions.
  • Document critical resources. Highlight resources with high impact (e.g., production databases, IAM roles, or security groups) with notes about dependencies, limitations, or risks.
  • Keep comments up-to-date. Update comments when making changes to the code. Outdated comments can mislead other contributors.
  • Indicate manual processes. Some configurations require manual steps, and documenting these ensures they are not overlooked. Use comments to flag any manual actions or processes required before or after deployment.
  • Automate comment checks. Tools like TFLint can be customized to include comment checks to ensure consistency, accuracy, and compliance with your team's coding standards. 

Key points

Using comments effectively can improve collaboration within teams and make Terraform configurations easier to understand and maintain over time. However, it's important to strike a balance — comments should enhance understanding without cluttering the codebase.

Tool Terraform (software) Infrastructure as code Open source

Published at DZone with permission of Mariusz Michalowski. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Infrastructure as Code: How Automation Evolved to Power AI Workloads
  • Policy-as-Code for Terraform in Regulated Environments
  • The Open Source Climate Stack: Essential GitHub Repos Powering the Decarbonization Movement
  • Automatic Code Transformation With OpenRewrite

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook