Use case 1 – system update automation

This use case is built to update and clean a Linux-based host under the two main families: Debian and Red Hat. The task should be able to update the software list index, install any available updates, remove unnecessary packages, clean the package manager cache, and, finally, restart the hosts if required. This playbook can be used on either physical or virtual Linux hosts that are accessible to the Ansible management server.

The code for this playbook is as follows:

---
- name: Update and clean up Linux OS
hosts: Linux
become: yes
gather_facts: yes
tasks:
- name: Update Debian Linux packages with Index
updated
apt:
upgrade: dist
update_cache: yes
when: ansible_os_family == "Debian"

- name: Update Red Hat Linux packages with Index
updated
yum:
name: "*"
state: latest
update_cache: yes
when: ansible_os_family == "RedHat"

- name: Clean up Debian Linux from cache and unused
packages
apt:
autoremove: yes
autoclean: yes
when: ansible_os_family == "Debian"

- name: Clean up Red Hat Linux from cache and unused
packages
shell: yum clean all; yum autoremove
when: ansible_os_family == "RedHat"
ignore_errors: yes

- name: Check if Debian system requires a reboot
shell: "[ -f /var/run/reboot-required ]"
failed_when: False
register: reboot_required
changed_when: reboot_required.rc == 0
notify: reboot
when: ansible_os_family == "Debian"
ignore_errors: yes

- name: Check if Red Hat system requires a reboot
shell: "[ $(rpm -q kernel|tail -n 1) !=
kernel-$(uname -r) ]"
failed_when: False
register: reboot_required
changed_when: reboot_required.rc == 0
notify: reboot
when: ansible_os_family == "RedHat"
ignore_errors: yes

handlers:
- name: reboot
command: shutdown -r 1 "A system reboot triggered
after and Ansible automated system update"
async: 0
poll: 0
ignore_errors: true

This playbook can then be scheduled to be executed using the crontab job during weekends or late at night when the system is idle. Alternatively, it can be scheduled to run during a maintenance period for a system that is active all the time. To accommodate redundant hosts, the user can add a batch size and a maximum failure percentage parameter to the playbook header, before defining the tasks. The following lines of code can be used to enable a level of protection:

---
- name: Update and clean up Linux OS
hosts: Linux
max_fail_percentage: 20
serial: 5
become: yes
become_user: setup
gather_facts: yes
tasks: ...

This allows you to work on five hosts at a time. In the event of 20% failure on the total amount of hosts, the playbook stops.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.121.242