Ansible - Edit a systemd service file

Viewed 4343

The systemd module: https://docs.ansible.com/ansible/latest/collections/ansible/builtin/systemd_module.html

I'm looking for a way to add a Condition to the service file.

For instance:

ConditionPathIsMountPoint=/mnt/myreplication/path/

This would be useful for docker installations, ensuring docker doesn't start containers before a mount they need is actually available.

Sadly, it looks like Ansible doesn't support adding this right now. Am I correct there? Will I need to manually add it, or with lineinfile? Or is there an other way?

EDIT: This question appears to be getting views, so I'll add this:

https://askubuntu.com/questions/659267/how-do-i-override-or-configure-systemd-services

And this answer to another question of mine: https://askubuntu.com/a/1348117/1612

To quote it:

Don't edit files in /lib/systemd/ or /usr/share/systemd as they will get overwritten on updates.

3 Answers

Let me post a solution using ini_file that worked for me:

- name: Create a foo.service override directory
  file:
    owner: root
    group: root
    mode: 0755
    path: /etc/systemd/system/foo.service.d
    state: directory
- name: Set up foo.service override
  ini_file:
    dest: /etc/systemd/system/foo.service.d/bar_override.conf
    owner: root
    group: root
    mode: 0644
    section: Unit
    option: ConditionPathIsMountPoint
    value: /mnt/myreplication/path/

This avoids rewriting the original service file, but rather adds a dedicated override into a .d subdirectory.

Note that ini_file adds whitespace around = as in

[Unit]
ConditionPathIsMountPoint = /mnt/myreplication/path/

but this is fine, see systemd.syntax(7):

Each file is a plain text file divided into sections, with configuration entries in the style key=value. Whitespace immediately before or after the "=" is ignored.

Am I correct there?

Right, the systemd_module is not for manipulating service files.

Since I've had some similar questions in the past I like to share my approach.

You could either maintain your own service file template and deploy it

- name: "Make sure the systemd service file is correct"
  template:
    src: "{{ MYSERVICE }}.service.j2"
    dest: "/etc/systemd/system/{{ MYSERVICE }}.service"
    mode: 0755
  tags: install,systemd

or add the necessary line via lineinfile_module

- name: "Make sure the entry in '{{ MYSERVICE }}.service' exists"
  lineinfile:
    path: "/etc/systemd/system/{{ MYSERVICE }}.service"
    line: "ConditionPathIsMountPoint=/mnt/myreplication/path/"
    state: present
  tags: install,systemd

and reload and restart the service

- name: "Make sure the service is started and enabled via systemd"
  systemd:
    name: "{{ MYSERVICE }}"
    state: started
    enabled: yes
    daemon_reload: yes
  tags: install,systemd

whereby it might be good to use insertbefore or insertafter also.

Related