19 min read
YAML Comments: How to Write, Use, and Format Comments in YAML Files
YAML comments make configuration files easier to understand, maintain, and troubleshoot by allowing developers to add explanations without affecting how the configuration is processed. Whether you are working with Docker Compose, Kubernetes, Ansible, GitHub Actions, or other YAML-based configuration files, understanding YAML comments is essential for writing clean and readable code. YAML uses the hash symbol (#) to indicate a comment, allowing you to document configuration settings, explain complex values, temporarily disable certain lines, and provide useful information for other developers. In this guide, you will learn what YAML comments are, how to write comments in YAML, how to use single-line and inline comments, whether YAML supports multiline comments, and how to avoid common formatting and indentation errors. You will also learn how to validate your YAML files using the CC0deLearner YAML Validator to identify syntax problems and ensure your configuration files follow valid YAML formatting rules.
What Are YAML Comments?
YAML comments are explanatory notes written inside a YAML file that are ignored during normal YAML data parsing. They help developers describe configuration options, explain specific values, provide instructions, and document important information about a project.
Unlike actual YAML data, comments do not create keys, values, lists, or objects. They exist only to make the source file easier for humans to understand.
The YAML comment symbol is the hash character (#). Anything following this character on a comment line is treated as a comment, provided the character appears in a position where YAML recognizes it as a comment indicator.
YAML Comment Syntax
The YAML comment syntax is straightforward. You simply add the # symbol before the text you want to write as a comment.
For example:
# This is a YAML comment
name: John
age: 25
city: LondonIn this example, the first line contains a comment, while the remaining lines contain actual YAML data.
You can also add comments next to configuration values:
name: John # User's full name
age: 25 # User's age
active: true # Account statusThese examples demonstrate how YAML comments work without changing the underlying configuration values.
How to Write Comments in YAML
Learning how to write comments in YAML is important for anyone working with configuration files. YAML does not require complicated comment declarations or special opening and closing tags. You only need the # character.
There are several ways to add comments depending on where you want to place them.
Single-Line YAML Comments
Single-line YAML comments are the most common type of comments. They allow you to write an explanation on a separate line before or after a configuration setting.
Example:
# Application configuration
app:
name: MyApplication
version: 1.0
environment: productionHere, the comment explains the purpose of the configuration section.
You can write multiple single-line comments when you need to explain several settings:
# Database configuration
# These settings connect the application to the database
database:
host: localhost
port: 3306
username: adminEach comment begins with the YAML comment symbol (#).
Inline Comments in YAML
Inline comments in YAML appear on the same line as a configuration value. They are useful when you want to explain a particular setting without creating additional lines.
Example:
server:
host: localhost # Local development server
port: 8080 # Application port
debug: true # Enable debuggingInline comments improve YAML readability by keeping explanations close to the values they describe.
However, avoid writing excessively long inline comments because they can make configuration files difficult to read, particularly on smaller screens.
Multiline Comments in YAML
One common question among developers is whether YAML supports multiline comments.
The answer is that YAML does not provide a dedicated multiline or block comment syntax. Unlike programming languages that support comment blocks, YAML uses the # symbol for individual comment lines.
However, you can create multiline comments by placing the comment symbol at the beginning of every line.
Example:
# Application settings
# The following configuration controls
# the application environment and server
# connection information.
app:
name: MyApplication
environment: productionThis approach is commonly used when writing longer explanations.
Can YAML Have Multiline Comments?
Yes, you can write comments across multiple lines, but each line must begin with # (or otherwise contain a valid YAML comment indicator in the appropriate position).
Does YAML Support Block Comments?
No. YAML does not have a dedicated block comment structure such as /* ... */ in JavaScript or ''' ... ''' in Python.
If you want to comment out several lines, add # to each line individually.
YAML Comments Examples for Different Data Structures
YAML supports different data structures, including arrays, lists, dictionaries, and nested objects. You can add comments to these structures to explain how they work.
YAML Comments in Arrays
Arrays contain collections of values. In YAML, these are commonly represented using sequences.
Example:
# Available programming languages
languages:
- Python
- JavaScript
- PHP
- JavaYou can also add comments between array elements:
languages:
- Python
# Frontend programming language
- JavaScript
- PHPComments do not become array elements.
YAML Comments in Lists
YAML lists are useful for representing multiple items under one key.
Example:
# Website navigation menu
menu:
- Home
- About
- Services
- ContactYou can add comments to explain individual list items:
services:
- SEO
# Website development services
- Web Development
- Content WritingThe comments are ignored when the YAML data is parsed.
YAML Comments in Dictionaries
Dictionaries contain key-value pairs and are commonly used for configuration settings.
Example:
# User information
user:
name: John
email: john@example.com
role: administratorComments can describe the purpose of a dictionary or explain individual values.
YAML Comments in Nested Objects
Nested objects contain multiple levels of configuration settings. Comments help developers understand how different sections relate to each other.
Example:
# Main application settings
application:
name: MyApp
database:
# Database connection details
host: localhost
port: 3306
security:
# Security configuration
authentication: true
encryption: trueNotice that comments are positioned according to the structure of the YAML document.
YAML Comments in Strings
Comments in YAML strings require special attention because the # character does not always represent a comment.
For example:
message: "Welcome to #CC0deLearner"Here, the hash character is part of the string rather than a comment.
Another example:
message: Welcome to YAML # This is a commentIn this example, the comment begins after the unquoted string value because the hash character is preceded by whitespace.
If you need to include a hash character inside a string, use quotation marks where appropriate.
YAML Comments in Block Scalars
YAML block scalars allow developers to write multiline string values using the | and > indicators.
Example:
description: |
This application provides
website development services.
It supports multiple features.You can add comments outside the block scalar:
# Application description
description: |
This application provides
website development services.
It supports multiple features.Be careful when placing the # symbol inside a block scalar. It becomes part of the string rather than a YAML comment.
YAML Comment Rules, Placement, and Indentation
Correct YAML comment placement is important because YAML depends heavily on whitespace and indentation to represent its data structures.
Although comments do not become data values, they should still be positioned carefully to keep the file understandable.
YAML Comment Placement
You can generally place YAML comments:
Before a key-value pair.
After a configuration value.
Between list items.
Before a nested object.
Above a complete configuration section.
Inside configuration files to explain individual settings.
Example:
# Main server configuration
server:
host: 127.0.0.1
port: 8080 # Server port
# Security settings
security:
enabled: true
ssl: falseYAML Comments and Indentation
YAML comments can appear at different indentation levels. However, aligning comments with the relevant configuration section improves readability.
Example:
application:
name: MyApp
# Database settings
database:
host: localhost
port: 3306Avoid unnecessary indentation and inconsistent spacing.
Incorrect indentation in actual YAML data can result in YAML indentation errors and parsing failures. Comments themselves are generally ignored by the parser, but their placement should not make the document confusing.
YAML Comment Limitations
YAML comments have several limitations:
YAML does not support dedicated block comments.
Comments are not part of the parsed YAML data model.
Some YAML parsers discard comments when loading and re-serializing documents.
Comments cannot be used as actual configuration values.
The
#character inside quoted strings is not automatically a comment.Comments inside block scalar content are treated as string content.
Understanding these limitations helps developers avoid unexpected behavior.
YAML Comments in Popular Development Tools and Frameworks
YAML is widely used in software development, automation, application deployment, and configuration management. Developers frequently add comments to explain configuration settings in different tools.
YAML Comments in Docker Compose
Docker Compose uses YAML files to define application services, networks, and volumes.
Example:
# Docker Compose configuration
services:
web:
image: nginx:latest
ports:
- "8080:80" # Expose application port
restart: alwaysIf you want to know how to comment Docker Compose YAML, simply use # before the explanation or add an inline comment after a valid configuration value.
YAML Comments in Kubernetes
Kubernetes uses YAML manifests to define resources such as Pods, Deployments, and Services.
Example:
# Kubernetes deployment configuration
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 3 # Number of application replicasIf you want to know how to comment in Kubernetes, use the same YAML comment syntax. Kubernetes does not introduce a separate comment system.
YAML Comments in Ansible
Ansible uses YAML for playbooks, roles, and automation tasks.
Example:
# Ansible playbook
- name: Install Nginx
hosts: webservers
tasks:
# Install the web server
- name: Install Nginx package
apt:
name: nginx
state: presentWhen learning how to comment Ansible playbooks, remember that YAML comments are ignored during playbook execution.
YAML Comments in GitHub Actions
GitHub Actions uses YAML files to define automated workflows.
Example:
# GitHub Actions workflow
name: CI Pipeline
on:
push:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
# Checkout repository
- uses: actions/checkout@v4
# Run application tests
- run: npm testComments can help explain different steps in your GitHub Actions workflow.
YAML Comments in CI/CD Pipelines
CI/CD pipelines frequently use YAML configuration files to automate testing, building, and deployment.
Example:
# CI/CD pipeline configuration
stages:
- build
- test
- deploy
# Application deployment settings
deploy:
stage: deploy
script:
- echo "Deploying application"Adding comments to CI/CD pipelines makes automation workflows easier to understand and maintain.
YAML Comments in Python YAML Files
Python developers commonly use YAML libraries such as PyYAML to read and write YAML configuration files.
Example:
# Python application configuration
database:
host: localhost
port: 5432Python can load YAML data using a YAML parser, but standard loading operations generally do not preserve comments in the resulting Python objects.
If you need to retain comments while editing YAML files programmatically, consider a comment-preserving library such as ruamel.yaml.
YAML Comments in YAML Front Matter
YAML front matter is commonly used in static site generators and Markdown-based content management systems.
Example:
---
# Blog post metadata
title: Learning YAML
description: A beginner's guide to YAML
author: John
---Comments can help explain metadata fields without becoming part of the front matter’s actual values.
How to Add YAML Comments in Different Code Editors
Most modern code editors support YAML syntax highlighting and provide shortcuts for commenting and uncommenting lines.
YAML Comments in VS Code
Visual Studio Code provides built-in support for commenting lines through keyboard shortcuts.
To learn how to add comments in VS Code YAML:
Open your YAML file.
Select the line or multiple lines.
Press
Ctrl + /on Windows or Linux.Press
Cmd + /on macOS.The editor will add or remove comment symbols where supported.
This is also useful when learning how to comment multiple lines in YAML.
YAML Comments in IntelliJ IDEA
IntelliJ IDEA supports YAML editing, syntax highlighting, and comment shortcuts.
You can select one or multiple lines and use the line-comment shortcut:
Windows/Linux:
Ctrl + /macOS:
Cmd + /
The editor automatically adds or removes the comment symbol.
YAML Comments in Notepad++
Notepad++ also allows developers to work with YAML files.
You can manually add # at the beginning of a line or use the available commenting commands when supported by the selected language configuration.
Always check the resulting file to ensure that the comment placement does not affect the YAML structure.
How to Uncomment YAML Lines
Uncommenting YAML means removing the comment symbol from a line so that the content becomes active YAML data again.
For example, before uncommenting:
# server:
# port: 8080After uncommenting:
server:
port: 8080You can remove the # characters manually or use the comment shortcut in your code editor.
YAML Comments vs Other Programming Language Comments
Different programming languages use different comment conventions. Understanding these differences helps prevent syntax mistakes when switching between file formats.
YAML Comments vs JSON Comments
YAML supports comments using the # symbol.
JSON, according to its standard syntax, does not support comments.
YAML example:
# Application name
name: MyAppJSON example:
{
"name": "MyApp"
}Standard JSON parsers may reject files containing comment syntax.
YAML Comments vs XML Comments
XML uses <!-- --> to define comments.
Example:
<!-- Application configuration -->
<application>
<name>MyApp</name>
</application>YAML uses the simpler # symbol instead.
YAML Comments vs Markdown Comments
Markdown does not define a universal visible comment syntax in its core formatting rules, but many Markdown processors support HTML comments.
Example:
<!-- This is a Markdown comment -->YAML comments use #, which is different from HTML-style comments.
YAML Comments vs Python Comments
Python uses # for single-line comments, just like YAML.
Example:
# This is a Python commentname = "John"However, Python and YAML have different syntax rules and parsing behavior. Python also supports multiline string literals, but these should not be confused with dedicated block comments.
YAML Comment Escaping and Special Characters
YAML comment escaping can be confusing when working with strings containing special characters.
The # symbol is treated as a comment indicator when it appears in an appropriate context. However, when it is included inside a quoted string, it becomes part of the actual value.
Example:
website: "https://example.com/#services"The hash symbol is part of the URL and is not treated as a comment.
Similarly:
color: "#FF3838"Here, the hash symbol represents a hexadecimal color value.
A common mistake is adding a space before the hash character in an unquoted value when the intention is to include it as part of the value.
Correct:
color: "#FF3838"Understanding YAML comment escaping and string quotation rules can help prevent parsing problems.
YAML Comments Best Practices for Developers
Following YAML comments best practices improves code readability, documentation quality, and long-term maintainability.
Here are some useful recommendations.
1. Write Clear and Meaningful Comments
Comments should explain why a configuration exists or what a particular setting controls.
Avoid unnecessary comments that simply repeat the configuration value.
2. Keep Comments Relevant
Only add comments when they provide useful information. Too many comments can make YAML files unnecessarily long.
3. Use Consistent Formatting
Follow a consistent style when adding comments to different configuration sections.
For example:
# Database configuration
database:
host: localhost
port: 3306
# Application configuration
application:
name: MyApp
debug: false4. Explain Complex Configuration Settings
Some configuration values may not be immediately understandable. Add comments to explain their purpose and expected behavior.
5. Avoid Using Comments as Permanent Documentation Storage
Comments are useful for short explanations, but larger technical documentation should be maintained separately.
6. Do Not Store Sensitive Information
Never include passwords, API keys, authentication tokens, or private credentials in YAML comments.
Comments remain visible in source files and may be committed to public repositories.
7. Validate YAML After Editing
Even when comments do not affect the parsed data, incorrect YAML formatting elsewhere in the document can cause parsing errors.
Use a YAML validator to check your file before using it in production.
YAML Comment Parsing, Preservation, and Stripping
Understanding how YAML parsers handle comments is important when editing configuration files programmatically.
YAML Comment Parsing
A YAML parser reads the document and converts its content into a structured data representation.
During normal parsing, comments are generally ignored because they are not part of the YAML data model.
For example:
# User configuration
name: John
age: 25The parsed data contains the name and age values, not the explanatory comment.
YAML Comment Preservation
YAML comment preservation depends on the parser or library being used.
Some YAML libraries discard comments when converting documents into programming language objects.
If you modify and save a YAML file using a parser that does not preserve comments, the original comments may disappear.
Developers who need YAML comment preservation can explore libraries designed to retain formatting and comments, such as ruamel.yaml.
YAML Comment Stripping
YAML comment stripping refers to removing comments from YAML source files.
Some applications or processing workflows remove comments when generating optimized configuration files.
However, stripping comments should be done carefully because comments may contain useful explanations for future developers.
YAML Comment Generators and YAML Comment Validators
YAML comment generators and YAML comment validators can help developers work with YAML files more efficiently.
A YAML comment generator may help format explanatory text or produce comment lines for documentation purposes. However, it is important to understand that YAML itself does not require a special generator to create comments.
You can simply write the # symbol manually.
Similarly, YAML comment validators are not a separate standardized category of YAML validation. Most YAML validators check the complete document for syntax and structural problems rather than checking whether comments are meaningful.
A YAML validator can help detect issues such as:
Invalid YAML syntax.
Incorrect indentation.
Missing colons.
Improper quotation marks.
Invalid sequences and mappings.
Incorrectly formatted configuration values.
Validate Your YAML Comments and Configuration Files
CC0deLearner YAML Validator
Writing YAML comments is simple, but maintaining a syntactically valid YAML document is equally important. Use the CC0deLearner YAML Validator to check your YAML configuration files and identify formatting or syntax problems before using them in your projects.
Validate Your YAML File
How to Troubleshoot YAML Comment-Related Errors
Although YAML comments are generally ignored during parsing, mistakes involving comment placement, quotation marks, and indentation can cause confusion.
Here are some common issues and their solutions.
1. Incorrect Comment Placement
Consider this example:
name: John# User nameWithout whitespace before the #, it may be interpreted as part of the plain scalar rather than a comment.
A clearer version is:
name: John # User name2. Using Unsupported Block Comment Syntax
Some developers try to use programming language comment structures:
/*
This is a comment
*/This is not valid YAML comment syntax.
Use:
# This is a comment
# This is another comment3. Incorrect YAML Indentation
Example:
server:
host: localhost
port: 8080The inconsistent indentation can produce YAML indentation errors.
Correct version:
server:
host: localhost
port: 80804. Confusing Comments with String Values
Example:
message: Welcome # to YAMLThe text after the hash is a comment, not part of the message value.
If you want the complete message, write:
message: "Welcome # to YAML"5. Unexpected Comment Removal
If comments disappear after saving a YAML file through a programming library, the library may not support YAML comment preservation.
Consider using a comment-preserving YAML library when comments need to remain in the original file.
6. How to Troubleshoot YAML Comment-Related Errors
To troubleshoot YAML comment-related errors, check the placement of the hash symbol, quotation marks, indentation, and block scalar formatting. If you still encounter YAML syntax errors, run the complete document through a YAML validator to identify the location and nature of the problem.
Frequently Asked Questions About YAML Comments
1. What Are YAML Comments?+
YAML comments are explanatory notes added to YAML files using the # symbol. They help developers document configuration settings and explain code without affecting the parsed YAML data.
2. How Do You Write Comments in YAML?+
Write the # symbol before your comment text. For example:
3. Can You Add Comments to YAML Files?+
Yes. You can add comments to YAML files by using the hash symbol. Comments can appear on separate lines or after configuration values.
4. Can YAML Have Multiline Comments?+
YAML does not support dedicated block comments, but you can create multiline comments by placing # at the beginning of each comment line.
5. Does YAML Support Block Comments?+
No. YAML does not provide a native block comment syntax. Use multiple single-line comments instead.
6. How Do You Comment Multiple Lines in YAML?+
Select the lines in your editor and use its line-comment shortcut, or manually add # at the beginning of each line.
7. How Do You Uncomment YAML Lines?+
Remove the # symbol from the beginning of each commented line. Most code editors also provide a keyboard shortcut to uncomment selected lines.
8. Are YAML Comments Included in Parsed Data?+
No. Standard YAML parsing generally ignores comments, so they are not included in the resulting data structure.
9. Can You Add Comments Inside YAML Lists?+
Yes. You can add comments before, after, or between list items using the # symbol.
10. Do YAML Comments Affect Indentation?+
Comments do not represent data nodes, but their placement should follow a consistent indentation style. Incorrect indentation in actual YAML values can cause parsing errors.
11. Can You Use Comments in Docker Compose and Kubernetes?+
Yes. Both Docker Compose and Kubernetes use YAML syntax, so you can use standard YAML comments in their configuration files.
12. Which Symbol Is Used for YAML Comments?+
The hash symbol (#) is used for YAML comments.
13. How Can I Check Whether My YAML File Is Valid?+
You can use an online YAML validator to check syntax, indentation, and structural formatting. The CC0deLearner YAML Validator provides a convenient way to validate YAML files.
Conclusion
YAML comments are an important part of writing understandable, maintainable, and well-documented configuration files. By using the hash symbol (#), developers can add single-line comments, inline comments, and multiline explanations without changing the actual YAML data. Although YAML does not support dedicated block comments, placing the comment symbol on each line provides a simple alternative.
Whether you are writing YAML for Docker Compose, Kubernetes, Ansible, GitHub Actions, Python YAML files, or CI/CD pipelines, following consistent YAML comment rules and formatting practices can make your projects easier to manage. Remember to pay attention to comment placement, quotation marks, indentation, and special characters to avoid common YAML syntax errors.
Before deploying or sharing your configuration, validate the complete document to ensure that it follows the correct YAML syntax. Visit the CC0deLearner YAML Validator to check your YAML files, identify formatting issues, and create cleaner, more reliable configuration files.
