Update Debian with Ansible

Posted by Antoine Joubert on Sun 31 January 2016

Introduction

I've recently bought a HP Proliant Microserver Gen8 to play around with LXC and try new stuff.

From the 4 Debian machines I had to keep up-to-date, I now have 7, so it became quite time-consumming to manually SSH to each of them whenever an update became available.

I ended up looking at Ansible to speed up the process and, within an hour, I had a working playbook that updates the debian packages, pip packages and git repos on all of my servers with a single command.

I figured I'd share the playbook I use to update the Debian packages !

The playbook

I modified this gist to only use apt-get instead of both apt-get and aptitude.

- hosts: all
  remote_user: admin
  become: yes
  become_method: sudo
  tasks:
    - name: update cache
      apt: update_cache=yes
    - name: list packages to upgrade (1/2)
      shell: apt-get upgrade --show-upgraded --assume-no | grep '^ ' | sed 's/  //;s/ /\n/g'
      register: updates
      changed_when: False
    - name: list packages to upgrade (2/2)
      debug: msg="{{ updates.stdout_lines | count }} packages to upgrade ({{ updates.stdout_lines | join(', ') }})"
      when: (updates.stdout_lines)
    - name: upgrade packages
      apt: upgrade=dist
    - name: check what the new version is
      shell: lsb_release -r | awk '{print $2}'
      changed_when: False
      register: new_release
    - name: notify distribution version upgrade
      debug: msg="Debian has been upgraded from {{ ansible_lsb.release }} to {{ new_release.stdout }}"
      when: ansible_lsb.release != new_release.stdout
    - name: install the debian-goodies package if it is missing
      apt: name=debian-goodies state=present
    - name: list services to restart (1/2)
      shell: checkrestart | grep ^service | awk '{print $2}'
      register: services
      changed_when: False
    - name: list services to restart (2/2)
      debug: msg="{{ services.stdout_lines | count }} services to restart ({{ services.stdout_lines | join (', ') }})"
      when: (services.stdout_lines)
    - name: cache cleanup
      shell: apt-get autoclean

Conclusion

That's all ! Please leave a comment if you've found this playbook helpful !



Comments !