20 min read
How to Create a YAML File: A Complete Step-by-Step Guide for Beginners
YAML is a popular data serialization language used to store configuration settings, organize structured information, and manage application environments. Developers use YAML files in Docker, Kubernetes, GitHub Actions, Ansible, Python, Node.js, and many other development tools. Learning how to create a YAML file is useful for beginners and experienced developers who need a simple, readable way to organize application settings and exchange structured data.
Creating a YAML file is relatively straightforward. You can use a basic text editor such as Notepad or Notepad++, a code editor such as VS Code, or a terminal on Windows, Linux, and macOS. However, understanding YAML syntax, indentation rules, data types, and file structure is important because even a small formatting mistake can cause parsing errors.
In this guide, you will learn how to write YAML code, create and save YAML files, understand their structure, use different data types, and validate YAML syntax. You will also explore practical YAML examples and learn how to identify and fix common YAML errors using the CCODeLearner YAML Validator.
What Is a YAML File?
A YAML file is a human-readable text file that stores structured data using key-value pairs, lists, and nested objects. YAML stands for YAML Ain’t Markup Language. It is commonly used for configuration files because its straightforward structure makes information easy to read, write, and maintain.
The YAML file format uses indentation instead of brackets and complex symbols to organize information. This makes YAML particularly useful for managing application settings, development environments, deployment instructions, and automated workflows.
A YAML file generally uses one of two file extensions:
.yaml.yml
Both extensions represent the same YAML file format and are widely supported by development tools.
Where Are YAML Files Used?
Developers use YAML configuration files across different programming environments and software platforms.
Common applications include:
Docker Compose YAML file for defining containers and services.
Kubernetes YAML manifest for managing deployments, services, and pods.
GitHub Actions workflow YAML for automating development workflows.
Ansible playbook YAML for infrastructure automation.
CI/CD pipeline YAML for continuous integration and deployment.
Application configuration YAML for storing software settings.
Database configuration YAML for defining database connections and options.
Environment variables in YAML for organizing application environment settings.
How to Create a YAML File: Step-by-Step Tutorial
You do not need advanced programming knowledge to create a YAML file. A simple text editor is enough to get started. Follow these steps to create your first YAML document.
Step 1: Choose a Text Editor
The first step is selecting a text editor where you can write YAML syntax. Several applications support YAML files.
You can create a YAML file using:
Notepad on Windows.
Notepad++ for Windows.
Visual Studio Code (VS Code).
Terminal-based text editors on Linux.
TextEdit or code editors on macOS.
For beginners, VS Code is a useful option because it provides syntax highlighting, indentation assistance, and extensions for YAML development.
Step 2: Write Your First YAML Code
Open your preferred editor and enter the following simple YAML example:
name: John
age: 25
city: London
is_student: false
skills:
- HTML
- CSS
- JavaScriptThis sample YAML file contains basic information about a person.
The name, age, city, and is_student fields are YAML key-value pairs. The skills field contains a list of values.
Step 3: Save Your YAML File
After writing the content, save the file using a supported extension.
For example:
config.yamlYou can also use:
config.ymlMake sure you select the appropriate file type or use the correct extension when saving. Some text editors may automatically add .txt to your filename, so check that your file is actually saved as .yaml or .yml.
Step 4: Validate Your YAML File
Writing YAML code is only part of the process. You should also check whether the file follows valid YAML syntax.
An indentation mistake, missing colon, or incorrect quotation mark can make your YAML document invalid.
You can use the free CCODeLearner YAML Validator to check your YAML content. Paste your code into the validator and run the validation to identify formatting or syntax problems.
How to Create a YAML File in Windows, Linux, and macOS
The process of creating YAML files differs slightly depending on your operating system. However, the basic YAML structure and syntax remain the same.
Create YAML File in Windows
Windows users can create YAML files through Notepad, Notepad++, or VS Code.
Using Notepad:
Open Notepad.
Write your YAML content.
Select File and click Save As.
Enter a filename such as
config.yaml.Select All Files as the file type.
Save the document.
Using Notepad++:
Open Notepad++.
Create a new document.
Write your YAML code.
Select Language and choose YAML if available.
Save the file with a
.yamlextension.
Notepad++ provides syntax highlighting, which makes YAML code easier to read and edit.
Create YAML File in Linux
Linux users can create YAML files using terminal-based editors such as Nano or Vim.
For example, use the following command to create a file:
nano config.yamlWrite your YAML content, save the document, and exit the editor.
You can also create an empty YAML file using:
touch config.yamlAfter creating the file, open it in your preferred text editor and add the required configuration.
Create YAML File in macOS
macOS supports several code editors and text editors for YAML development.
You can use VS Code, TextEdit, or terminal-based tools.
To create a YAML file through the terminal, run:
touch config.yamlTo edit the file using Nano, enter:
nano config.yamlWrite your YAML content and save it with the .yaml extension.
Understanding YAML Syntax and Structure
Before creating complex YAML configuration files, you should understand how YAML syntax works. YAML uses a simple structure based on indentation, key-value pairs, lists, and mappings.
YAML Key-Value Pairs
Key-value pairs are the foundation of YAML structure. A key identifies a particular field, while its value contains the associated information.
Example:
website: ccodelearner
language: English
category: ProgrammingHere, website, language, and category are keys, while their corresponding values are strings.
YAML Data Types
YAML supports different data types that help developers organize information.
The most common YAML data types include:
| Data type | Example |
|---|---|
| YAML strings | name: John |
| YAML numbers | age: 25 |
| YAML booleans | active: true |
| YAML null values | address: null |
| YAML lists | colors: [red, blue] |
| YAML mappings | person: {name: John} |
Understanding these data types helps you create accurate and readable configuration documents.
YAML Strings
Strings represent text values in YAML.
name: John
website: "ccodelearner.com"You can write strings without quotation marks in many situations, but quoting strings can help avoid ambiguity.
YAML Numbers
Numbers represent numeric values, including integers and decimal numbers.
age: 25
price: 99.99YAML Booleans
Boolean values represent true or false conditions.
enabled: true
maintenance: falseYAML Null Values
Null values represent missing or empty information.
username: John
phone: nullYou can also use ~ to represent a null value in YAML.
YAML Lists, Arrays, and Sequences
YAML lists are used to store multiple values under a single key. These structures are also called sequences and are commonly compared to arrays in programming languages.
Example:
languages:
- Python
- JavaScript
- PHP
- JavaEach list item begins with a hyphen followed by a space.
YAML sequences can also contain more complex objects:
employees:
- name: John
department: Development
- name: Sarah
department: MarketingYAML Dictionaries and Mappings
YAML dictionaries and mappings organize data through key-value relationships.
Example:
database:
host: localhost
port: 3306
username: adminThe database key contains a nested mapping with three additional key-value pairs.
Nested YAML Objects
Nested YAML objects allow developers to organize related information inside other objects.
company:
name: CCODeLearner
location:
country: Pakistan
city: Peshawar
services:
- Programming Tutorials
- Online ToolsThis structure makes complex information easier to organize.
YAML Indentation Rules You Must Follow
YAML indentation rules are extremely important because indentation defines relationships between different elements.
Unlike JSON, YAML uses whitespace to represent nested structures.
Consider the following example:
website:
name: CCODeLearner
category: EducationThe name and category properties are indented under website.
Follow these YAML best practices when writing indentation:
Use spaces instead of tabs.
Keep indentation consistent throughout the document.
Use two spaces per indentation level as a common convention.
Align related properties at the same indentation level.
Indent nested lists and mappings correctly.
Spaces vs Tabs in YAML
YAML does not allow tab characters for indentation. Always use spaces to define the structure of your document.
Incorrect example:
website:
name: CCODeLearnerCorrect example:
website:
name: CCODeLearnerCommon Indentation Errors in YAML
An indentation error occurs when YAML elements are not aligned correctly.
Incorrect:
services:
web:
image: nginx
ports:
- "80:80"Correct:
services:
web:
image: nginx
ports:
- "80:80"Consistent indentation prevents YAML parsing errors and makes configuration files easier to maintain.
YAML Comments and Document Separators
YAML supports comments that allow developers to explain different sections of a configuration file.
YAML Comments
Comments begin with the # character.
# Website configuration
name: CCODeLearner
# Website settings
status: activeComments are ignored during YAML parsing and do not become part of the resulting data structure.
YAML Document Separators (—)
The three-hyphen sequence --- marks the beginning of a YAML document.
Example:
---
name: John
age: 25
---
name: Sarah
age: 30A single YAML file can contain multiple documents separated by ---. The ... indicator can also mark the end of a YAML document.
YAML Block Scalars and Multiline Strings
YAML block scalars allow developers to store multiline strings without writing everything on one line.
There are two commonly used block scalar indicators.
Literal block scalar (|):
The pipe character preserves line breaks.
description: |
CCODeLearner provides programming tutorials.
Developers can learn different technologies.
Users can explore online developer tools.Folded block scalar (>):
The greater-than symbol generally folds ordinary line breaks into spaces.
description: >
YAML is a readable data serialization format
used for configuration and structured data.These YAML multiline strings are particularly useful for descriptions, documentation, messages, and application settings.
YAML Anchors, Aliases, and Tags
YAML includes advanced features that help developers reuse information and define specific data types.
YAML Anchors and Aliases
Anchors allow you to define reusable YAML content, while aliases allow you to reference that content elsewhere.
Example:
defaults: &default_settings
timeout: 30
retries: 3
development:
<<: *default_settings
environment: development
production:
<<: *default_settings
environment: productionIn this example, &default_settings creates an anchor, while *default_settings references it.
The merge key << is supported by many YAML implementations, although it is not part of the YAML 1.2 core specification.
YAML Tags
YAML tags provide additional information about the data type or how a value should be interpreted.
Example:
number: !!int "100"
message: !!str 100The !!int tag indicates an integer, while !!str indicates a string.
YAML Configuration Examples for Developers
YAML is widely used in software development. Understanding practical YAML configuration examples will help you create files for different platforms.
Docker Compose YAML File
Docker Compose uses YAML files to define application services, networks, and volumes.
Example:
services:
web:
image: nginx:latest
ports:
- "8080:80"
database:
image: mysql:8
environment:
MYSQL_ROOT_PASSWORD: exampleSave this configuration as compose.yaml or docker-compose.yml, depending on your project and Docker Compose version.
Kubernetes YAML Manifest
Kubernetes YAML manifests define resources such as deployments and services.
Example:
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 2
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latestThis example defines a Kubernetes Deployment with two replicas.
GitHub Actions Workflow YAML
GitHub Actions uses YAML files to define automated workflows.
Example:
name: Build Project
on:
push:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Run build
run: echo "Building project"Save the workflow inside the .github/workflows/ directory of your repository.
Ansible Playbook YAML
Ansible uses YAML to define automation tasks and infrastructure management instructions.
Example:
---
- name: Install Nginx
hosts: webservers
become: true
tasks:
- name: Install Nginx package
ansible.builtin.package:
name: nginx
state: presentThis Ansible playbook defines a task that installs Nginx on the selected hosts.
CI/CD Pipeline YAML
CI/CD pipeline YAML files define automated build, testing, and deployment processes.
Different platforms, such as GitHub Actions, GitLab CI/CD, and Azure Pipelines, use YAML-based configuration with their own supported syntax.
Example of a simple pipeline-style configuration:
pipeline:
stages:
- build
- test
- deploy
build:
stage: build
script:
- echo "Building application"
test:
stage: test
script:
- echo "Running tests"This is a conceptual example rather than a complete platform-specific pipeline configuration.
Application and Database Configuration YAML
YAML can also store application configuration YAML and database configuration YAML settings.
Example:
application:
name: my-app
environment: production
debug: false
database:
host: localhost
port: 5432
database: app_db
username: admin
environment_variables:
APP_ENV: production
LOG_LEVEL: infoThis example demonstrates how environment variables in YAML can be organized alongside application and database settings. Avoid storing actual passwords, API keys, or other secrets directly in configuration files.
How to Create a YAML File for Python and Node.js
YAML is not limited to infrastructure tools. Developers can also use YAML files for Python and Node.js applications.
YAML File for Python
Python developers can read YAML files using libraries such as PyYAML.
First, install the library:
pip install pyyamlCreate a file named config.yaml:
application:
name: Python Project
version: 1.0
debug: trueRead the YAML file using Python:
import yamlwith open("config.yaml", "r") as file: data = yaml.safe_load(file)print(data)The safe_load() method is recommended for loading untrusted YAML data because it avoids constructing arbitrary Python objects.
YAML File for Node.js
Node.js developers can use packages such as yaml to read YAML files.
Install the package:
npm install yamlCreate a YAML configuration file:
server:
host: localhost
port: 3000
environment: developmentRead the file using Node.js:
const fs = require("fs");
const YAML = require("yaml");
const file = fs.readFileSync("config.yaml", "utf8");
const config = YAML.parse(file);
console.log(config);This allows Node.js applications to import and use YAML configuration data.
How to Validate YAML Syntax Online
Validating your YAML file before using it in an application helps prevent configuration problems and deployment failures.
A YAML validator checks whether your document follows the expected YAML syntax and identifies errors that may prevent successful parsing.
You can validate YAML files using online tools, command-line utilities, or editor extensions.
Use the CCODeLearner YAML Validator
The CCODeLearner YAML Validator provides a convenient way to check YAML formatting and syntax without installing additional software.
Follow these steps:
Open the CCODeLearner YAML Validator.
Copy your YAML content from your text editor.
Paste the content into the validation area.
Run the validation process.
Review the validation result.
Correct any reported syntax issues.
Validate the updated YAML document again.
This is particularly helpful when working with Kubernetes manifests, Docker Compose files, application configuration files, and other structured YAML documents.
YAML Validator vs YAML Linter vs YAML Parser
These three tools serve related but different purposes.
| Tool | Main purpose |
|---|---|
| YAML validator | Checks whether YAML syntax is valid. |
| YAML linter | Identifies formatting issues and style problems. |
| YAML parser | Reads YAML content and converts it into structured data. |
| YAML formatter | Automatically formats YAML code consistently. |
A validator is useful for identifying syntax errors, while a linter can help enforce coding standards.
How to Check If a YAML File Is Valid
You can check YAML validity through an online validator, a YAML parser, or a development environment.
For example, using Python:
import yamlwith open("config.yaml", "r") as file: try: yaml.safe_load(file) print("Valid YAML file") except yaml.YAMLError as error: print("Invalid YAML:", error)If the YAML parser successfully reads the document, it means the document is syntactically valid according to that parser.
However, syntax validation does not necessarily confirm that the configuration contains all required fields or follows an application’s expected structure. For that, you may also need a YAML schema or application-specific validation.
Common YAML Syntax Errors and How to Fix Them
Even experienced developers sometimes make mistakes when creating YAML documents. Understanding common YAML syntax errors helps you troubleshoot problems quickly.
Missing Colon After a Key
Incorrect:
name John
age: 25Correct:
name: John
age: 25Every mapping key must be separated from its value using a colon.
Incorrect Indentation
Incorrect:
user:
name: John
age: 25Correct:
user:
name: John
age: 25Incorrect List Formatting
Incorrect:
languages:
-Python
-JavaScriptCorrect:
languages:
- Python
- JavaScriptProblems With Special Characters
Some characters have special meanings in YAML. For example, :, #, and certain indicators can cause unexpected parsing behavior when used in plain strings.
To avoid these problems, quote strings when necessary.
Incorrect:
message: Welcome: DevelopersCorrect:
message: "Welcome: Developers"Quote Strings in YAML
Single and double quotation marks can be used to represent strings.
single_quote: 'Hello World'
double_quote: "Hello World"Single-quoted strings generally treat most characters literally, while double-quoted strings support escape characters such as \n for a newline and \t for a tab.
Example:
message: "Hello\nWelcome to CCODeLearner"Understanding escape characters in YAML helps you write strings containing special characters correctly.
How to Fix YAML Parsing Errors
Follow these troubleshooting steps:
Check whether every mapping key has a colon.
Look for indentation errors in YAML.
Replace tabs with spaces.
Check list items and nested objects.
Verify quotation marks and escape characters.
Check whether special characters are quoted appropriately.
Review document separators and YAML tags.
Run the file through a YAML validator.
You can use the online YAML validation tool to identify syntax problems and make troubleshooting easier.
YAML Schema and YAML Specification
A YAML schema defines which data types and structures are allowed in a particular context. Developers often use schemas to validate configuration files against application-specific requirements.
The YAML specification defines how YAML documents should be structured and interpreted.
YAML 1.1 vs YAML 1.2
YAML 1.1 and YAML 1.2 are different versions of the YAML specification.
YAML 1.2 introduced changes to improve compatibility with JSON and make data interpretation more predictable.
One important difference involves boolean values. YAML 1.1 implementations may interpret values such as yes, no, on, and off as booleans. YAML 1.2’s core schema treats true and false as the standard boolean values.
When creating YAML files, check which specification and schema your application supports because different parsers may interpret certain values differently.
YAML Language Server and Extensions for VS Code
Visual Studio Code provides several features that make YAML development easier.
A YAML language server provides editor support such as syntax validation, autocomplete, document formatting, and schema-based assistance.
YAML Extensions for VS Code
The Red Hat YAML extension is a popular choice for working with YAML files in VS Code.
It provides features such as:
YAML syntax highlighting.
Automatic indentation support.
Code completion.
YAML schema validation.
Error highlighting.
Document formatting.
Integration with the YAML language server.
These features can help developers identify errors while writing YAML code instead of waiting until the application attempts to load the configuration.
JSON vs YAML: What Is the Difference?
JSON and YAML are both used to store and exchange structured data. However, their syntax and readability differ.
| Feature | YAML | JSON |
|---|---|---|
| Readability | Human-friendly | Structured and compact |
| Comments | Supported | Not supported in standard JSON |
| Indentation | Defines structure | Used for formatting only |
| Syntax | Uses mappings and sequences | Uses objects and arrays |
| File extensions | .yaml, .yml | .json |
| Common usage | Configuration files | APIs and data exchange |
YAML is often preferred for manually maintained configuration files because it supports comments and has a readable structure. JSON is widely used for APIs and application data exchange.
YAML vs XML
YAML and XML are also used for structured data, but they have different approaches.
XML uses opening and closing tags to define elements, whereas YAML uses indentation, mappings, and sequences.
For example, YAML is generally easier to read for simple configuration files, while XML provides a tag-based structure that may be useful in systems that depend on XML standards.
YAML Best Practices for Beginners
Following YAML best practices makes your configuration files easier to understand, edit, and troubleshoot.
Consider these recommendations:
Use two spaces for indentation.
Never use tabs for indentation.
Keep key names consistent.
Use meaningful property names.
Add YAML comments where explanations are necessary.
Quote strings when special characters or ambiguous values require it.
Avoid unnecessarily complex nested structures.
Use a YAML validator before deploying configuration files.
Follow the relevant YAML schema.
Store sensitive information securely instead of exposing credentials in YAML files.
Keep reusable configuration organized through anchors and aliases where appropriate.
Use a consistent YAML formatter.
Check parser compatibility when working with different YAML versions.
These practices are especially useful when maintaining Docker, Kubernetes, Ansible, and CI/CD pipeline configurations.
How to Open, Read, Import, Convert, and Troubleshoot YAML Files
After creating a YAML file, you may need to open it, read its contents, import it into an application, or convert it into another format.
How to open a YAML file: Open it using Notepad, Notepad++, VS Code, or another compatible text editor.
How to read a YAML file: Understand its indentation, mappings, key-value pairs, lists, and nested structures.
How to import a YAML file: Use the YAML parser or configuration-loading functionality supported by your programming language or application.
How to convert YAML: A YAML to JSON converter can transform YAML data into JSON format. This is useful when working with applications that require JSON instead of YAML.
How to troubleshoot YAML files: Check syntax, indentation, data types, quotation marks, and parser compatibility. Use a validator or linter to identify potential problems.
Frequently Asked Questions About Creating YAML Files
1. How to create a YAML file for beginners?+
Open a text editor, write your configuration using YAML syntax, organize the information with key-value pairs and proper indentation, and save the file using the .yaml or .yml extension.
2. Can I create a YAML file in Notepad?+
Yes. Open Notepad, write your YAML code, and select Save As. Enter a filename ending in .yaml and select All Files as the file type.
3. What is the difference between .yaml and .yml?+
There is no functional difference between .yaml and .yml. Both are commonly used extensions for YAML documents.
4. How do I validate a YAML file online?+
Open an online YAML validator, paste your YAML content, and run the validation. The tool checks the syntax and reports errors when they are detected. You can use the CCODeLearner YAML Validator for this purpose.
5. Why is indentation important in YAML?+
Indentation defines relationships between keys, values, lists, and nested objects. Incorrect indentation can change the document structure or cause parsing errors.
6. Can YAML contain comments?+
Yes. YAML supports comments using the # character. Comments are useful for explaining configuration settings and organizing complex documents.
7. Is YAML better than JSON?+
It depends on your requirements. YAML is often easier for humans to read and maintain, while JSON is widely used for APIs and structured data exchange.
8. Can I use YAML with Python and Node.js?+
Yes. Python supports YAML through libraries such as PyYAML, while Node.js developers can use packages such as yaml to parse and manage YAML configuration files.
9. How do I fix YAML parsing errors?+
Check indentation, colons, quotation marks, list formatting, special characters, and document structure. You can also run your content through an online YAML validator to identify syntax problems.
10. Can one YAML file contain multiple documents?+
Yes. You can use the --- document separator to define multiple YAML documents inside a single file.
Final Thoughts
Learning how to create a YAML file is an important skill for developers working with modern applications, automation tools, and infrastructure platforms. Whether you are creating a basic configuration file in Notepad, writing a Docker Compose YAML file, managing a Kubernetes YAML manifest, or building a GitHub Actions workflow, understanding YAML syntax and indentation rules will help you avoid common formatting problems.
Start with simple YAML examples, learn how key-value pairs, lists, mappings, and nested objects work, and gradually move toward more advanced configuration structures. Always check your document before using it in a development environment.
If you want to make sure your YAML document follows the correct syntax, try the free CCODeLearner YAML Validator. Paste your YAML code, validate its structure, identify syntax errors, and make the necessary corrections before using your configuration file in a project.
