我正在尝试在 ansible 中循环自定义字典以检查 Linux 服务器上的某些挂载点,但在寻找正确的解决方案时遇到了一些麻烦,请在下面找到我的剧本:
- name: Check lvm devs
hosts: localhost
vars:
vg_os: vg_root
fs_configuration:
- /:
lvm_device: "/dev/mapper/{{ vg_os }}-lv_root"
lvm_size: 8589934592
- /var:
lvm_device: "/dev/mapper/{{ vg_os }}-lv_var"
lvm_size: 6442450944
- /var/crash:
lvm_device: "/dev/mapper/{{ vg_os }}-lv_crash"
lvm_size: 6442450944
- test:
lvm_device: "/dev/mapper/{{ vg_os }}-lv_crash"
lvm_size: 6442450944
tasks:
- name: Debug dict
debug:
msg: "{{ fs_configuration }}"
- name: Check Dev /
assert:
that: "'{{ item.value.lvm_device }}' == '{{ ansible_mounts | json_query('[?mount == `/` ] | [0].device') }}'"
with_dict: "{{ fs_configuration }}"
when: " item.key == '/' "
我试图构建一个自定义循环来循环字典条目,并用更少的代码进行相同类型的检查,类似这样的
- name: Check Dev loop
assert:
that: "'{{ item.value.lvm_device }}' == '{{ ansible_mounts | json_query('[?mount == `{{item.key}}` ] | [0].device') }}'"
with_dict: "{{ fs_configuration }}"
但我无法扩展 json_query 中的变量({{item.key}})。我想有办法转义或传递变量,但我找不到解决方案。我更喜欢制作一个循环,而不是编写多个任务来检查所有文件系统
failed: [localhost] (item={'value': {u'lvm_size': 8589934592, u'lvm_device': u'/dev/mapper/vg_root-lv_root'}, 'key': u'/'}) => {
**"assertion": "'/dev/mapper/vg_root-lv_root' == ''",** <-- not working
"changed": false,
"evaluated_to": false,
"item": {
"key": "/",
"value": {
"lvm_device": "/dev/mapper/vg_root-lv_root",
"lvm_size": 8589934592
}
}
}
谢谢!
答案1
您可以使用任务变量:
- name: Check Dev loop
assert:
that: "'{{ item.value.lvm_device }}' == '{{ ansible_mounts | json_query(query) }}'"
with_dict: "{{ fs_configuration }}"
vars:
query: '[?mount == `{{ item.key }}` ] | [0].device'