How To Add Comments In Terraform: Syntax, Examples & Best Practices

How to Add Comments in Terraform

Table of Contents

Get up to 50% off now

Become a partner with CyberPanel and gain access to an incredible offer of up to 50% off on CyberPanel add-ons. Plus, as a partner, you’ll also benefit from comprehensive marketing support and a whole lot more. Join us on this journey today!

Comments in Terraform are lines or parts of code that get ignored when the code runs. However, they’re super helpful for giving context, explanations, or notes into the code. This way, team members can easily understand what the configurations are for, which cuts down on confusion and boosts efficiency.

Importance of Comments in Terraform

Advantages of Commenting in Terraform

  • Documentation: Comments give clarity on the intent, function, and application of blocks, variables, and resources.
  • Debugging and Troubleshooting: A codebase with good comments helps in understanding the purpose and reasoning behind various elements.
  • Collaboration: Comments are essential for effective communication in a team setting where several members are contributing to the same codebase.

Types of Comments in Terraform

Terraform has two primary comment types:

  • Single-line comments (which begin with # or //) Double Sash supported but is less common.
  • Multi-line comments (which are found within a comment block between /* and */).
  • The Terraform parser ignores both comment types, meaning they do not influence code execution.
  • Some custom tools or integrations might use ‘// comments, which are not officially recognized but can be found in specific workflows.
  • Certain documentation generation tools see lines starting with ‘//’ as indicators for extracting structured documentation.

When to Use Comments in Terraform

Comments should improve understanding and teamwork without making the codebase messy. Here are some typical situations where you should add comments in your configurations:

  • Explain purpose: Clarify the purpose of a resource, variable, or module to give context.
  • Document assumptions: Point out assumptions made during the configuration.
  • Mark TODOs: Use comments to indicate areas that require more attention or future updates (e.g., # TODO: Add monitoring).
  • Provide references: Connect to documentation or ticket numbers related to the code.
  • Versioning: Comment on the configuration to show the Terraform or provider version compatibility.

How to Add Comments in Terraform

It’s essential to understand that Terraform does not consider comments when running the code. Comments exist solely for the sake of human understanding and documentation. This is how commenting functions in Terraform.

Single-Line Comments

Let’s start with the fundamentals – single-line comments. These comments are ideal for inserting brief notes or clarifications on a particular line of code. In Terraform, you can create a comment by using the ‘#’ symbol or ‘//’. Everything that comes after these symbols on a line is regarded as a comment.

Tech Delivered to Your Inbox!

Get exclusive access to all things tech-savvy, and be the first to receive 

the latest updates directly in your inbox.

This is a single-line comment

# This is a single-line comment

resource "aws_instance" "example" {

  ami           = "ami-0c55b159cbfafe1f0"

  instance_type = "t2.micro"

}

// This is another single-line comment

variable "region" {

  type        = string

  description = "The AWS region where resources will be created"

  default     = "us-west-2"

}

Both ‘#’ and ‘//’ can be utilized for single-line comments. Nevertheless, the preferred style for single-line comments is indicated by the ‘#’ symbol and is suggested for most cases. Frequently, automatic configuration formatting tools will change ‘//’ comments into ‘#’ comments, as the double-slash format is not seen as standard.

Using // for Single-Line Comments

// 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
}

Using /* */ for Multi-Line Comments

For multi-line comments, Terraform uses standard block comments with the syntax. Everything between these markers is treated as a comment, similar to multi-line comments in many programming languages, such as Java or C.

The command shows how to comment multiple lines in Terraform:

/*
  This is a multi-line comment in Terraform.

  Use this to document:
  - Configuration details
  - Explanation of resources
  - Notes for other team members
*/
resource "aws_instance" "example" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"
}

Multi-line comments are a powerful tool for adding in-depth explanations and documentation to your code. They’re perfect for when you want to clarify complex logic or share important insights about functionality, making your code not just more understandable, but also more maintainable for anyone who comes across it.

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

Best Practices for Comments in Terraform

Comments-in-Terraform-best-practices-flowchart

Terraform Best Practices and Guidelines

1. Storing Terraform Code in a Git Repository

  • GitHub is a robust platform for DevOps and collaboration, recognized for its version control capabilities.
  • It enables users to document, track, revert, and merge changes made by multiple users simultaneously.
  • GitHub acts as a collaborative space for millions of developers through discussions in pull requests and issues.
  • Terraform users should keep their configuration files in a Version Control System (VCS) to manage versions and collaborate on infrastructure.

2. Establishing a Git Repository

  • The initial best practice for Terraform is to set up a Git repository before beginning to write Terraform code.
  • The Git init command sets up a working directory that contains Terraform configuration files.
  • Not all locally downloaded files need to be pushed to the Git Repository alongside other Terraform configuration files.
  • A .gitignore file can be added to the root directory of your project to specify which files and directories Git should ignore during commits.

3. Maintaining a Consistent File Structure

  • Terraform code should be organized into files consistently across all projects.
  • For simpler projects, utilize folders in your project structure when implementing modules.
  • Each repository should include a README.md file.
  • Create a main.tf file to call modules, and store locals and data sources.
  • Include a provider.tf file with provider information.
  • Have a variables.tf file to declare variables used in main.tf and outputs.
  • Use terraform.tfvars to automatically load several variable definitions.

4. Automatically Formatting Terraform Files

  • The HashiCorp Terraform language adheres to the same style guidelines as most programming languages.
  • The ‘terraform fmt’ command can be utilized to correct all code inconsistencies at once.
  • Always run ‘terraform fmt -diff’ to review and format your Terraform configuration files before committing and pushing them.

5: Avoid Hard-Coding Resources in Terraform

  • Steer clear of hard-coding default settings to prevent forgetfulness and save time.
  • Opt for variables instead of hard-coding resources in Terraform configuration files.
  • Always assign values to variables and utilize them as needed.
  • For example, when setting up an EC2 instance, refrain from hard-coding the AMI ID, Instance Type, etc.

6: Follow Naming Convention

  • Create guidelines and standards within your team for naming resources.
  • Use _ (underscore) consistently in resource names, data source names, variable names, outputs, etc.
  • Prefer lowercase letters and numbers whenever feasible.
  • Always use singular nouns for names.
  • Use -(dash) in arguments and in places where the value will be visible to users.

Tip: Set Standards or Norms for Naming Resources

  • Establish standards or norms within your team for naming resources and adhere to them consistently.
  • For instance: _(underscore) is used for naming resource blocks, -(dash) is used for naming a resource, and variables and outputs are named uniformly.

7: Use the Self Variable

  • Self-variables are specific to your resources and are filled in during creation.
  • Utilize the ‘self’ variable when the value of the variable is unknown before deploying the infrastructure.
  • For instance, self.private_ip can be used to retrieve the private IP address of a machine after the initial deployment, even though the IP address isn’t known until it is assigned.

Key Takeaways!

Writing good comments in Terraform makes your code easier to read, helps with teamwork, and acts as useful documentation. If you stick to the best practices mentioned earlier, you’ll make sure your Terraform setups are clear, easy to maintain, and look professional.

To further improve readability and reduce confusion in large teams, maintain a consistent comment style across your infrastructure. Avoid excessive comments, limit inline notes, and protect sensitive information. Focus on the intent and rationale behind design choices.

Write important resources and keep comments updated, highlighting manual processes. Or you can use tools like TFLint, Terraform FMT, and IDE Extensions to automate comment checks for consistency and accuracy.

Enhance Your CyerPanel Experience Today!
Discover a world of enhanced features and show your support for our ongoing development with CyberPanel add-ons. Elevate your experience today!

FAQ’s

1. Can I use both # and // for comments in Terraform?
A: Yes, both are allowed, but # is the preferred and standard style in Terraform.

2: How to comment multiple lines in Terraform?
A: You can use the block comment syntax /* */ to comment out several lines.

3: Do comments influence the Terraform plan or apply process?
A: No, comments are ignored during execution and do not affect the plan or apply phases.

4: Are there tools available to help manage comments in Terraform code?
A: Yes, tools such as TFLint and Terraform FMT can help in managing and formatting comments.

Areeba Nauman
Areeba is a Content Writer with expertise in web content and social media, she can simplify complex concepts to engage diverse audiences. Fueled by creativity and driven by results, she brings a unique perspective and a keen attention to detail to every project she undertakes with her creativity and passion for delivering impactful content strategies for success. Let's connect on Linkedin: https://www.linkedin.com/in/areeba-bhatti/
Unlock Benefits

Become a Community Member

SIMPLIFY SETUP, MAXIMIZE EFFICIENCY!
Setting up CyberPanel is a breeze. We’ll handle the installation so you can concentrate on your website. Start now for a secure, stable, and blazing-fast performance!