use a variable inside json_query in ansible/jinja
7,430
You can use a task variable:
- 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'
Related videos on Youtube
Author by
peyoz
Updated on September 18, 2022Comments
-
peyoz over 1 year
I'm trying to loop on a custom dictionary in ansible in order to check some mount points on a linux server, and I'm a little bit in trouble finding the correct solution, find below my playbook right now:
- 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 == '/' "
I was trying to build a custom loop to cycle on the dictionary entries and make the same kind of check with less code, something like that
- name: Check Dev loop assert: that: "'{{ item.value.lvm_device }}' == '{{ ansible_mounts | json_query('[?mount == `{{item.key}}` ] | [0].device') }}'" with_dict: "{{ fs_configuration }}"
But I'm not able to expand the variable inside json_query ({{item.key}}). I suppose there is way to escape or pass the variable but I can not find a solution. I prefer to make a single loop instead of writing multiple tasks to check all the filesystems
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 } } }
Thanks!
-
peyoz about 6 yearsAwesome solution, I wonder why I did not thought about it.. Many Thanks Fra!