【问题标题】:How to skip some loops in Ansible playbook如何跳过 Ansible 剧本中的一些循环
【发布时间】:2020-05-15 11:11:20
【问题描述】:

我正在使用 Ansible,并且我有一本剧本,其中我有这样的任务:

- name: Get remote system names
  xml:
    xmlstring: "{{ item.xml }}"
    xpath: "/rpc-reply/lldp/lldp-system-name"
    content: text
  loop: "{{ topology.results }}"
  register: names

地点:

"topology": {
    "changed": false, 
    "msg": "All items completed", 
    "results": [............] }

所以我循环所有结果,在里面我从结果的每个项目中得到一个 item.xml []。然后,我收到一个特定的标签。我的问题是某些标签对 xpath: "/rpc-reply/lldp/lldp-system-name" 没有任何价值,所以我想跳过它或者只是用其他东西替换它,因为现在我得到一个错误并且我的任务失败了所以我的剧本不起作用很好。

有什么想法吗?

【问题讨论】:

  • 无法清楚了解如何获取标签以及内容是什么样的。如果您可以添加这些信息,将会很有帮助。还要检查when conditional 是否有任何帮助。您还可以使用default filter 分配默认值
  • 假设我的结果是这样的 "results": [ { "item":"A", "xml": [...my rpc-reply..] },{"item":"B", "xml": [...my rpc-reply...] } 。问题是 item:"A" 在我的 rpc-reply 的特定标记中有一个值,而 B 在那个 xml 标记中没有任何值。所以我在循环时遇到错误。 @Mamun 现在更清楚了吗?我还将编辑我的问题,以使其更清楚!!!
  • 错误是什么?
  • "xml": "\n-neighbors-information>"}, "msg": "Xpath /rpc-reply/lldp-neighbors-information/lldp-neighbor-information/lldp-remote-system-name 没有引用节点! "}@Mamun
  • 并且我检查了 rpc-reply 对“lldp-remote-system-name”没有任何值,而我的结果列表中的其他项目确实具有我成功检索的值! !

标签: xml loops ansible skip


【解决方案1】:

不确定这是否是最佳解决方案,但您可以这样做以跳过失败的项目。首先收集xpath匹配到一个变量的结果,忽略错误。然后遍历收集的结果并通过使用when: not item.failed跳过失败的项目来使用所需的数据。

- name: Get remote system names
  xml:
    xmlstring: "{{ item.xml }}"
    xpath: "/rpc-reply/lldp/lldp-system-name"
    content: text
  loop: "{{ topology.results }}"
  register: names
  ignore_errors: yes

- debug: var=item
  when: not item.failed
  with_items: "{{ names.results }}"

【讨论】:

  • 是的,它正在工作!我在文档中的任何地方都找不到这个 ignore_errors !!!非常感谢!!!!
  • 我的荣幸。 Here is the documentation
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-28
  • 1970-01-01
相关资源
最近更新 更多