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

如何统计Ansible中未被跳过的循环实际执行次数?

统计Ansible循环实际执行次数

你当前的方法会返回5,因为with_list的每个条目都会在somedata.results里生成一条结果记录,不管when条件是否触发任务执行。要得到实际执行的次数,需要过滤掉那些被跳过的记录。

完整解决方案

  1. 给原任务添加register:
- name: this step
  debug:
    msg: "working on {{ item.name }}"
  when: not item.skip
  with_list: 
    - {name: t1, skip: True}
    - {name: t2, skip: False}
    - {name: t3, skip: False}
    - {name: t4, skip: False}
    - {name: t5, skip: True}
  register: somedata
  1. 过滤被跳过的记录并统计数量:
- debug:
    msg: "实际执行次数: {{ somedata.results | rejectattr('skipped', 'equalto', true) | list | length }}"

原理说明

Ansible循环的每个条目都会生成一条结果记录:

  • 当when条件不满足时,记录的skipped字段为true
  • 条件满足执行任务的记录,skipped字段为false或不存在

通过rejectattr('skipped', 'equalto', true)过滤器,可以剔除所有被跳过的记录,再用length统计剩余记录的数量,就是实际执行的次数(示例中会得到3)。

内容的提问来源于stack exchange,提问作者hitesh jetwani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 03:54:55