Interview Prep/Real-World Interview/Write-an-Ansible-playbook tasks

Write a playbook that gathers disk usage from all servers and writes a single report on the control node.

IntermediateHands-onWrite-an-Ansible-playbook tasks
Answer
- hosts: all
  gather_facts: true
  tasks:
    - name: Build report on control node
      ansible.builtin.template:
        src: disk_report.j2
        dest: ./disk_report.txt
      delegate_to: localhost
      run_once: true
{% for h in ansible_play_hosts %}
{% for m in hostvars[h].ansible_facts.mounts if m.mount == '/' %}
{{ h }}: {{ ((1 - m.size_available / m.size_total) * 100) | round(1) }}% used on /
{% endfor %}
{% endfor %}

Key trick → run_once plus delegate_to: localhost runs one task for the whole play, and hostvars[h] reads facts gathered from every other host.

All Real-World Interview questions Roadmap: Interview readiness

More on Write-an-Ansible-playbook tasks