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

Ansible循环收集失败任务并打印汇总遇错,求技术支持

问题分析与修正方案

你的Ansible任务存在语法和逻辑错误,以下是修正后的完整代码及说明:

错误点说明

  • 单个Ansible任务只能调用一个模块,你在Summary of Jobs任务中同时使用set_fact和fail模块,这是不允许的。
  • set_facts是拼写错误,正确模块名为set_fact。
  • 列表拼接逻辑错误,需将字符串作为列表元素添加,应使用+ ["描述文本"]格式,而非直接拼接字符串到列表。
  • 判断列表长度的语法错误,Ansible中需用failed_tests | length >= 1,而非failed_tests.length()。
  • 最后打印失败任务的任务语法错误,需用debug模块输出内容。
  • 任务失败时stdout可能不存在,优先使用stderr或结合default过滤器避免未定义错误。

修正后的完整代码

# 原有的检查任务保持不变
- name: Check the nslookup status 
  shell: nslookup mydomain.com
  register: nslookup_result
  ignore_errors: yes

- name: Check the Time date status
  shell: timedatectl status 
  register: timedatectl_result
  ignore_errors: yes 

- name: Check Date
  shell: date
  register: date_result
  ignore_errors: yes

# 收集失败任务信息
- name: Collect failed test information
  set_fact:
    failed_tests: "{{ failed_tests | default([]) + [item.task_name ~ ' 执行失败,错误信息: ' ~ (item.result.stderr | default(item.result.msg | default('无详细错误')))] }}"
  loop:
    - { task_name: "DNS查询(nslookup)", result: "{{ nslookup_result }}" }
    - { task_name: "时间服务状态检查(timedatectl)", result: "{{ timedatectl_result }}" }
    - { task_name: "日期检查(date)", result: "{{ date_result }}" }
  when: item.result.failed is defined and item.result.failed

# 判断是否有失败任务并终止(可选)
- name: Fail if any tests failed
  fail:
    msg: "存在失败的检查任务,详情如下:\n{{ failed_tests | join('\n') }}"
  when: failed_tests is defined and failed_tests | length >= 1

# 打印失败任务列表(如果不需要终止,可单独保留此任务)
- name: Print failed tests summary
  debug:
    msg: "{{ item }}"
  loop: "{{ failed_tests | default([]) }}"
  loop_control:
    label: "{{ item.split(':')[0] }}"

代码说明

  1. 收集失败信息:通过loop遍历每个任务结果,将任务名称和错误信息以字符串形式添加到failed_tests列表,同时处理错误信息可能未定义的场景。
  2. 失败终止逻辑:若存在失败任务,直接输出所有错误信息并终止Playbook,也可注释此任务,仅保留打印逻辑。
  3. 打印失败列表:用debug模块循环输出每个失败任务的信息,loop_control的label用来简化输出标签,让结果更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 21:31:11