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

如何在RHEL配置Playbook执行失败时自动运行sosreport

自动在失败的RHEL主机上生成sosreport的Ansible方案

刚好我之前处理过类似的需求,你可以借助Ansible的block-rescue错误处理结构,搭配内置的魔术变量来实现「任务失败时自动触发sosreport」的逻辑,完全不需要手动重新执行Playbook。

具体实现思路和代码

核心思路是把你的常规配置任务放在block块里,一旦block内任意任务执行失败,就自动进入rescue块执行故障排查操作(也就是生成sosreport)。

完整Playbook示例

- name: 配置RHEL系统并在失败时自动生成sosreport
  hosts: all
  gather_facts: true
  become: true
  tasks:
    - block:
        # ========== 这里放你原本的RHEL配置任务 ==========
        - name: 安装基础服务包
          dnf:
            name: [httpd, firewalld]
            state: present

        - name: 启动并设为开机自启httpd
          service:
            name: httpd
            state: started
            enabled: true

        # 更多你的配置任务...
      rescue:
        # ========== 失败后自动执行的操作 ==========
        - name: 生成带主机名和时间戳的sosreport
          command: sosreport --batch --tmp-dir /var/tmp/ --name "{{ inventory_hostname }}_failure_{{ ansible_date_time.iso8601_basic_short }}"
          register: sos_report_output

        - name: 打印生成的sosreport路径
          debug:
            msg: "主机 {{ inventory_hostname }} 执行失败,sosreport已生成:{{ sos_report_output.stdout_lines[-1] }}"

        # 可选:把报告拉取到控制节点归档
        - name: 将sosreport同步到控制节点
          fetch:
            src: "{{ sos_report_output.stdout_lines[-1] }}"
            dest: "./sos_reports/{{ inventory_hostname }}/"
            flat: yes

关键魔术变量说明

这里用到几个实用的魔术变量帮你精准处理故障场景:

  • inventory_hostname:当前执行任务的主机名,用来给sosreport命名,方便区分不同主机的报告
  • ansible_date_time.iso8601_basic_short:生成短格式时间戳,避免报告文件名重复
  • ansible_failed_task(可选):如果需要排查具体失败的任务,可以用这个变量查看详情,比如:
    - name: 输出失败任务详情
      debug:
        msg: "失败任务:{{ ansible_failed_task.name }},失败原因:{{ ansible_failed_task.msg }}"
    

额外优化建议

  • 提前安装sos包:如果你的RHEL系统没默认安装sos,可以在block开头加一个安装任务,避免rescue时找不到命令
  • 限制触发条件:如果只想在特定类型的失败下生成报告,可以给rescue任务加when条件,比如只在命令执行失败时触发:
    when: ansible_failed_task.action == 'command' or ansible_failed_task.action == 'dnf'
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:49:38