Ansible systemd 挂载依赖

3

我使用Ansible将systemd单元文件部署到所有服务器并启用其在开机时自动启动。 在其中一些服务器上,单元文件中定义的二进制文件位于不同的文件系统上。 这需要单元文件依赖于该文件系统被挂载。例如:

[Unit]
Description = Start the widget
After = network.target usr.mount

[Service]
Type = simple
ExecStart = /usr/bin/widget

[Install]
WantedBy = multi-user.target

目前单元文件是使用Ansible作为静态文件进行部署,采用ansible.builtin.copy模块。是否有一种方法可以将其转换为一个模板,并向After=附加挂载点(mountpoint),如果/usr是挂载点。


“/usr” 是否会自动转换为 “usr.mount”,还是需要进行映射?例如,“/usr/local/” 也可能是挂载点。 - Vladimir Botka
@VladimirBotka 看起来是通过将 / 替换为 - 进行翻译的。例如,/usr/local 变成了 usr-local.mount。运行 systemctl list-units --type=mount 可以显示它们全部。 - Steve Crook
2个回答

2

Ansible的事实(fact)ansible_mounts保存着挂载点列表。让我们使用以下变量进行测试:

    widgets:
      - /usr/local/apps/widget
      - /usr/share/apps/widget
      - /scratch/apps/widget
    my_ansible_mounts:
      - mount: /
      - mount: /boot/efi
      - mount: /usr
      - mount: /usr/local
    root:
      - /

创建一个小部件及其相关挂载点的字典,例如:
    - set_fact:
        _mlist: []
    - set_fact:
        _mlist: "{{ _mlist + [{'dict': item.0, 'mount': item.1}] }}"
      with_nested:
        - "{{ widgets }}"
        - "{{ my_ansible_mounts|map(attribute='mount')|difference(root) }}"
      when: item.0|regex_search('^' ~ item.1) != None
    - set_fact:
        _mdict: {}
    - set_fact:
        _mdict: "{{ _mdict|combine({item.0: item.1|
                                            map(attribute='mount')|
                                            map('regex_replace', '/', '-')|
                                            list}) }}"
      loop: "{{ _mlist|groupby('dict') }}"

提供

  _mdict:
    /usr/local/apps/widget:
    - -usr
    - -usr-local
    /usr/share/apps/widget:
    - -usr

那么流程应该很简单,例如:
    - debug:
        msg: |-
          {% if _mdict[item]|default([])|length > 0 %}
          [Unit]
          Description = Start the widget
          After = network.target{% for i in _mdict[item] %} {{ i[1:] }}.mount{% endfor %}


          {% endif %}
          [Service]
          Type = simple
          ExecStart = {{ item }}
      loop: "{{ widgets }}"

提供

ok: [localhost] => (item=/usr/local/apps/widget) => 
  msg: |-
    [Unit]
    Description = Start the widget
    After = network.target usr.mount usr-local.mount
  
    [Service]
    Type = simple
    ExecStart = /usr/local/apps/widget
ok: [localhost] => (item=/usr/share/apps/widget) => 
  msg: |-
    [Unit]
    Description = Start the widget
    After = network.target usr.mount
  
    [Service]
    Type = simple
    ExecStart = /usr/share/apps/widget
ok: [localhost] => (item=/scratch/apps/widget) => 
  msg: |-
    [Service]
    Type = simple
    ExecStart = /scratch/apps/widget

为了测试真实内容,在代码中,将my_ansible_mounts替换为ansible_mounts,并根据您的需求调整widgetshosts


0

只需使用模板任务,在src模板任务中设置一个条件,根据条件打印所需的块。您可以将变量传递给模板任务,并根据它做出决策,例如,您首先检查任务中是否需要该文件系统,然后基于模板任务生成文件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接