C.W.K.
Stream
Lesson 07 of 14 · published

Ansible Playbook Example

~18 min · ansible, playbook, yaml, tasks

Level 0Pinger
0 XP0/101 lessons0/12 achievements
0/150 XP to next level150 XP to go0% complete

From ad-hoc to repeatable

Ad-hoc ansible all -a 'cmd' is the parallel-ssh use case. Playbooks are where Ansible earns its keep — multi-step workflows that converge machines toward a desired state, idempotently.

Anatomy of a playbook

YAML file with: a play (target hosts + tasks), tasks (each one calls a module), optionally registered output (register:) you can branch on with when:. Modules are the building blocks; orchestration is your composition.

Code

update-all.yml — daily fleet update·yaml
---
- name: Update all Macs
  hosts: all_macs
  tasks:
    - name: brew update
      command: brew update
      register: update_result
      changed_when: "'Already up-to-date' not in update_result.stdout"

    - name: brew upgrade
      command: brew upgrade
      register: upgrade_result

    - name: Show upgraded packages
      debug:
        var: upgrade_result.stdout_lines
      when: upgrade_result.stdout_lines | length > 0

    - name: Cleanup old versions
      command: brew cleanup -s

    - name: Disk space report
      command: df -h /
      register: disk_info
      changed_when: false

    - name: Show disk space
      debug:
        msg: "{{ inventory_hostname }}: {{ disk_info.stdout_lines[-1] }}"
Run the playbook·bash
# Standard run
ansible-playbook update-all.yml -i inventory.ini

# Dry run (check mode)
ansible-playbook update-all.yml -i inventory.ini --check

# Limit to specific hosts
ansible-playbook update-all.yml -i inventory.ini --limit office,server

# Verbose
ansible-playbook update-all.yml -i inventory.ini -v

External links

Exercise

Save the example playbook as update-all.yml. Run a dry-run first: ansible-playbook update-all.yml -i inventory.ini --check --limit office. If that looks right, run for real on one host. Once you're confident, run on all_macs. Compare the experience to manually SSH'ing into each one — that's the time you've reclaimed.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.