Quick Syntax Check

Always validate before running:

# Check syntax
ansible-playbook playbook.yml --syntax-check

# Lint for best practices
ansible-lint playbook.yml

Error 1: Indentation Mistakes

# WRONG — inconsistent indentation
- hosts: webservers
  tasks:
    - name: Install nginx
      apt:
       name: nginx    # ← 1 space instead of 2
        state: present  # ← 3 spaces — YAML breaks

# RIGHT — consistent 2-space indentation
- hosts: webservers
  tasks:
    - name: Install nginx
      ansible.builtin.apt:
        name: nginx
        state: present

Error 2: Missing Colon Space

# WRONG — no space after colon
- name:Install nginx
  apt:
    name:nginx

# RIGHT
- name: Install nginx
  ansible.builtin.apt:
    name: nginx

Error 3: Unquoted Special Characters

# WRONG — colon in value breaks YAML
- debug:
    msg: Error: something failed

# RIGHT — quote strings with special characters
- debug:
    msg: "Error: something failed"

Error 4: Boolean Gotchas

# WRONG — YAML interprets 'yes', 'no', 'true', 'false' as booleans
- debug:
    msg: "Country: {{ country }}"
  vars:
    country: no  # ← This becomes boolean false!

# RIGHT — quote it
  vars:
    country: "no"

Error 5: Tabs Instead of Spaces

# Find tabs in your playbook
grep -P '\t' playbook.yml

# Convert tabs to spaces
sed -i 's/\t/  /g' playbook.yml

Error 6: Multiline Strings

# WRONG — unquoted multiline
- debug:
    msg: This is a long message
    that spans multiple lines

# RIGHT — use | or >
- debug:
    msg: |
      This is a long message
      that spans multiple lines

# RIGHT — folded (joins lines with spaces)
- debug:
    msg: >
      This is a long message
      that spans multiple lines

Debugging Tools

# 1. Syntax check
ansible-playbook playbook.yml --syntax-check

# 2. Parse YAML with Python
python3 -c "import yaml; yaml.safe_load(open('playbook.yml'))"

# 3. Use ansible-lint
pip install ansible-lint
ansible-lint playbook.yml

# 4. VS Code with Red Hat Ansible extension
# Install: ext install redhat.ansible

Conclusion

90% of Ansible YAML errors come from indentation, missing spaces after colons, unquoted special characters, and tabs. Use --syntax-check and ansible-lint to catch them before running.