我有一个json查询,在使用set_fact运行并使用debug显示时返回此结果:
'''
Json_query: hits | community.general.json_query('results[?item==`xyz`].count')
debug output: TASK [debug] **********************************************************************************************************************************************
ok: [control] => {
"new_list8": "0"
}
Variable used in when conditional
matched: ["0"]
"
In the JSON_query, "xyz" needs to be substituted by a loop variable in when conditional:
```
**- name: test
community.general.xml:
file: '/home/cloud_user/ansible/ansible_playbook/dev/xmlfiles/test.xml'
#backup: yes
pretty_print: true
xpath: /x:AgentMap
namespaces:
x: http://xyz
add_children:
- env:
name: "{{ server|upper }}"
_:
- agent:
_:
- name: "{{ server }}"
with_items:
- "{{ servers }}"
when: matched[0] in (hits | community.general.json_query('results[?item==`" + server + "`].count'))
loop_control:
loop_var: server**
```
在
中提到了循环变量& lt; https://stackoverflow.com/questions/46038985/ansible-pass-a-variable-in-a-json-query-filter>
当条件总是求值为false时。任务是添加一个服务器到文件中,如果它还不存在。前面提到的JSON_QUERY是从另一个检查出现次数的任务中提取计数值。在JPTERM中查询也可以。'
对于你的问题,我重写你的任务如下:
```
**- name: test
community.general.xml:
file: '/home/cloud_user/ansible/ansible_playbook/dev/xmlfiles/test.xml'
#backup: yes
pretty_print: true
xpath: /x:AgentMap
namespaces:
x: http://xyz
add_children:
- env:
name: "{{ item|upper }}"
_:
- agent:
_:
- name: "{{ item }}"
when: matched[0] in (hits | community.general.json_query('results[?item==`" ~ item ~ "`].count'))
with_items:
- "{{ servers }}"
<代码>代码>
不能在json_query中使用可见变量。
在变量中指定jmespath语句,
在json_query 中使用PP_5