YAML Essentials
YAML Essentials
YAML Syntax Overview
Basic Rules
- Case sensitive
- Indentation matters
- Uses spaces (not tabs)
- Key-value pairs
Document Structure
- Start with
---
- End with
...
(optional) - Comments use
#
- Hierarchical structure
Data Types and Structures
Scalars
- Strings
name: "John Doe" description: 'A simple string' unquoted: This is also a string
- Numbers
integer: 42 float: 3.14 scientific: 1.23e-4
- Booleans
true_value: true false_value: false yes_value: yes no_value: no
Collections
Lists
fruits:
- apple
- banana
- orange
# Alternative syntax
fruits: [apple, banana, orange]
Dictionaries
user:
name: John
age: 30
roles:
- admin
- developer
# Alternative syntax
user: {name: John, age: 30}
Common YAML Patterns
Multi-line Strings
description: |
This is a long
multi-line string
that preserves newlines
folded_text: >
This is a long text
that will be folded
into a single line
Anchors and Aliases
defaults: &defaults
timeout: 30
retries: 3
webserver:
<<: *defaults
port: 80
YAML in Ansible
Playbook Structure
---
- name: Example Playbook
hosts: webservers
become: true
tasks:
- name: Install Apache
yum:
name: httpd
state: present
Variables
vars:
http_port: 80
max_clients: 200
vars_files:
- vars/common.yml
- vars/webserver.yml
Common Mistakes
Indentation Issues
# Incorrect
tasks:
- name: Install package
yum:
name: httpd
# Correct
tasks:
- name: Install package
yum:
name: httpd
Quoting Special Characters
# Incorrect
command: echo * > output.txt
# Correct
command: "echo * > output.txt"
Best Practices
- Use consistent indentation
- Quote strings with special characters
- Use descriptive keys
- Keep files organized
- Comment complex structures
Practical Exercise
Writing a Simple YAML File
- Create a new file
- Define basic structures
- Validate syntax
Common Tools
yamllint
for validation- Online YAML validators
- Text editors with YAML support
Key Takeaways
- YAML is human-readable
- Proper indentation is crucial
- Understanding data types helps
- Practice improves proficiency