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,并根据您的需求调整widgets和hosts。
systemctl list-units --type=mount
可以显示它们全部。 - Steve Crook