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.
It seems to me that it would be easier to start those services at the end of the Ansible playbook rather than trying to implement that in systemd. I would just add:
to the end of the playbook. Ansible fails fast so that when that task is at the end of the play the completion of the rest of the tasks is ensured.
You could configure some variables if you say the playbook is generic, a short example:
Hosts file:
You run it against
- hosts: t
, at the end of the play: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 runningsystemctl status
:Now let's take a look at
/lib/systemd/system/apache2.service
: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):Into this directory you can place one ore more drop in files.
This drop in file then only contains the lines we want to override:
Save the file and have systemd reload the service definitions:
From now on the
apache2
service will only start aftermy-ansible-script
ran.You can add
Requires=
in the same file if needed.