【问题标题】:Insert a loop variable into json_query in a when condition (ansible)在 when 条件下将循环变量插入 json_query (ansible)
【发布时间】:2021-10-16 07:41:19
【问题描述】:

我有一个 json 查询,它在使用 set_fact 运行并使用调试显示时返回此结果:

'''
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**
```

中提到了循环变量

当条件总是评估为假时。任务是将服务器添加到文件中,如果它不存在的话。提到的 JSON_QUERY 是从另一个检查出现次数的任务中提取计数值。 JPTERM 中的查询也可以正常工作。`

【问题讨论】:

  • file: 不是这个模块的参数,我想是它的参数路径:而不是

标签: ansible json-query


【解决方案1】:

对于您的问题,我会像这样重写您的任务:

 ```
 **- 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 }}"

【讨论】:

    猜你喜欢
    • 2021-04-02
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    相关资源
    最近更新 更多