Ubuntu desktop automated maintenance with Ansible

When running enough desktop office machines doing maintenance and making changes like installing new software quickly becomes a problem. You can configure unattended upgrades but this becomes a problem when it does not work. Often a update won’t install and you’ll need to intervene.

To resolve this we decided to try Ansilbe, which has worked out great for us. We start up the machines using wake on lan at night, apply any changes run the updates and clean up the system.

If you do not know how Ansible works, read up on it here. We needed to work around some bugs in Ansible but the playbook below is what works right now.

---
- hosts: desktops
 strategy: free
 serial: 10
 connection: local
 tasks:
 - name: wake up desktop
 local_action: command /usr/bin/wakeonlan {{ macaddress }}

- name: wait for desktop to start
 wait_for: >
 host={{ inventory_hostname }}
 port=22
 delay=1
 timeout=360
 delegate_to: localhost
 ignore_errors: True

- hosts: desktops
 strategy: free
 remote_user: ansibleuser
 become: yes
 become_user: root
 serial: 5
 tasks:

- name: update
 apt: update_cache=yes

- name: check for updates
 command: /usr/lib/update-notifier/apt-check --package-names
 register: packages

- name: upgrade
 apt: upgrade=dist
 when: packages.stderr != ""

- name: autoremove
 command: apt-get -y autoremove

- name: cleanup
 command: apt-get clean

- name: shutdown
 command: /sbin/shutdown -h +1

You’ll need to add all the desktop host names and mac addresses to /etc/ansible/hosts defining the mac address like this:

[desktops]

desktop1.example.com macaddress=00:EE:EE:EE:00:EE
desktop2.example.com macaddress=00:EE:EE:EE:00:EE
desktop3.example.com macaddress=00:EE:EE:EE:00:EE

You can add any task to run on the desktops in the playbook.