如何在ansible中解析XML响应?

时间:2018-04-16 21:42:57

标签: 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

我该如何做到这一点?

更新:我已经尝试了另一种方式,但现在我有一个新问题试图处理文字“&lt;”炭。

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

错误:     找不到预期的关键

任何帮助都将非常感激。

1 个答案:

答案 0 :(得分:0)

正如我刚才提到的那样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