首页 > 解决方案 > 如何从 Ansible 中的 xml 响应中读取和检索多个值

问题描述

我正在使用 Ansible,我正在尝试从一个 xml 中检索多个标签的值。我找到了如何从 1 个标签中检索值,但我需要从许多不同的标签中检索值。特别是,我知道如果你想检索 1 个标签的值,你可以在你的剧本中这样做:How to parse a XML response in ansible?

所以我可以使用这个 xml 模块,但是如果我想拥有多个 'xpath' 怎么办?

标签: xmlansibleyaml

解决方案


如果我理解正确并基于您链接中提供的示例。我会使用带有子键的 Ansible 循环:

剧本.yml

---
- hosts: localhost
  gather_facts: no
  tasks:
    - name: Retrieve multiple xml tags value
      xml:
        xmlstring: "{{ item.string }}" 
        xpath: "{{ item.path }}"
        content: text 
      loop: 
        - { path: "/value", string: "<value>foo</value>" }
        - { path: "/tag/other-value", string: "<tag><other-value>bar</other-value></tag>" }
      register: tags_value 

    - debug:
        msg: "{{ item.matches }}"
      loop: "{{ tags_value.results }}"
      loop_control:
        label: "{{ item.matches }}"

结果

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

TASK [Retrieve multiple xml tags value] ********************************************************************************************************************************************************************
ok: [localhost] => (item={u'path': u'/value', u'string': u'<value>foo</value>'})
ok: [localhost] => (item={u'path': u'/tag/other-value', u'string': u'<tag><other-value>bar</other-value></tag>'})

TASK [debug] ***********************************************************************************************************************************************************************************************
ok: [localhost] => (item=[{u'value': u'foo'}]) => {
    "msg": [
        {
            "value": "foo"
        }
    ]
}
ok: [localhost] => (item=[{u'other-value': u'bar'}]) => {
    "msg": [
        {
            "other-value": "bar"
        }
    ]
}

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

推荐阅读