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

如何在Ansible Playbook中同时保存命令的正常输出与错误信息到文件?

问题描述

编写Ansible Playbook执行两条命令并将输出保存到文件时,只能捕获命令的正常输出,无法捕获错误信息。比如查询ChessX服务状态时,系统返回错误Unit chessx.service could not be found.,但该信息没有保存到out.txt中,文件内SERVICE字段为空。

现有Playbook代码:

---
- hosts: chapter1
  become: yes
  ignore_errors: no
  tasks:
    - name: Q1. Find RAM
      ansible.builtin.shell: free -h | grep Mem | awk {'print $2'}
      register: ram
    - debug: var=ram.stdout_lines

    - name: Q2. Find status
      ansible.builtin.shell: systemctl status chessx | grep Active | awk '{print $2$3}'
      register: chessStatus
    - debug: var=chessStatus.stdout_lines

    - name: Q3. Save content to file in /home/gwen/Desktop/out.txt
      ansible.builtin.copy:
        content: |
          RAM={{ ram.stdout }}
          SERVICE={{ chessStatus.stdout }}
        dest: /home/gwen/Desktop/out.txt

当前out.txt内容:

RAM=2.9Gi
SERVICE=

解决方案

要捕获错误信息并写入文件,需要做两处关键修改:

1. 允许任务执行失败时继续运行

在查询服务状态的任务中添加ignore_errors: yes,这样即使systemctl status chessx执行失败,Ansible也不会终止Playbook,同时会把错误信息保存到注册变量的stderr字段中。

2. 优先读取错误输出,无错误时用正常输出

在保存文件的步骤里,修改SERVICE字段的取值逻辑:如果存在错误输出就用错误信息,否则用正常输出。借助Ansible的default过滤器就能实现这个逻辑。

修改后的完整Playbook

---
- hosts: chapter1
  become: yes
  ignore_errors: no
  tasks:
    - name: Q1. Find RAM
      ansible.builtin.shell: free -h | grep Mem | awk {'print $2'}
      register: ram
    - debug: var=ram.stdout_lines

    - name: Q2. Find status
      ansible.builtin.shell: systemctl status chessx | grep Active | awk '{print $2$3}'
      register: chessStatus
      ignore_errors: yes  # 新增:允许任务失败,不中断后续流程
    - debug: var=chessStatus.stdout_lines
    - debug: var=chessStatus.stderr_lines  # 可选:调试查看错误输出内容

    - name: Q3. Save content to file in /home/gwen/Desktop/out.txt
      ansible.builtin.copy:
        content: |
          RAM={{ ram.stdout }}
          SERVICE={{ chessStatus.stderr | default(chessStatus.stdout) }}
        dest: /home/gwen/Desktop/out.txt

修改后效果

当chessx.service不存在时,out.txt内容会变为:

RAM=2.9Gi
SERVICE=Unit chessx.service could not be found.

如果服务存在且正常运行,SERVICE字段会显示正常的状态信息(比如active(running))。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 02:00:18