Ansible Playbook for System Updates

So lately I’ve been playing a lot with ansible. It makes administrating close to 20 servers a real breeze! Come Patch Tuesday, you never know if reboots will be required on a server. I took a bit of inspiration from this ansible script and tweaked it a bit to reboot the servers after updates if required… as well as performing an apt-get autoremove to clear out old packages (usually kernels) so my /boot partition doesn’t get full and wreak havoc.

- hosts: all
  sudo: yes
  tasks:
  - name: Update package list and perform safe-upgrade
    apt: upgrade=safe update_cache=yes

  - name: Check if packages need to be autoremoved
    command: apt-get --dry-run autoremove
    register: check_autoremove
    changed_when: False

  - name: Autoremove unused packages
    command: apt-get -y autoremove
    when: "'packages will be REMOVED' in check_autoremove.stdout"

  - name: Check if packages need to be autocleaned
    command: apt-get --dry-run autoclean
    register: check_autoclean
    changed_when: False

  - name: Clean up package cache
    command: apt-get -y autoclean
    when: "'Del' in check_autoclean.stdout"

  - name: Check reboot if required
    stat: path=/var/run/reboot-required get_md5=no
    register: sym

  - name: Reboot if required
    shell: reboot
    when: sym.stat.exists is defined and sym.stat.exists
    async: 0
    poll: 0
    ignore_errors: true

  - name: Wait for server to come back
    local_action: wait_for host={{ inventory_hostname }} state=started
    when: sym.stat.exists is defined and sym.stat.exists
    sudo: false

All that’s left is to run ansible-playbook -K doSystemUpdates.yml (or whatever you saved it as) and twiddle your thumbs!

This worked great on all of our Ubuntu production servers the other night. Hopefully someone finds this helpful!

No Comments, Be The First!

Your email address will not be published.