How to Start systemd Service After Ansible Playbook Execution

ansibleansible-playbookcentoslinuxsystemd

We are running ansible playbook on every boot and it does bunch of checks and configuration tasks on the host. We also have few systemd services that needs to run on that host. How do I make those services dependent on the ansible playbook completion? I want those services to run only after my ansible playbook execution is complete. Is there any direct way in systemd to establish that dependency or should I write some file on path after ansible completion and use that as a check in my systemd service file? Please let me know if you have a better way of doing this.

Best Answer

Create drop-ins for the unit definitions of the services you want to start after your script.

drop-ins are files that override directives in the original unit definition. They belong into directories with the schema /etc/systemd/system/<servicename>.service.d.

For a concrete example, let's use apache.

First you need to find out the current After= line of the unit definition. You can find the unit definition by running systemctl status:

$ systemctl status apache2
* apache2.service - The Apache HTTP Server
   Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)

Now let's take a look at /lib/systemd/system/apache2.service:

[Unit]
Description=The Apache HTTP Server
After=network.target remote-fs.target nss-lookup.target

The After= line is what we want to modify.

Next we create a directory for the drop-in files (You could have this created automatically using sudo systemctl edit apache2.service, but I want you to know how this works):

sudo mkdir /etc/systemd/system/apache2.service.d

Into this directory you can place one ore more drop in files.

sudo vi /etc/systemd/system/apache2.service.d/10-after-ansible.conf

This drop in file then only contains the lines we want to override:

[Unit]
After=network.target remote-fs.target nss-lookup.target my-ansible-script.service

Save the file and have systemd reload the service definitions:

sudo systemctl daemon-reload

From now on the apache2 service will only start after my-ansible-script ran.

You can add Requires= in the same file if needed.