【问题标题】:How to view the single service status via Ansible with modules rather than shell?如何通过 Ansible 使用模块而不是 shell 查看单个服务状态?
【发布时间】:2019-03-27 18:44:43
【问题描述】:

需要使用 Ansible playbook 检查多个系统上的单一服务状态,有没有办法使用服务模块而不是 shell 模块?

【问题讨论】:

    标签: ansible ansible-2.x ansible-facts


    【解决方案1】:

    使用service 模块(以及相关的更具体的模块,如systemd),您可以确保服务处于所需状态。

    例如,以下任务将启用 apache 在引导时启动(如果尚未配置),如果 apache 停止则启动 apache,如果进行任何更改则报告更改,如果不需要更改则报告 ok。

    - name: Enable and start apache
      service:
        name: apache
        enabled: yes
        state: started
    

    这些模块不支持只检查服务状态而不做任何更改。您将不得不使用命令行并分析输出/返回状态。

    systemd 示例

    - name: Check status of my service
      command: systemctl -q is-active my_service
      check_mode: no
      failed_when: false
      changed_when: false
      register: my_service_status
    
    - name: Report status of my service
      debug:
        msg: "my_service is {{ (my_service_status.rc == 0) | ternary('Up', 'Down') }}"
    

    注意:

    • check_mode: no 无论您是否在 ansible_playbook 命令行上使用“--check”,都可以让任务运行。如果没有这个,在检查模式下,下一个任务将因未定义的变量而失败。
    • failed_when: false 在返回码不为 0 时(未启动服务时)阻止任务失败。您可以通过列出正常情况下所有可能的返回码并在获得其他返回码时失败(例如failed_when: not (my_service_status in [0, 3, X]))来更具体
    • changed_when: false 使任务始终报告正常,但命令和 shell 模块默认情况下 changed 除外。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-01
      • 1970-01-01
      • 2016-06-29
      • 1970-01-01
      • 1970-01-01
      • 2019-04-21
      相关资源
      最近更新 更多