You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ansible循环中提取执行失败任务的Item值

没问题,这事儿好办!你只需要给循环任务注册结果,再用Ansible的过滤器就能轻松提取出那些检查失败的IP了。我给你整理好修改后的Playbook和详细解释:

解决方案:提取Ansible循环中失败的IP项

修改后的完整Playbook

- hosts: localhost
  connection: local
  gather_facts: no
  tasks:
    - name: Get list of IP addresses
      shell: cat /home/file
      register: ip_addrs

    - name: Check SSH port
      wait_for:
        host: "{{ item }}"
        port: 22
        timeout: 5
      with_items: "{{ ip_addrs.stdout_lines }}"
      ignore_errors: true
      register: port_check_results  # 注册循环任务的所有执行结果

    - name: Extract failed IPs into variable
      set_fact:
        failed_ips: "{{ port_check_results.results | selectattr('failed', 'equalto', true) | map(attribute='item') | list }}"

    - name: Verify failed IPs (optional)
      debug:
        var: failed_ips

关键步骤解释

  1. 注册循环结果
    给Check SSH port任务加上register: port_check_results后,Ansible会把循环中每一次任务的执行状态、目标IP(item字段)等信息,统一存在port_check_results.results这个列表里。

  2. 筛选失败IP
    利用Ansible的过滤器链精准提取故障IP:

    • selectattr('failed', 'equalto', true):从结果列表中筛选出所有执行失败(超时也算失败)的条目
    • map(attribute='item'):从这些失败条目中提取对应的IP地址(也就是循环中的item值)
    • list:把最终结果转换成列表格式,方便后续任务调用
  3. 后续使用
    现在failed_ips变量就存储了所有SSH端口检查失败的IP,你可以直接在后续任务中调用它,比如执行二次连通性检查、发送告警通知等。

执行完成后,failed_ips会输出类似['1.1.1.3']的结果,完全符合你要的需求。

内容的提问来源于stack exchange,提问作者Semka Mesilov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:49:51