如何在 Ansible 中过滤 XML 属性?

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

下面的输出是日志消息,我需要检索

log
count
,即
5

代码

name: get system log count
connection: local
xml:
  xmlstring: "{{log.content}}"
  content: attribute
  xpath: '/response/result/log/logs[@count]
register: log_count

name: print log count
debug:
  msg: "{{ log_count.matches }}"

输出

ok: [10.46.255.101] => {
    "msg": {
        "actions": {
            "namespaces": {},
            "state": "present",
            "xpath": "/response/result/log/logs[@count]"
        },
        "changed": false,
        "count": 1,
        "failed": false,
        "matches": [
            {
                "logs": {
                    "count": "5",
                    "progress": "100"
                }
            }
        ]

如何过滤日志计数并将其用作下一个任务的条件? 如何修改此代码以将

count
(5) 的值存储在变量中,并将其用作下一个任务的条件?我尝试使用
log_count.matches.count
但不起作用。

基本上我试图从这个输出中获取计数值

<response status="success"><result>
  <job>
    <tenq>05:03:36</tenq>
    <tdeq>05:03:36</tdeq>
    <tlast>05:03:36</tlast>
    <status>FIN</status>
    <id>90</id>
  </job>
  <log>
    <logs count="0" progress="100"/>
  </log>
</result></response>
xml filter ansible
1个回答
0
投票

问:“我正在尝试从此输出中获取

count
值_”

基于 How to fetch value from API response with Ansible playbook?,一个最小的示例 playbook

---
- hosts: localhost
  become: false
  gather_facts: false

  vars:

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

  tasks:

  - debug:
      msg: "{{ YML }}"

  - name: Logs count
    debug:
      msg: "{{ YML.response.result.log.logs['@count'] }}"

将产生

的输出
TASK [debug] *****************
ok: [localhost] =>
  msg:
    response:
      '@status': success
      result:
        job:
          id: '90'
          status: FIN
          tdeq: 05:03:36
          tenq: 05:03:36
          tlast: 05:03:36
        log:
          logs:
            '@count': '0'
            '@progress': '100'

TASK [Logs count] ************
ok: [localhost] =>
  msg: '0'

问:“如何在下一个任务中使用它作为条件?

示例中

  - fail:
      msg: No logs!
    when: YML.response.result.log.logs['@count'] | int < 1

产生

的输出
TASK [fail] ********************************
fatal: [localhost]: FAILED! => changed=false
  msg: No logs!
© www.soinside.com 2019 - 2024. All rights reserved.