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

如何编写Ansible断言任务,输出所有版本超标的主机?

Ansible 多主机版本校验断言任务实现

实现思路

先通过过滤器筛选出所有版本大于3的主机,再通过assert任务判断该列表是否为空,若不为空则输出包含所有违规主机的失败信息。

完整Playbook代码

- name: Validate host versions
  vars:
    # 筛选出version > 3的主机集合
    non_compliant_hosts: "{{ myvar | selectattr('version', '>', 3) | map(attribute='host') | list }}"
  assert:
    that:
      - non_compliant_hosts | length == 0
    fail_msg: "The following hosts have a version greater than 3: {{ non_compliant_hosts | join(', ') }}"

代码解释

  • 变量non_compliant_hosts:使用Ansible内置过滤器完成筛选:
    • selectattr('version', '>', 3):从myvar列表中筛选出version属性大于3的字典项
    • map(attribute='host'):提取筛选结果中的host字段
    • list:将结果转换为列表格式
  • assert任务:
    • that条件判断违规主机列表长度是否为0,若不为0则触发失败
    • fail_msg通过join(', ')将违规主机列表拼接为字符串,展示所有不符合要求的主机

内容的提问来源于stack exchange,提问作者Bruce Johnson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 13:43:13