如何将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
相关产品推荐
相关产品推荐

