xml-parsing - 如何解析 ansible 中的 XML 响应?

标签 xml-parsing ansible

我正在运行 panos_op ansible 模块并努力解析输出。

ok: [localhost] => {
  "result": {
    "changed": true, 
    "failed": false, 
    "msg": "Done", 
    "stdout": "{\"response\": {\"@status\": \"success\", \"result\": \"no\"}}", 
    "stdout_lines": [
        "{\"response\": {\"@status\": \"success\", \"result\": \"no\"}}"
    ], 
    "stdout_xml": "<response status=\"success\"><result>no</result></response>"
  }
}

这已经接近于为“结果”赋值了。

ok: [localhost] => {
  "result.stdout": {
    "response": {
        "@status": "success", 
        "result": "no"
    }
  }
}

我的目标是为 ansible 任务设置一个条件循环。

tasks:
- name: Checking for pending changes
panos_op:
  ip_address: '{{ host }}'
  password: '{{ operator_pw }}'
  username: '{{ operator_user}}'
  cmd: 'check pending-changes'
register: result
until: result.stdout.result = no
retries: 10
delay: 5
tags: check

我怎样才能让它工作?

更新:我试过另一种方法,但现在我遇到了一个新问题,试图处理文字“<”字符。

tasks:
- name: Checking for pending changes
panos_op:
  ip_address: '{{ host }}'
  password: '{{ operator_pw }}'
  username: '{{ operator_user}}'
  cmd: 'check pending-changes'
register: result

- fail:
   msg: The Firewall has pending changes to commit.
 when: '"<result>no"' not in result.stdout_xml

错误: 没有找到预期的 key

如有任何帮助,我们将不胜感激。

最佳答案

正如我刚才提到的 in another answer , 从 Ansible 2.4 开始,有 an xml module .

剧本

---
- hosts: localhost
  gather_facts: false

  tasks:
    - name: Get result from xml.
      xml:
        xmlstring: "<response status=\"success\"><result>no</result></response>"
        content: "text"
        xpath: "/response/result"

输出

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

TASK [Get result from xml.] ****************************************************
ok: [localhost] => changed=false
  actions:
    namespaces: {}
    state: present
    xpath: /response/result
  count: 1
  matches:
  - result: 'no'
  msg: 1
  xmlstring: |-
    <?xml version='1.0' encoding='UTF-8'?>
    <response status="success"><result>no</result></response>

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

关于xml-parsing - 如何解析 ansible 中的 XML 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49866698/

相关文章:

javascript - 使用 Xml.parse() 删除标签内容与值数组匹配的 html 标签和内容

python - 逗号出现在自定义 Ansible 查找插件返回的值中

ansible - 是否可以使用 Ansible Playbook 将 with_dict 和 with_nested 一起循环?

java - XSD 导入问题

xml - &lt;! ... !> 在 XML 中是什么意思?

Python BeautifulSoup 不会从 XML 返回标签

xml - 在 R 中解析 XML 文件(>1 MB)

docker - docker_container:如何添加多个卷

ansible - 在 Ansible + Test Kitchen 中包含依赖项

ssh - Ansible:SSH 错误:unix_listener:对于 Unix 域套接字来说太长