Ansible - 编辑 systemd 服务文件

Ansible - Edit a systemd service file

systemd 模块:https://docs.ansible.com/ansible/latest/collections/ansible/builtin/systemd_module.html

我正在寻找向服务文件添加条件的方法。

例如:

ConditionPathIsMountPoint=/mnt/myreplication/path/

这对 docker 安装很有用,确保 docker 不会在容器实际需要的安装可用之前启动容器。

遗憾的是,Ansible 现在似乎不支持添加它。我在那里是正确的吗?我需要手动添加还是使用 lineinfile?或者有其他方法吗?

编辑:这个问题似乎越来越受欢迎,所以我将添加:

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

这是对我的另一个问题的回答:https://askubuntu.com/a/1348117/1612

引用它:

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

Am I correct there?

对了,systemd_module不是用来操作服务文件的

因为我过去有过一些类似的问题,所以我想分享我的方法。

您可以维护自己的服务文件模板并进行部署

- 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

或通过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

并重新加载并重启服务

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

因此也可以使用 insertbeforeinsertafter

编辑:这个问题似乎越来越受欢迎,所以我将添加:

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

这是对我的另一个问题的回答:https://askubuntu.com/a/1348117/1612

引用它:

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

让我 post 使用 ini_file 对我有用的解决方案:

- 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/

这避免了重写原始服务文件,而是将专用覆盖添加到 .d 子目录中。

请注意 ini_file= 周围添加了空格,如

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

但这很好,参见 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.