Wednesday 15 February 2017

Automatically running a script on system startup with RHEL / CentOS 7

Since CentOS 7 has adopted systemd - hence replacing the need for SysV. This now begs the question of how we can easily add a script to run on startup - traditionally it's pretty easy to do with the rc.local file:

/etc/rc.local (RHEL based)

or

/etc/rc.d/rc.local (Found in Debain based distros)

In fact systemd actually maintains backward compatibility for the old SysV init script (/etc/init.d/) by using the systemd-sysv-generator utility. We can manually invoke this with:

/usr/lib/systemd/system-generators/systemd-sysv-generator

The init scripts get called just after the basic.target is executed.

By default the rc.local file is not present - so lets create it and ensure that it's executable:

sudo touch /etc/rc.local

Since the file is treated like a script we should add the relevant interpreter at the beginning of the file for example:

#!/bin/bash

Set the execution bits:

sudo chmod +x /etc/rc.local

and finally enable the rc.local service with:

sudo systemctl enable rc-local.service

Although this failed with the following message:

The unit files have no installation config (WantedBy, RequiredBy, Also, Alias
settings in the [Install] section, and DefaultInstance for template units).
This means they are not meant to be enabled using systemctl.

This is in fact because the service is static - i.e. static services have no [Install] section and are typically used as dependencies for other services.

So after some digging it turns out that the service does not need to be enabled (after inspecting the service file):

cat /usr/lib/systemd/system/rc-local.service

....
# This unit gets pulled automatically into multi-user.target by
# systemd-rc-local-generator if /etc/rc.d/rc.local is executable.
...

So it turns out by turning on the executable bit of rc.local it will be pulled into the multi-user target.

  

0 comments:

Post a Comment