Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save UniversalSuperBox/11b17d52d902850879f94a45a3c91641 to your computer and use it in GitHub Desktop.
Save UniversalSuperBox/11b17d52d902850879f94a45a3c91641 to your computer and use it in GitHub Desktop.
Automatic security update and reboot of RHEL 7 servers

On Ubuntu, it's stupidly easy to enable automatic security updates. If you didn't do it in the installer:

sudo apt install unattended-upgrades
sudo dpkg-reconfigure unattended-upgrades

You can also make the server reboot automatically at a scheduled time by setting the following settings in /etc/apt/apt.conf.d/50unattended-upgrades:

Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "02:00";

On RHEL this gets a bit more tricky. While RedHat provides an easy-to-use update scheduler in yum-cron, it has no facility that I've found for automatic reboots. Here's how I set up my servers to automatically upgrade and then reboot:

First, we'll install a couple of utilities:

sudo yum install yum-cron yum-utils

Next, we'll set up yum-cron. By default we get two different configurations, one for hourly (/etc/yum/yum-cron-hourly.conf) and one for daily (/etc/yum/yum-cron.conf) runs of cron. Let's get security updates daily and ignore the hourly configuration.

Edit the file /etc/yum/yum-cron.conf. You'll see the line:

update_cmd = default

Change the line to:

update_cmd = security

If you'd like to reduce the automatic changes even more, you may choose minimal-security rather than security. To get the bare minimum updates only when a critical security errata is published, choose minimal-security-severity:Critical.

This will only allow yum-cron to download updates, not install them. To install updates, also change the line:

apply_updates = no

To...

apply_updates = yes

To enable yum-cron, start its service unit:

sudo systemctl enable --now yum-cron

Next, we'll set up your automatic reboots. We'll use cron to ensure that the reboot always occurs at a predictable time. Get started by running sudo crontab -e to edit root's crontab.

Add the following line to the crontab:

0 2 * * * /usr/bin/needs-restarting -r || /usr/sbin/reboot

This line will check if the server needs to be restarted (and restart it if so) at 2AM every day.

You can also restart only the services that need restarting by adding this line:

50 1 * * * for SERVICE in $(needs-restarting -s); do echo "Attempting to restart $SERVICE"; systemctl restart "$SERVICE"; done

That's a bit of a mess, but it restarts all of the services that must be to apply updates at 1:50AM every day. Note that I personally don't do this, but you can if you like to live dangerously.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment