如何将消息表单shell脚本返回到Ansible playbook以显示为输出



我正在通过剧本运行shell脚本

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

我的shell脚本是get_status.sh

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

我想让shell脚本的这个echo语句在ansible输出上,我该怎么办?

对于您最初的问题,您可以只注册返回值。

---
- hosts: test
become: no
gather_facts: no
tasks:
- name: Verify service status
shell:
cmd: "/home/{{ ansible_user }}/test.sh"
warn: false
changed_when: false
check_mode: false
register: result
- name: Show result
debug:
msg: "{{ result.stdout }}"

导致的输出

TASK [Show result] *******
ok: [test1.example.com] =>
msg: RUNNING
  • 使用Ansible显示远程命令的输出

如果您的服务以与其他服务相同的方式安装在系统中,那么更好的方法可能是使用Ansible内建。

  • 如何检查Ansible中是否存在服务
  • 使用Ansible检查服务是否存在
  • 如何通过Ansible获取服务状态

如果使用systemd运行filebeat,则可以使用systemd_module。

- name: Make sure service is started
systemd:
name: filebeat
state: started

最新更新