【问题标题】:How to return a message form shell script to Ansible playbook to Display as output如何将消息表单 shell 脚本返回到 Ansible playbook 以显示为输出
【发布时间】:2022-01-07 03:13:26
【问题描述】:

我正在通过 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 输出上,我该怎么做?

【问题讨论】:

    标签: shell ansible


    【解决方案1】:

    关于您最初的问题,您可能只是registerreturn value

    ---
    - 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 内置插件。

    如果你是running filebeat with systemd,你可以使用systemd_module。

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

    【讨论】:

    • 这不是作为服务安装的,我只是运行一个 filebeat 二进制文件来启动服务并杀死它来停止。在上述解决方案中,我如何运行我的 shell 文件?我试过 cmd: sh /path/get_status.sh "status",它的输出为 "msg": "result.stdout"
    • @Priya,关于您的异议“在上述解决方案中,我如何运行我的 shell 文件?”,您可以在命令行中调用它。我正在相应地更新示例。对于调试 puprose,您还可以将消息更改为 msg: "{{ result }}"
    猜你喜欢
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 2022-01-12
    • 2022-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多