如何使用 Ansible playbook 从 SOAP API 响应中获取标签值?

问题描述 投票:0回答:1

问题陈述

我们正在使用 Ansible 在 Windows 主机上运行 SOAP API 并尝试从 API 响应中获取值,但是,由于无效的 XPath 异常,我们无法获取值。

本活动的主要目的是了解

errorCode
标签的价值。但是,无法获取该值。

下面是我们正在尝试的示例剧本:

---
- name: execute soap api
  ansible.windows.win.uri:
    url: " "
    method: POST
    body: |
      < body of the soap>
    headers:
      Content-Type: "text/xml: charset=utf-8"
    status_code: 200
    return_content: yes
    validate_certs: false
  register: api_response

- name: set the content of the file
  ansible.windows.win.copy:
    content: "{{ api_response.content }}"
    dest: C:\Temp\response.xml

- name: get result from xml
  community.windows.win.xml:
    path: C:\Temp\response.xml
    content: "xml"
    xpath: "/S:Envelope/S:Body/ns10:xyz/retrun/responseservice:status/responseservice:errorCode"
  register: soap_result

- name: display soap result
  debug:
    var: soap_result

下面是 SOAP API 响应示例:

"<?xml version='1.0' encoding='UTF-8'?>
<S:Envelope xmlns:S=\" ***\">
   <S:Body>
     <ns10:xyz xmlns:responseservice=\" ***\">
       <return>
         <responseservice:status>
            <responseservice:errorCode>0</responseservice:errorCode>
         </responseservice:status>
       </return>
     </ns10:xyz>
   </S:Body>
</S:Envelope>"

以下是我们收到的消息:

msg: "The supplied xpath did not match any nodes. If this is unexpected , check your xpath is valid for the xml file at supplied path

期待

我们期望从上面的 SOAP API 响应中获取

errorCode
标签的值,即
0

xml ansible
1个回答
0
投票

对于有效的 XML 文件

response.xml
,内容为

<?xml version='1.0' encoding='UTF-8'?>
<S:Envelope xmlns:S=" ***">
   <S:Body>
     <ns10:xyz xmlns:responseservice=" ***">
       <return>
         <responseservice:status>
            <responseservice:errorCode>0</responseservice:errorCode>
         </responseservice:status>
       </return>
     </ns10:xyz>
   </S:Body>
</S:Envelope>

一个最小的示例手册

---
- hosts: localhost
  gather_facts: false

  vars:

    XML: "{{ lookup('file', 'response.xml') }}"
    YML: "{{ XML | ansible.utils.from_xml }}"

  tasks:

  - debug:
      msg: "{{ YML['S:Envelope']['S:Body'] | json_query('*.return') }}"

将产生

的列表输出
TASK [debug] ***********************
ok: [localhost] =>
  msg:
  - responseservice:status:
      responseservice:errorCode: '0'

类似的任务

  - debug:
      msg: "{{ YML['S:Envelope']['S:Body'] | json_query('*.return.*') | flatten | first }}"

只是结果

TASK [debug] *********************
ok: [localhost] =>
  msg:
    responseservice:errorCode: '0'

感谢

© www.soinside.com 2019 - 2024. All rights reserved.