Ansible playbook to automate Ubuntu/Debian updates

Installing Ubuntu/Debian updates manually for each machine individually is quite inefficient and you usually want to automate this task.

The following Ansible playbook installs Ubuntu/Debian updates on a group of machines in parallel.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
---
- hosts: linux
  become: true
 
  tasks:
 
    - name: Update apt repo and cache on all Debian/Ubuntu boxes
      apt:
        update_cache: yes
        cache_valid_time: 3600
 
    - name: Safe-Upgrade all packages on servers
      apt:
        upgrade: safe
 
    - name: Check if a reboot is needed on all servers
      register: reboot_required_file
      stat: path=/var/run/reboot-required get_md5=no
 
    - name: Reboot the box if kernel updated
      reboot:
        msg: "Reboot initiated by Ansible for kernel updates"
        connect_timeout: 5
        reboot_timeout: 300
        pre_reboot_delay: 0
        post_reboot_delay: 30
        test_command: uptime
      when: reboot_required_file.stat.exists
 
    - name: Remove dependencies that are no longer required
      apt:
        autoremove: yes