Ansible playbook to upgrade Ubuntu/Debian servers and reboot if needed

I realized I've never posted this playbook to my blog... I needed to grab it for a project I'm working on, so I figured I'd post it here for future reference.

Basically, I need a playbook I can run whenever, that will ensure all packages are upgraded, then checks if a reboot is required, and if so, reboots the server. Afterwards, it removes any dependencies no longer required.

- hosts: all
  gather_facts: yes
  become: yes

    - name: Perform a dist-upgrade.
        upgrade: dist
        update_cache: yes

    - name: Check if a reboot is required.
        path: /var/run/reboot-required
        get_md5: no
      register: reboot_required_file

    - name: Reboot the server (if required).
      when: reboot_required_file.stat.exists == true

    - name: Remove dependencies that are no longer required.
        autoremove: yes

Reboot and wait for reboot to complete in Ansible playbook

September 2018 Update: Ansible 2.7 (to be released around October 2018) will include a new reboot module, which makes reboots a heck of a lot simpler (whether managing Windows, Mac, or Linux!):

- name: Reboot the server and wait for it to come back up.

That's it! Much easier than the older technique I used in Ansible < 2.7!

One pattern I often need to implement in my Ansible playbooks is "configure-reboot-configure", where you change some setting that requires a reboot to take effect, and you have to wait for the reboot to take place before continuing on with the rest of the playbook run.

For example, on my Raspberry Pi Dramble project, before installing Docker and Kubernetes, I need to make sure the Raspberry Pi's /boot/cmdline.txt file contains a couple cgroup features so Kubernetes runs correctly. But after adding these options, I also have to reboot the Pi.