【问题标题】:How to parse a XML response in ansible?如何在 ansible 中解析 XML 响应?
【发布时间】:2018-04-16 21:42:56
【问题描述】:

我正在运行 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

错误: 没有找到预期的密钥

非常感谢任何帮助。

【问题讨论】:

    标签: xml-parsing ansible


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-17
      • 2015-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多