大网数据广告活动
服务器运维问答

use a variable inside json_query in ansible/jinja

· 52CE 我爱测

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 ho…

问题原文

原帖链接 · peyoz · CC BY-SA 4.0

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!

已采纳解答

原帖链接 · Fran · CC BY-SA 4.0

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'

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2018-05-17)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。