ansible-json_query将布尔值与外部变量进行比较

时间:2018-12-21 17:23:33

标签: ansible jinja2

我正在尝试通过将dict的值与我的剧本的另一个变量进行比较来对json_query内部的ansible进行测试:

我的字典:

cust_pkg:
  - { name: "a" }
  - { name: "b", web: true }

我想要作为输出:

当web_host为true

dict_pkg:
  - { name: "a" }
  - { name: "b", web: true }

否则(web_host为false或未定义)

 dict_pkg:
  - { name: "a" }

我正在这样尝试:

- set_fact:
    dict_pkg: "{{ cust_pkg | json_query(\"[?web == '\" + web_host + \"']\") }}"

但是,我遇到了这个错误:

{"msg": "Unexpected templating type error occurred on ({{ cust_pkg | json_query(\"[?web == '\" + web_host + \"']\") }}): cannot concatenate 'str' and 'bool' objects"}

然后如何根据外部布尔变量进行过滤?

谢谢

2 个答案:

答案 0 :(得分:0)

  

无法连接“ str”和“ bool”对象

您希望错误消息更清晰?

您想要的是将该值显式强制为str,以便类型匹配:

dict_pkg: "{{ cust_pkg | json_query(\"[?web == `\" + (web_host|lower) + \"`]\") }}"

接下来,您可能需要考虑更改yaml构造,以避免引用地狱:

dict_pkg: >-
   {{ cust_pkg | json_query("[?web == `" + (web_host|lower) + "`]") }}

答案 1 :(得分:0)

谢谢,就是这样了:

---
- hosts: localhost
  gather_facts: false
  vars:
    cust_pkg:
      - { name: "a" }
      - { name: "b", web: true }

  tasks:

  - name: Step 1
    debug:
      msg: "{{ cust_pkg | json_query(\"[?web == nul || web == `\" + (web_host|default('false')|lower) + \"`]\") }}"

输出:

$ ansible-playbook test.yml

PLAY [localhost] ***************************************************************

TASK [Step 1] ******************************************************************
ok: [localhost] => {
    "msg": [
        {
            "name": "a"
        }
    ]
}

PLAY RECAP *********************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0   

并且:

$ ansible-playbook test.yml --extra-vars="web_host=true"

PLAY [localhost] ***************************************************************

TASK [Step 1] ******************************************************************
ok: [localhost] => {
    "msg": [
        {
            "name": "a"
        }, 
        {
            "name": "b", 
            "web": true
        }
    ]
}

PLAY RECAP *********************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0