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

如何将Shell脚本的echo内容返回至Ansible playbook并作为输出展示

实现方法

你只需要给现有任务添加register参数捕获脚本输出,再通过debug模块打印即可,修改后的playbook配置如下:

- name: Get status of Filebeat
  shell: sh /path/get_status.sh "status"
  register: filebeat_status_result
  when: action == "status"

- name: Print Filebeat status
  debug:
    msg: "{{ filebeat_status_result.stdout }}"
  when: action == "status"
  • 这里register会把shell模块的所有执行结果存储到你自定义的变量(示例中为filebeat_status_result)中,脚本echo输出的内容会默认存在该变量的stdout属性里
  • 如果需要同时捕获脚本的标准错误输出,可以打印filebeat_status_result.stderr
  • 如果不需要单独加debug任务,也可以直接给shell任务添加verbosity: 0参数,或者执行ansible-playbook命令时加上-v参数,即可直接在shell任务的执行日志里看到脚本输出,不过单独配置debug任务的输出更直观,也方便后续扩展其他逻辑判断

额外注意你当前提供的get_status.sh脚本末尾缺少if判断的闭合语句fi,运行前需要补全,否则会执行报错,补全后脚本如下:

SERVICE="filebeat"
if pgrep -x "$SERVICE" >/dev/null
then
  echo "$SERVICE is running"
else
  echo "$SERVICE is stopped"
fi

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 01:15:03