In the previous lesson you wrote your first playbook, common.yml, and saw that its structure depends entirely on indentation and a handful of symbols (-, :, quotes). That language is YAML, and it isn't only used in playbooks: it's also used in the inventory (inventory/hosts.yml), in the group_vars/ and host_vars/ files, in roles and in almost everything you will write in this course. Most beginner mistakes in Ansible aren't Ansible mistakes at all but YAML mistakes: an extra space, missing quotes, a yes that accidentally turns into a boolean. In this lesson you will learn exactly the part of YAML you need for Ansible, with Aurora Store examples, and you will be able to read and interpret syntax errors when they show up.
Contents
- What YAML is and how Ansible reads it
- Documents and the
---marker - Maps (dictionaries)
- Lists
- Nesting and indentation
- Scalars and data types
- Booleans:
true/falseversusyes/no - Strings and quotes
- Multi-line text:
|and>blocks - Comments
key=valuesyntax versus native YAML- Anchors and aliases
- Typical mistakes and how to read a syntax error
- Validating before running
- Practice: Aurora's welcome message in
common.yml
- What YAML is and how Ansible reads it
YAML (YAML Ain't Markup Language) is a text format for representing structured data in a human-readable way. It has only three kinds of constructs:
| Construct | What it represents | Example |
|---|---|---|
| Map (dictionary) | Key → value pairs | nginx_port: 80 |
| List (sequence) | Ordered values | - web1 |
| Scalar | A simple value: text, number, boolean, null | 80, true, Europe/Madrid |
Everything else is a combination of these three. Ansible reads files with the PyYAML library, which implements version YAML 1.1 of the specification. This detail matters, as you will see with booleans and numbers.
To see how YAML interprets a snippet, you can convert it to JSON with Python (which you already have on the control node, because Ansible needs it):
python3 -c 'import sys, yaml, json; print(json.dumps(yaml.safe_load(sys.stdin), indent=2))' <<'EOF'
nginx_port: 80
aurora_web_root: /var/www/aurora
EOFIf import yaml fails, run the command with the Python from the environment where you installed Ansible (for example, ~/.local/pipx/venvs/ansible/bin/python). We'll use this trick several times in the lesson: it's the quickest way to check which data type YAML has understood.
- Documents and the
--- marker
--- markerA YAML file can contain one or more documents. Each document starts with --- and, optionally, ends with ...:
In Ansible each file contains a single document, and the convention is to always start it with ---, even though it's optional. Every file in aurora-infra follows this convention. The ... marker isn't used in practice.
- Maps (dictionaries)
A map is a set of key: value pairs. Notice that a space follows the colon: it's mandatory.
This is exactly the content of inventory/group_vars/webservers.yml. Rules:
- Keys are unique within the same map. If you repeat one, PyYAML keeps the last one (and Ansible prints a warning): it's a common mistake when editing long files.
- The order of the keys in a map has no meaning for the data (although Ansible preserves it when displaying them).
- In Ansible, variable names may contain only letters, numbers and underscores, and may not start with a number (
nginx_port, nevernginx-port).
There is also a compact form (flow style), inherited from JSON:
It's valid, but in Aurora we always use block style (one key per line), which is easier to read and to review in Git.
- Lists
A list is a sequence of items, each preceded by a dash and a space (- ):
The equivalent compact form is aurora_common_packages: [htop, curl, vim]. You have already used lists without knowing it: a playbook is a list of plays and tasks: is a list of tasks. That's why every play and every task starts with - .
The items of a list can be maps. This case is so common in Ansible that it's worth understanding it well:
aurora_team_users:
- name: deploy
comment: Aurora Store deployments
- name: laura
comment: Laura Gómez - DevelopmentHere aurora_team_users is a list of two maps. The dash opens each item, and the name and comment keys of the same item are aligned with each other. In JSON:
{
"aurora_team_users": [
{"name": "deploy", "comment": "Aurora Store deployments"},
{"name": "laura", "comment": "Laura Gómez - Development"}
]
}(This list is just an example for now; in Lesson 3.6 you will create a similar one for real.)
- Nesting and indentation
YAML expresses that something is inside something else through indentation. Let's analyze common.yml from the previous lesson:
---
- name: Common configuration for Aurora Store servers # item 1 of the list (a play)
hosts: aurora # key of the same map (the play)
become: true
tasks: # the value of "tasks" is...
- name: Install htop # ...a list; item 1 (a task)
ansible.builtin.apt: # task key whose value is...
name: htop # ...a map of parameters
state: presentflowchart TD
A["List (the playbook)"] --> B["Map (the play)<br/>name, hosts, become, tasks"]
B --> C["List (tasks)"]
C --> D["Map (the task)<br/>name, ansible.builtin.apt"]
D --> E["Map (parameters)<br/>name: htop, state: present"]
Golden rules of indentation:
- Spaces only, never tabs. YAML forbids tabs for indentation. Set up your editor (VS Code, vim, nano…) so the Tab key inserts spaces.
- Items at the same level are exactly aligned.
hosts,becomeandtasksstart in the same column as the play'sname. - The number of spaces per level is up to you, but it must be consistent. The Ansible convention is 2 spaces.
- Lists may or may not be indented relative to their parent key; both forms are valid:
# Form A: indented list (the one we use in Aurora)
tasks:
- name: Install htop
# Form B: list at the same level as the key (also valid)
tasks:
- name: Install htopIn aurora-infra we always use form A. What matters is not to mix them within the same file.
- Scalars and data types
YAML infers a scalar's type from how it looks:
| You write | Type YAML understands | Value |
|---|---|---|
80 |
Integer | 80 |
16 |
Integer | 16 |
0.5 |
Decimal (float) | 0.5 |
1.10 |
Decimal | 1.1 (the zero is lost!) |
0644 |
Octal integer (YAML 1.1) | 420 |
644 |
Decimal integer | 644 |
true |
Boolean | true |
null, ~ or nothing |
Null | null |
Europe/Madrid |
String | "Europe/Madrid" |
"16" |
String (because of the quotes) | "16" |
Two cases that cause real problems:
Versions with decimals. If you write app_version: 1.10, YAML turns it into the number 1.1. Versions are text, not numbers: write them in quotes (app_version: "1.10"). In Aurora, postgresql_version: 16 is an integer with no decimals and works fine in paths such as /etc/postgresql/16/main, but if you ever use a version with a dot, quote it.
File permissions. The mode parameter of modules such as file or copy is the classic case:
mode: 0644 # YAML 1.1 reads it as octal → 420 decimal → rw-r--r-- permissions. It works, but it's fragile.
mode: 644 # ERROR! Decimal integer 644 → 1204 in octal → nonsensical permissions.
mode: "0644" # RECOMMENDED: a string; Ansible interprets it as octal without ambiguity.
mode: u=rw,g=r,o=r # Also valid: symbolic notation.In aurora-infra we always write mode in quotes and with the leading zero.
- Booleans:
true/false versus yes/no
true/false versus yes/noYAML 1.1 recognizes many words as booleans: true/false, yes/no, on/off, in lowercase, capitalized or all caps. That's why you'll see old playbooks with become: yes.
| You write | YAML 1.1 (PyYAML) interprets it as |
|---|---|
true, True, TRUE |
Boolean true |
yes, Yes, on, ON |
Boolean true |
false, no, off, NO |
Boolean false |
"yes", 'no' |
String (because of the quotes) |
Convention in this course (and in ansible-lint): always use lowercase true and false. They are valid in YAML 1.1 and in YAML 1.2 (where yes/no are no longer booleans), and they hold no surprises.
The classic surprise is the opposite one: a value you did not want to be a boolean.
Write "NO" in quotes. The same goes for answers or configuration values such as on/off that a program expects as literal text.
- Strings and quotes
Most strings don't need quotes (aurora_timezone: Europe/Madrid). But there are situations where they are mandatory:
| Situation | Wrong | Right |
|---|---|---|
The value starts with {{ |
name: {{ aurora_timezone }} |
name: "{{ aurora_timezone }}" |
It contains : (colon and space) |
msg: Warning: check db1 |
msg: "Warning: check db1" |
It contains # (space and hash) |
msg: Aurora coffee #1 |
msg: "Aurora coffee #1" |
It starts with a special character (*, &, !, %, @, `, [, {, >, ` |
`) | pattern: *.log |
| You want text that looks like another type | version: 1.10, answer: yes |
version: "1.10", answer: "yes" |
The {{ rule is the most important one in Ansible. For YAML, a { at the start of a value opens a compact map ({a: 1}), so {{ aurora_timezone }} without quotes is a syntax error. If the expression is not at the start, no quotes are needed:
dest: /etc/aurora/{{ inventory_hostname }}.conf # valid: doesn't start with {
msg: "{{ inventory_hostname }} is ready" # quotes mandatory: starts with {Single or double quotes:
- Double (
"..."): interpret escape sequences such as\n(newline),\t(tab) or\". - Single (
'...'): everything is literal; the only "escape" is''to write an apostrophe.
msg_double: "Line 1\nLine 2" # two lines
msg_single: 'Line 1\nLine 2' # literally: Line 1\nLine 2
note: 'Aurora''s store' # result: Aurora's storePractical tip: use double quotes by default when quotes are needed, and single quotes when the text contains backslashes you don't want interpreted (regular expressions, Windows paths).
- Multi-line text:
| and > blocks
| and > blocksFor long text (the contents of a file, a message, a long command) YAML offers two blocks:
|(literal): keeps line breaks exactly as they are. Ideal for the contents of configuration files.>(folded): joins the lines with spaces into a single line; a blank line produces a line break. Ideal for long text or commands you want to split so they read better.
aurora_motd_literal: |
Aurora Store
Restricted access
aurora_folded_description: >
Aurora Store sells specialty coffee
roasted every week in small batches.Result:
{
"aurora_motd_literal": "Aurora Store\nRestricted access\n",
"aurora_folded_description": "Aurora Store sells specialty coffee roasted every week in small batches.\n"
}The block's contents must be indented further than the key, and that leading indentation is removed. An optional indicator controls the final line break (chomping):
| Indicator | Final line break | Typical use |
|---|---|---|
| ` | or>` |
Exactly one |
| ` | -or>-` |
None |
| ` | +or>+` |
All trailing ones |
Inside a block nothing needs escaping: not quotes, not :, not #. {{ }} expressions are still evaluated, because Ansible processes them after reading the YAML.
- Comments
Everything after a # preceded by a space (or at the start of the line) is a comment:
Use comments to explain why, not what: nginx_port: 80 # port adds nothing, but nginx_worker_connections: 1024 # measured at the Black Friday peak does. Remember that inside a | or > block, # is plain text, not a comment.
key=value syntax versus native YAML
key=value syntax versus native YAMLFor compatibility with ad hoc commands, Ansible lets you write a task's parameters as a key=value string (free form):
# key=value style (discouraged)
- name: Install htop
ansible.builtin.apt: name=htop state=present update_cache=true
# Native YAML style (the one we use)
- name: Install htop
ansible.builtin.apt:
name: htop
state: present
update_cache: true| Aspect | key=value |
Native YAML |
|---|---|---|
| Readability | Long, dense line | One parameter per line |
| Data types | Everything is text | Real integers, booleans, lists and maps |
| Lists as values | Awkward (name=htop,curl) |
Natural (a YAML list) |
| Quotes and spaces | A frequent source of errors | Clear YAML rules |
| Review in Git | A change alters the whole line | The diff shows only the changed parameter |
In aurora-infra we always use native YAML. The only reasonable exception is modules such as command or shell, whose main "parameter" is the command itself (ansible.builtin.command: nginx -v); even for them there's the cmd: form, which you will see in Lesson 3.7.
- Anchors and aliases
YAML lets you define a snippet once with an anchor (&name) and reuse it with an alias (*name). With the special << key (merge key) you can merge one map into another:
---
_aurora_file_defaults: &aurora_file_defaults
owner: root
group: root
mode: "0644"
aurora_motd_file:
<<: *aurora_file_defaults
dest: /etc/motd
aurora_issue_file:
<<: *aurora_file_defaults
dest: /etc/issue.net
mode: "0640" # overrides the anchor's valueAnchors are useful, but they have important limits: they only work within the same file and they make the code harder to read for anyone who doesn't know them. In Ansible, it's almost always better to reuse through variables (Lesson 3.5) and, later on, through roles (Module 4). You will come across them in other people's projects; in Aurora we won't use them.
- Typical mistakes and how to read a syntax error
Suppose you write this task in common.yml and forget the quotes:
When you run ansible-playbook common.yml --syntax-check, Ansible replies with something like this (the exact format varies between ansible-core versions; since 2.19 the messages are more compact):
ERROR! We were unable to read either as JSON nor YAML, these are the errors we got from each:
JSON: Expecting value: line 1 column 1 (char 0)
Syntax Error while loading YAML.
found unacceptable key (unhashable type: 'AnsibleMapping')
The error appears to be in '/home/student/aurora-infra/common.yml': line 16, column 15, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
community.general.timezone:
name: {{ aurora_timezone }}
^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:
...How to read it:
- Ignore the JSON line: Ansible tries to read the file as both JSON and YAML; the JSON error is irrelevant.
- Read the cause (
found unacceptable key...,mapping values are not allowed here…). It's often cryptic, but it gives you a clue. - Go to the line and column indicated and look at the
^ here. - Read the final suggestion if there is one: Ansible recognizes some typical mistakes, such as this one with the quotes.
- Remember the warning "may be elsewhere in the file": the real problem may be one or several lines earlier (an unclosed quote, a wrong indentation that YAML only detects further down).
Catalog of frequent errors:
| Message (summarized) | Usual cause |
|---|---|
found character '\t' that cannot start any token |
A tab in the indentation |
mapping values are not allowed in this context |
A : inside an unquoted value, or a badly indented key |
found unacceptable key / missing quotes |
{{ }} at the start of an unquoted value |
did not find expected key |
Inconsistent indentation: an item indented more or less than its siblings |
did not find expected '-' indicator |
A list item without a dash or misaligned |
found undefined alias |
An *alias without its &anchor, or an unquoted value that starts with * |
conflicting action statements: ansible.builtin.apt, name |
The module's parameters aren't indented inside the module |
The last one deserves an explanation, because YAML accepts it and it's Ansible that complains:
- name: Install htop
ansible.builtin.apt:
name: htop # wrong! at the same level as the module
state: presentFor YAML it's a valid map with three keys (an empty ansible.builtin.apt, name, state), but Ansible sees a task with two possible actions and doesn't know which one to run. The parameters must go two spaces further in than the module name.
- Validating before running
| Tool | What it checks | When |
|---|---|---|
ansible-playbook file.yml --syntax-check |
YAML syntax and Ansible structure (valid keywords, one action per task…) | Always, before running a new or modified playbook |
ansible-inventory --list |
That the inventory and its variables load correctly | When you touch inventory/ |
python3 -c 'import yaml...' |
How YAML interprets a snippet (types) | One-off doubts |
yamllint and ansible-lint |
Style, best practices and frequent mistakes | Lesson 9.4 (integration into day-to-day work and CI) |
--syntax-check does not check that variables exist or that modules receive correct parameters: you only find that out when running (or with --check, Lesson 3.3). But it catches most of the mistakes in this lesson in a second.
- Practice: Aurora's welcome message in
common.yml
common.ymlPut literal blocks into practice by adding to common.yml the welcome message (/etc/motd) you created with an ad hoc command in Lesson 2.4. Add this task at the end of tasks::
- name: Configure the welcome message (motd)
ansible.builtin.copy:
dest: /etc/motd
owner: root
group: root
mode: "0644"
content: |
==========================================================
Aurora Store - {{ inventory_hostname }} ({{ aurora_env }})
Access restricted to authorized personnel.
Incidents: {{ aurora_admin_email }}
==========================================================YAML details that appear here:
mode: "0644"in quotes and with the zero (section 6).content: |introduces a literal block: each line of the block will be a line of the file, and it will end with a final newline, as it should.- The
{{ ... }}variables inside the block don't need quotes because they aren't at the start of a YAML value.inventory_hostnameis a special variable holding the host's name in the inventory (web1,web2,db1); you will study it in Lesson 3.5.aurora_envandaurora_admin_emailcome frominventory/group_vars/all/aurora.yml.
Check the syntax, run it and verify:
ansible-playbook common.yml --syntax-check
ansible-playbook common.yml
ansible web1 -a 'cat /etc/motd'web1 | CHANGED | rc=0 >>
==========================================================
Aurora Store - web1 (lab)
Access restricted to authorized personnel.
Incidents: [email protected]
==========================================================Commit the change:
Common Mistakes and Tips
- Invisible tabs: if you copy code from a website or a document, it may bring along tabs or "odd" spaces (non-breaking). Turn on your editor's option to show whitespace.
mode: 644without a zero or quotes: the file ends up with strange permissions and there's no error. Always writemode: "0644".yes/nomixed withtrue/false: it works, but it's inconsistent andansible-lintwill flag it. Usetrue/false.- Forgetting the space after
:or-:nginx_port:80is a string ("nginx_port:80"), not a key-value pair;-web1is the string"-web1", not a list item. - Blocks with irregular indentation: inside
|, every line must have at least the indentation of the first one; a less indented line ends the block and causes a strange error on the following line. - Tip: set up your editor with YAML support (in VS Code, Red Hat's official Ansible extension), which flags errors as you type and autocompletes modules and parameters.
Exercises
Exercise 1: Find the mistakes
This variables file has five problems (some are syntax errors and others are misinterpreted data). Find and fix them:
---
aurora_app_version: 2.10
aurora_banner: Notice: maintenance on Sunday
aurora_backup_dir: {{ aurora_web_root }}/backups
aurora_backup_mode: 750
aurora_maintenance:
enabled: noExercise 2: From key=value to native YAML
Rewrite this task in native YAML:
- name: Create the Aurora log directory
ansible.builtin.file: path=/var/log/aurora state=directory owner=root group=root mode=0755Exercise 3: Literal or folded
Write the aurora_robots variable with the contents of a two-line robots.txt file (User-agent: * and Disallow: /admin/), and the aurora_slogan variable with a long sentence written on two YAML lines that must end up as a single line with no final newline. Check the result with the Python trick from section 1.
Solutions
Exercise 1.
---
aurora_app_version: "2.10"
aurora_banner: "Notice: maintenance on Sunday"
aurora_backup_dir: "{{ aurora_web_root }}/backups"
aurora_backup_mode: "0750"
aurora_maintenance:
enabled: false2.10would become the number 2.1: put it in quotes.Notice: maintenancecontains:: put it in quotes.- The value starts with
{{: put it in quotes. 750would be decimal:"0750".- The last line was indented with a tab: use two spaces. Also,
noworks, but the convention isfalse.
Exercise 2.
- name: Create the Aurora log directory
ansible.builtin.file:
path: /var/log/aurora
state: directory
owner: root
group: root
mode: "0755"Exercise 3.
aurora_robots: |
User-agent: *
Disallow: /admin/
aurora_slogan: >-
Specialty coffee roasted every week
and shipped all over the peninsula.aurora_robots is "User-agent: *\nDisallow: /admin/\n": inside the literal block, : and * don't need quotes. aurora_slogan is "Specialty coffee roasted every week and shipped all over the peninsula.", on one line and with no final newline thanks to >-.
Conclusion
You now master the part of YAML that Ansible uses: documents that start with ---, maps, lists and their combination (lists of maps), indentation with spaces as the way to nest, scalar types and their traps (versions with decimals, octal permissions, YAML 1.1 booleans), when quotes are mandatory (above all with {{ at the start of a value), | and > blocks with their indicators, comments, why we prefer native YAML over key=value, and what anchors are. You know how to read a syntax error and validate with --syntax-check. And common.yml now configures Aurora's welcome message with a literal block. With these foundations, in the next lesson, Writing Your First Playbook, you will build a complete, real playbook step by step: the one that turns web1 and web2 into Aurora Store's web servers with nginx.
Ansible Course: From Beginner to Advanced
Module 1: Introduction to Ansible
- What Is Ansible?
- Installing Ansible
- Setting Up the Practice Lab
- Ansible Architecture
- Basic Ansible Commands
Module 2: Ansible Fundamentals
- Inventory Files
- Inventory Variables: group_vars and host_vars
- Configuring Ansible (ansible.cfg)
- Ad Hoc Commands
- Ansible Modules
- Collections and Fully Qualified Names (FQCN)
Module 3: Playbooks
- Introduction to Playbooks
- Essential YAML for Ansible
- Writing Your First Playbook
- Playbook Structure
- Variables and Facts
- Conditionals and Loops
- Registering Results and Debugging Playbooks
Module 4: Roles
- Introduction to Roles
- Creating Roles
- Role Directory Structure
- Using Roles in Playbooks
- Reusing Tasks: include and import
- Role Dependencies and Argument Validation
Module 5: Advanced Playbook Techniques
- Handlers
- Jinja2 Templates
- Filters and Lookups
- Ansible Vault
- Error Handling
- Tags and Selective Execution
- Rolling Deployments and Delegation
- Optimizing Playbooks
Module 6: Ansible Galaxy
- What Is Ansible Galaxy?
- Using Ansible Galaxy
- Managing Dependencies with requirements.yml
- Creating and Sharing Roles
- Creating Your Own Collections
Module 7: Ansible Tower, AWX and Automation Platform
- Introduction to Ansible Tower and AWX
- Installing AWX
- Using AWX: Job Templates and Jobs
- Managing Projects and Inventories
- Credentials, Permissions (RBAC) and Workflows
- Execution Environments and ansible-navigator
Module 8: Ansible for DevOps
- Ansible and Docker
- Ansible and Kubernetes
- CI/CD with Ansible
- Ansible in Cloud Environments
- Ansible and Terraform
Module 9: Ansible Best Practices
- Code Organization
- Security Best Practices
- Performance Tuning
- Code Quality: ansible-lint and yamllint
- Testing Ansible Code with Molecule
Module 10: Advanced Ansible Topics
- Custom Modules
- Dynamic Inventory
- Ansible Plugins
- The Ansible API and ansible-runner
- Event-Driven Ansible
