Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Ansible - Update And Reboot (if required) Amazon Linux Servers

Below is the playbook I use for updating my Amazon Linux servers. This will reboot the servers if they receive an updated kernel. It has to run a custom ssh command because unlike Ubuntu, there is no reboot-required file to indicate a reboot is required. The script is one I customized, but is largely based on the content linked to in the references.

You will need to change hosts: amazon-linux-servers to whatever you have called your hosts in your ansible hosts file.

- hosts: amazon-linux-servers
  sudo: true
  tasks:
    - name: upgrade all packages
      yum: name=* state=latest

    - name: Check for reboot hint.
      shell: LAST_KERNEL=$(rpm -q --last kernel | awk 'NR==1{sub(/kernel-/,""); print $1}'); CURRENT_KERNEL=$(uname -r); if [ $LAST_KERNEL != $CURRENT_KERNEL ]; then echo 'reboot'; else echo 'no'; fi
      ignore_errors: true
      register: reboot_hint

    - name: Rebooting ...
      command: shutdown -r now "Reboot required for updated kernel"
      async: 0
      poll: 0
      sudo: true
      ignore_errors: true
      when: reboot_hint.stdout.find("reboot") != -1
      register: rebooting

    - name: Wait for thing to reboot...
      pause: seconds=45
      when: rebooting|changed

I previously used shell: LAST_KERNEL=$(rpm -q --last kernel | perl -pe 's/^kernel-(\S+)./$1/' | head -1); CURRENT_KERNEL=$(uname -r); if [ $LAST_KERNEL != $CURRENT_KERNEL ]; then echo 'reboot'; else echo 'no'; fi* but have changed it to remove the perl aspect.

Execute

Execute it with:

ansible-playbook /path/to/playbook.yml --user=ec2-user

This works in ansible version 1.7.2 which was installed on debian simply by running sudo apt-get install ansible rather than installing through Pip.

SSH Keys

Don't forget to specify the SSH key to log into your remote servers with.

References

Last updated: 8th January 2023
First published: 16th August 2018