20 min read
How to Write a YAML File: Complete Beginner’s Guide With Syntax, Examples, and Best Practices
Learning how to write a YAML file is useful for developers, DevOps engineers, system administrators, and beginners who want to manage application settings, automate workflows, or configure modern software applications. YAML is a human-readable data serialization language commonly used in Docker Compose, Kubernetes, GitHub Actions, Ansible, and CI/CD pipelines. Its simple structure makes configuration easier to read, write, and maintain.
Whether you want to create your first YAML configuration file, understand YAML syntax, write nested structures, or troubleshoot formatting errors, learning its basic rules will help you avoid common mistakes. Unlike programming languages, YAML focuses on representing structured data through indentation, key-value pairs, lists, and mappings.
In this beginner YAML tutorial, you will learn how to create a YAML file, understand its syntax, work with different data types, write practical configuration examples, and validate your YAML syntax using an online tool. By following this step-by-step YAML guide, you can learn how to write clean, readable, and error-free YAML configuration files.
What Is a YAML File?
YAML stands for YAML Ain’t Markup Language. It is a human-readable data serialization language designed to represent structured information in a simple format. Developers use YAML to store configuration settings, exchange data between applications, and define automated processes.
A YAML file typically contains key-value pairs, lists, nested mappings, and other structured information. Its straightforward syntax makes it easier for humans to understand compared to some other data formats.
What Is YAML Used For?
YAML is widely used in software development and configuration management. Some common applications include:
Docker Compose configuration files.
Kubernetes YAML manifests.
GitHub Actions workflow files.
Ansible playbooks.
Application settings and environment variables.
Database configuration.
API configuration.
CloudFormation templates.
GitLab CI pipelines.
YAML front matter in content management systems.
Why Use YAML Files?
There are several reasons developers prefer YAML for configuration tasks.
Readability: YAML uses indentation and simple key-value structures, making configuration files easier to understand.
Simplicity: You do not need complicated syntax to define lists, mappings, and nested structures.
Flexibility: YAML supports strings, numbers, booleans, null values, and complex data structures.
Compatibility: Many modern development tools support YAML through built-in or third-party YAML parsers.
Automation: YAML for automation is particularly useful in DevOps environments, where configuration files define deployment processes and application behavior.
How Does YAML Work?
YAML works by representing information through structured data elements. A YAML parser reads the file and converts its contents into data structures that an application can understand.
For example:
name: CCodeLearner
category: Education
active: trueThis example contains three YAML key-value pairs. The keys are name, category, and active, while their corresponding values describe the website’s information.
How to Write a YAML File Step by Step
If you are wondering how to write a YAML file, start with a basic text editor and follow the correct indentation and formatting rules. You do not need specialized software to create a YAML file.
Step 1: Choose a Text Editor
You can create YAML files using several text editors and development environments.
Popular options include:
Visual Studio Code (VS Code).
Notepad.
Notepad++.
Sublime Text.
Vim.
Online YAML editors.
VS Code is particularly useful because it supports syntax highlighting, extensions, and YAML language server features.
Step 2: Create a New YAML File
Create a blank file in your preferred editor. Save it using either the .yaml or .yml file extension.
For example:
config.yamlOr:
docker-compose.ymlBoth extensions represent the same YAML file format. The .yaml extension is more descriptive, while .yml is also widely used in development tools.
Step 3: Write Your First YAML Content
Start by adding a few key-value pairs.
website: CCodeLearner
language: English
category: Programming
published: trueThis is an example of how to write a simple YAML file.
Each line contains a key and its corresponding value. A colon separates the key from the value, followed by a space.
Step 4: Save Your YAML File
Once you finish writing the content, save your file with the .yaml or .yml extension.
Make sure the editor does not accidentally save it as a .txt file.
Step 5: Validate Your YAML Syntax
Before using your file in an application, check whether its structure and syntax are correct.
You can use the CCodeLearner online YAML validator:
Validate Your YAML File Online
Paste your YAML content into the tool to check for formatting and syntax problems. YAML validation can help identify issues before they cause problems in your application or deployment workflow.
Understanding YAML Syntax and Formatting Rules
Understanding YAML syntax is essential if you want to create configuration files without errors. YAML uses indentation to represent relationships between different elements.
YAML Key-Value Pairs
Key-value pairs are the foundation of YAML configuration files.
name: John
age: 25
country: PakistanIn this example:
nameis a key.Johnis its value.ageis another key.25is its value.
To understand how to write multiple key-value pairs in YAML, remember that each pair generally appears on a separate line.
YAML Indentation Rules
YAML indentation defines the relationship between parent and child elements.
Consider this example:
website:
name: CCodeLearner
category: Programming
language: EnglishHere, name, category, and language are nested under website.
Correct indentation is one of the most important YAML best practices.
YAML Spaces vs Tabs
YAML uses spaces for indentation. Tabs should not be used to indent YAML content.
For example, this is correct:
server:
host: localhost
port: 8080Inconsistent indentation can produce parsing errors or unexpected structures.
A common approach is to use two spaces for each indentation level, although the important requirement is consistency.
YAML Data Types
YAML supports different data types that help represent structured information.
YAML Strings
Strings represent text values.
name: CCodeLearner
description: Learn programming onlineYou can also use single or double quotation marks.
message: "Welcome to CCodeLearner"
category: 'Programming Tutorials'YAML Numbers
Numbers represent numeric values.
age: 25
price: 99.99
quantity: 10YAML Booleans
Boolean values represent true or false conditions.
published: true
maintenance: falseYAML Null Values
Null represents an empty or undefined value.
author: null
description: nullYou can also use ~ to represent null in YAML.
How to Write YAML Lists, Arrays, and Nested Structures
YAML supports different structures for organizing information. Understanding lists, arrays, sequences, dictionaries, mappings, and objects will help you create more advanced configuration files.
YAML Lists and Sequences
A YAML list is written using a hyphen followed by a space.
languages:
- Python
- JavaScript
- PHP
- JavaThis structure represents a YAML sequence containing four items.
Sequences are useful when you need to store multiple values under one key.
YAML Dictionaries and Mappings
A YAML mapping stores information as key-value pairs.
student:
name: Ahmed
age: 22
course: ProgrammingThe student mapping contains three properties.
Mappings are similar to dictionaries in Python and objects in JavaScript.
YAML Objects and Nested YAML Structures
Nested YAML allows you to organize complex information through multiple indentation levels.
website:
name: CCodeLearner
settings:
language: English
theme: light
author:
name: Admin
role: EditorThis example contains nested mappings.
If you want to understand how to write nested YAML, remember that child elements must be indented consistently under their parent keys.
How to Write a YAML List of Objects
You can combine sequences and mappings to create lists of objects.
users:
- name: Ahmed
role: Admin
active: true
- name: Sara
role: Editor
active: falseThis structure is particularly useful for application settings, user records, and automation configurations.
YAML Block Style and Flow Style
YAML supports two common presentation styles: block style and flow style.
YAML Block Style
Block style uses indentation and multiple lines to represent data.
database:
host: localhost
port: 5432
username: adminThis format is easier to read when working with large configuration files.
YAML Flow Style
Flow style uses square brackets and curly braces to represent sequences and mappings.
languages: [Python, JavaScript, PHP]
database: {host: localhost, port: 5432}Flow style is useful for short structures, but block style is generally easier to maintain in larger configuration files.
How to Write YAML Comments and Multiline Strings
Comments and multiline strings make YAML files easier to understand and organize.
YAML Comments
YAML comments begin with the # character.
# Website configuration
name: CCodeLearner
# Website status
active: trueComments are ignored by YAML parsers and are useful for explaining configuration settings.
YAML Multiline Strings
YAML supports multiline text through block scalars.
There are two important indicators:
|preserves line breaks.>folds most line breaks into spaces.
Example:
description: |
CCodeLearner provides programming tutorials.
Learn YAML, Python, and JavaScript.Folded style:
description: >
CCodeLearner provides programming tutorials
for beginners and developers.These YAML block scalars are useful for descriptions, messages, and other long text values.
Advanced YAML Features: Anchors, Aliases, Tags, and Document Separators
YAML includes advanced features that help developers manage reusable and complex data.
YAML Document Separators
The three-hyphen marker --- indicates the beginning of a YAML document.
---
name: CCodeLearner
category: Education
---
name: Programming Tutorials
active: trueThe three-dot marker ... can indicate the end of a YAML document.
YAML Anchors and Aliases
Anchors and aliases allow you to reuse previously defined YAML content.
default: &settings
language: English
theme: light
website:
<<: *settings
name: CCodeLearnerHere, &settings defines an anchor, while *settings references it through an alias.
YAML Tags
YAML tags provide additional information about how a value should be interpreted.
For example:
date: !!str 2026-11-02The !!str tag explicitly indicates that the value should be treated as a string.
YAML Schema
A YAML schema defines the rules used to interpret YAML data types and values. Different YAML parsers may support different schemas or schema configurations.
Understanding the schema is important when working with dates, booleans, numbers, and other values that may be interpreted differently depending on the parser.
How to Create a YAML File in VS Code and Notepad
You can create YAML files in almost any text editor.
How to Create a YAML File in VS Code
Follow these steps:
Open Visual Studio Code.
Select File and choose New Text File.
Write your YAML configuration.
Save the file with a
.yamlextension.Install a YAML extension if you need additional validation and autocomplete features.
Review indentation and syntax highlighting.
VS Code can also integrate with a YAML language server to provide suggestions, schema support, and diagnostic information.
How to Create a YAML File in Notepad
To create a YAML file in Notepad:
Open Notepad on Windows.
Enter your YAML content.
Select File and click Save As.
Enter a filename such as
config.yaml.Choose All Files from the Save as type option.
Save the file.
Check that Windows has not added an extra .txt extension.
YAML File Examples: Practical Configuration Examples
Understanding practical YAML file examples makes it easier to apply your knowledge to real-world development projects.
Sample YAML Configuration
application:
name: CCodeLearner
version: 1.0
environment: production
settings:
debug: false
language: English
database:
host: localhost
port: 5432
username: adminThis sample YAML configuration demonstrates application settings, environment information, and database configuration.
YAML in Docker Compose
Docker Compose uses YAML configuration files to define and manage multiple containers.
The commonly used filename is docker-compose.yml.
services:
web:
image: nginx:latest
ports:
- "8080:80"
database:
image: mysql:8
environment:
MYSQL_ROOT_PASSWORD: exampleThis example defines two services: a web server and a database.
YAML in Kubernetes
Kubernetes YAML manifests define resources such as pods, deployments, and services.
apiVersion: v1
kind: Pod
metadata:
name: example-pod
spec:
containers:
- name: nginx
image: nginx:latestKubernetes uses these YAML configuration files to describe the desired state of resources.
YAML in GitHub Actions
GitHub Actions uses YAML files to define automated workflows.
A common filename is GitHub Actions workflow.yml, typically stored in the .github/workflows/ directory.
name: Test Workflow
on:
push:
branches:
- main
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Display message
run: echo "Workflow started"This example demonstrates how YAML in GitHub Actions defines triggers, jobs, and workflow steps.
YAML in Ansible
Ansible uses YAML to define automation tasks through Ansible playbooks.
---
- name: Configure web server
hosts: servers
tasks:
- name: Install Nginx
apt:
name: nginx
state: presentAnsible playbooks are commonly used for server configuration and infrastructure automation.
YAML in CI/CD Pipelines
YAML in CI/CD pipelines helps automate testing, building, and deployment processes.
It allows developers to define workflow stages, jobs, dependencies, and execution instructions.
YAML in GitLab CI is another example:
stages:
- build
- test
build:
stage: build
script:
- echo "Building application"
test:
stage: test
script:
- echo "Testing application"YAML in CloudFormation
AWS CloudFormation supports YAML templates for defining cloud infrastructure.
AWSTemplateFormatVersion: '2010-09-09'
Description: Example CloudFormation Template
Resources:
MyBucket:
Type: AWS::S3::BucketThis example defines an Amazon S3 bucket resource.
How to Write YAML Files in Python and JavaScript
YAML can be processed programmatically using libraries and parsers in different programming languages.
Python YAML File and PyYAML
PyYAML is a popular Python library for reading and writing YAML files.
Install it using:
pip install pyyamlTo read a YAML file in Python:
import yamlwith open("config.yaml", "r") as file: data = yaml.safe_load(file)print(data)To write YAML in Python:
import yamldata = { "name": "CCodeLearner", "active": True, "category": "Programming"}with open("config.yaml", "w") as file: yaml.safe_dump(data, file)This demonstrates how YAML in Python can be used to read and generate configuration files.
JavaScript YAML Parser
JavaScript developers can use libraries such as yaml to parse and generate YAML content.
Install the package:
npm install yamlRead YAML content:
const YAML = require('yaml');
const content = `
name: CCodeLearner
active: true
category: Programming
`;
const data = YAML.parse(content);
console.log(data);A JavaScript YAML parser converts YAML content into JavaScript data structures, making it useful for web applications and development tools.
YAML vs JSON vs XML vs TOML
YAML is not the only format used for storing structured data. JSON, XML, and TOML are also widely used.
| Feature | YAML | JSON | XML | TOML |
|---|---|---|---|---|
| Readability | High | High | Moderate | High |
| Comments | Supported | Not supported in standard JSON | Supported | Supported |
| Indentation | Important for structure | Optional | Optional | Important for readability |
| Data structures | Lists and mappings | Arrays and objects | Elements and attributes | Tables and key-value pairs |
| Common usage | Configuration | APIs and data exchange | Documents and integrations | Application configuration |
YAML vs JSON
YAML is generally easier to read when working with large configuration files because it supports comments and indentation-based structures.
JSON is commonly used for APIs and data exchange because of its widespread programming language support.
YAML can also represent many of the same structures as JSON, making conversion between the two formats possible.
YAML vs XML
XML uses opening and closing tags to represent structured data, while YAML uses indentation and key-value pairs.
YAML is often more compact for configuration management, whereas XML is useful in document-oriented applications and systems that depend on XML-based standards.
YAML vs TOML
TOML is another human-readable configuration format. It uses tables, key-value pairs, and sections.
YAML provides more flexible structures for complex nested data, while TOML can be easier to understand for certain application configuration requirements.
How to Convert JSON to YAML and YAML to JSON
Developers often need to convert structured data between different formats.
How to Convert JSON to YAML
To convert JSON to YAML, use a compatible converter or programming library.
For example, the following JSON:
{
"name": "CCodeLearner",
"active": true
}Can be represented in YAML as:
name: CCodeLearner
active: trueHow to Convert YAML to JSON
YAML can also be converted into JSON using a YAML parser.
For example:
name: CCodeLearner
active: trueProduces:
{
"name": "CCodeLearner",
"active": true
}Always verify the resulting data because some YAML features do not have direct equivalents in JSON.
How to Validate YAML Syntax Online
Writing YAML correctly is important, but even a small formatting mistake can prevent an application from reading a configuration file.
A YAML validator online helps identify syntax problems before you use the file.
Why Is YAML Validation Important?
YAML validation checks whether your file follows the expected syntax and structure.
It can help identify:
Incorrect indentation.
Missing colons.
Invalid mappings.
Incorrect list formatting.
Unclosed quotation marks.
Malformed nested structures.
Invalid YAML values.
How to Validate YAML Syntax Using CCodeLearner
If you have created a YAML file and want to check whether it is valid, use the CCodeLearner YAML Validator.
Follow these simple steps:
Visit the CCodeLearner YAML Validator.
Copy your YAML configuration content.
Paste it into the validator.
Run the validation process.
Review any reported syntax errors.
Correct the problems in your original YAML file.
Validate the updated content again.
Using an online YAML validator can save time when working with Docker Compose, Kubernetes, Ansible, and other configuration management tools.
YAML Parser vs YAML Linter vs YAML Formatter
These tools perform different functions.
| Tool | Main Purpose |
|---|---|
| YAML Parser | Reads YAML and converts it into structured data |
| YAML Linter | Checks syntax, formatting, and style issues |
| YAML Formatter | Organizes YAML content into consistent formatting |
| YAML Validator | Checks whether YAML content is syntactically valid |
A YAML online editor may also combine editing, formatting, and validation features.
A YAML generator can help create YAML structures automatically, reducing manual work.
Common YAML Syntax Errors and How to Fix Them
Beginners frequently encounter YAML errors because the format has strict indentation and structural rules.
Understanding common YAML syntax errors will help you troubleshoot problems more efficiently.
Incorrect Indentation
Incorrect:
website:
name: CCodeLearner
category: EducationCorrect:
website:
name: CCodeLearner
category: EducationThe name and category properties should have the same indentation level.
How to Fix YAML Indentation Errors
Use consistent spaces and check the parent-child relationships between elements. Avoid tabs and ensure that nested structures are correctly aligned.
Missing Spaces After Colons
Incorrect:
name:CCodeLearnerCorrect:
name: CCodeLearnerYAML key-value pairs require a space after the colon in this standard mapping format.
Incorrect List Formatting
Incorrect:
languages:
-Python
-JavaScriptCorrect:
languages:
- Python
- JavaScriptEach sequence item should use a hyphen followed by a space.
Incorrect Boolean Values
Incorrect:
active: truCorrect:
active: trueUse valid boolean values supported by the YAML version and parser.
Unquoted Special Characters
Some values containing special characters may need quotation marks.
For example:
message: "Welcome: Learn YAML today"Quoting values can help avoid ambiguity when strings contain characters that have special meanings in YAML.
How to Troubleshoot YAML Errors
When a YAML parser reports an error:
Check the reported line number.
Review indentation around that line.
Check colons, quotation marks, and brackets.
Verify list and mapping structures.
Confirm that tabs have not been used.
Run the content through a YAML linter or validator.
Test the corrected file again.
You can use the CCodeLearner YAML Validator to check your content and identify formatting problems.
YAML Best Practices for Clean and Readable Configuration Files
Following YAML best practices makes your files easier to maintain and reduces the risk of configuration errors.
Use Consistent Indentation
Choose a consistent indentation style throughout your file. Two spaces are commonly used for nested structures.
Use Descriptive Keys
Use meaningful key names that explain what each value represents.
For example:
database_host: localhost
database_port: 5432Add YAML Comments
Use comments to explain complicated configuration options and important settings.
Organize Nested Structures
Group related settings under meaningful parent keys instead of creating unnecessarily complicated structures.
Quote Ambiguous Strings
Quote values containing special characters or strings that might otherwise be interpreted as booleans, numbers, or other data types.
Validate Before Deployment
Always perform YAML validation before using configuration files in production environments.
Protect Sensitive Information
Avoid storing passwords, API keys, and other secrets directly in YAML files. Use environment variables or a dedicated secrets management system.
Use a Consistent File Extension
Choose .yaml or .yml according to your project’s conventions and maintain consistency across your repository.
How to Read and Edit a YAML File
Reading and editing YAML files is straightforward once you understand the structure.
How to Read a YAML File
Open the file in a text editor such as VS Code or Notepad.
Start by identifying the main keys, then review their associated values. Indentation indicates which properties belong to parent structures.
For example:
server:
host: localhost
port: 8080The server key contains two nested properties: host and port.
How to Edit a YAML File
To edit a YAML file:
Open the existing
.yamlor.ymlfile.Locate the configuration value you want to change.
Update the key or value.
Maintain the existing indentation.
Save your changes.
Validate the updated content.
Avoid changing the structure unnecessarily, especially when editing Docker Compose files, Kubernetes YAML manifests, or CI/CD configurations.
Frequently Asked Questions About How to Write a YAML File
1. How Do I Write a YAML File for Beginners?+
Start by creating a text file and saving it with a .yaml extension. Add simple key-value pairs, use spaces for indentation, and organize information using lists and nested mappings. Validate your content before using it.
2. What Does a YAML File Look Like?+
A YAML file typically contains readable key-value pairs, lists, and nested structures.
Example:
3. Is YAML a Programming Language?+
No. YAML is a data serialization language, not a programming language. It is designed to represent structured data and configuration settings rather than execute programming instructions.
4. What Is the Difference Between .yaml and .yml?+
Both .yaml and .yml are commonly used file extensions for YAML files. They represent the same format, and the choice usually depends on project conventions or tool requirements.
5. Can I Create a YAML File in Notepad?+
Yes. You can create a YAML file in Notepad by writing your content and saving it with a .yaml extension. Select All Files in the Save As dialog to avoid accidentally creating a .txt file.
6. How Do I Check Whether a YAML File Is Valid?+
Use a YAML parser, linter, or online validator. Paste your YAML content into the CCodeLearner YAML Validator to check for syntax and formatting problems.
7. Can YAML Store Lists and Nested Objects?+
Yes. YAML supports sequences, mappings, and nested structures. You can use these features to organize complex application settings and configuration data.
8. Is YAML Better Than JSON?+
It depends on the use case. YAML is often preferred for human-readable configuration files because it supports comments and indentation-based structures. JSON is widely used for APIs and data exchange.
9. What Are the Most Common YAML Errors?+
Common problems include incorrect indentation, missing spaces after colons, invalid list formatting, unquoted special characters, and inconsistent data structures.
10. Can YAML Be Used for Automation?+
Yes. YAML is widely used for automation in tools such as Ansible, Docker Compose, GitHub Actions, Kubernetes, and GitLab CI.
Conclusion: Write Clean and Error-Free YAML Files
Learning how to write a YAML file becomes easier when you understand its basic syntax, indentation rules, key-value pairs, data types, lists, mappings, and nested structures. Whether you are creating a simple application configuration or managing complex DevOps workflows, YAML provides a readable and flexible way to organize structured information.
You can create YAML files using VS Code, Notepad, or an online editor. You can also use YAML in Python, JavaScript, Docker Compose, Kubernetes, GitHub Actions, Ansible, and CI/CD pipelines.
However, writing YAML is only one part of the process. You should always check your configuration for formatting and syntax problems before using it in a real application.
If you want to check your YAML content without manually reviewing every line, visit the CCodeLearner YAML Validator. Paste your YAML code, validate its syntax, identify potential errors, and make the necessary corrections.
Start using the validator today to create clean, readable, and error-free YAML configuration files.
