How to parse a XML response in ansible?

瘦欲@ 提交于 2020-06-17 07:17:15

问题


I'm running the panos_op ansible module and struggling to parse the output.

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

This is as close as I can get to assigning the value for "result".

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

My goal is to set a conditional loop for the ansible task.

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

How can I make this work?

UPDATE: I've tried it another way, but now I have a new issue trying to deal with a literal "<" char.

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

ERROR: did not find expected key

Any help at all would be very appreciated.


回答1:


As I just mentioned in another answer, since Ansible 2.4, there's an xml module.

Playbook

---
- 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"

Output

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


来源:https://stackoverflow.com/questions/49866698/how-to-parse-a-xml-response-in-ansible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!