Format Ansible Playbook YAML Files

Format and validate Ansible playbook YAML with correct task indentation, module arguments, variable definitions, and handler references. Follow Ansible best practices for readable automation.

Real-World

Detailed Explanation

Ansible Playbook YAML Formatting

Ansible uses YAML for its playbooks, roles, inventories, and variable files. Ansible YAML has its own conventions and common patterns that differ from other YAML-heavy tools like Kubernetes.

Playbook Structure

---
- name: Configure web servers
  hosts: webservers
  become: true
  vars:
    http_port: 80
    max_clients: 200

  tasks:
    - name: Install Apache
      ansible.builtin.apt:
        name: apache2
        state: present
        update_cache: true

    - name: Configure Apache
      ansible.builtin.template:
        src: templates/httpd.conf.j2
        dest: /etc/apache2/apache2.conf
      notify: Restart Apache

    - name: Ensure Apache is running
      ansible.builtin.service:
        name: apache2
        state: started
        enabled: true

  handlers:
    - name: Restart Apache
      ansible.builtin.service:
        name: apache2
        state: restarted

Ansible-Specific Formatting Rules

  1. Start with --- — All Ansible YAML files should begin with the YAML document start marker
  2. Task names — Every task should have a descriptive name field (ansible-lint enforces this)
  3. FQCN modules — Use fully qualified collection names like ansible.builtin.apt instead of short names like apt
  4. Key ordering — Convention is: name, module name, module arguments, when, register, notify, tags

Variable Files

---
# vars/main.yml
app_name: myapp
app_version: "2.1.0"
app_config:
  database:
    host: "{{ db_host }}"
    port: 5432
  cache:
    driver: redis
    ttl: 3600

Note the quoting of Jinja2 expressions ("{{ }}") — these must be quoted to prevent YAML from misinterpreting the braces.

Common Formatting Issues

  • Unquoted Jinja2host: {{ var }} fails; must be host: "{{ var }}"
  • Boolean module arguments — Use true/false, not yes/no (ansible-lint recommends this)
  • Long lines — Ansible tasks with many arguments can become very long; use YAML multiline syntax
  • Inconsistent indentation — Ansible works with any indentation width, but 2 spaces is standard

ansible-lint Integration

The ansible-lint tool enforces YAML formatting rules specific to Ansible. Running it alongside a YAML formatter catches both general YAML issues and Ansible-specific anti-patterns.

Use Case

Ansible playbook formatting is essential for infrastructure-as-code teams. Clean, consistently formatted playbooks are easier to review, debug, and maintain. Teams managing hundreds of roles and playbooks benefit from automated formatting that enforces Ansible best practices, especially when onboarding new team members who may not know Ansible YAML conventions.

Try It — YAML Formatter & Validator

Open full tool