【问题标题】:How to get system status using Ansible如何使用 Ansible 获取系统状态
【发布时间】:2020-11-26 09:31:36
【问题描述】:

我有一个简单的ansible playbook 来获取etcd 服务的状态,如下所示。

- name: Check if etcd service is running
  command: systemctl status etcd
  register: result
  ignore_errors: yes

起初该服务可能没有运行

所以如果服务没有运行,我想启动它。所以一定是有条件的检查,我是这样做的:


- name: showing report
  debug:
    var: result.ansible_facts.services["etcd.service"].state  

但这会产生如下错误:

TASK [显示报告] ****************************************** ****************** 好的:[35.236.98.212] => { "result.ansible_facts.services["etcd.service"].state": "变量未定义!"

如何查看etcd 服务的状态,如果它未运行我想启动该服务,如果它已经在运行,请离开照原样。

有人可以帮帮我吗?

【问题讨论】:

    标签: ansible


    【解决方案1】:

    您在 IMO 混淆了很多东西。如果您注册结果,shell 会有效地返回一些信息。但结果不会包含任何ansible_facts.services 条目。

    此名称与service_facts module 返回的名称相似。您需要运行它来填充主机事实中的相应信息:

    - name: Get service facts for all hosts in play
      service_facts:
    
    - name: dummy task to show it worked
      debug:
        var: ansible_facts.services
    

    现在您还应该了解 ansible 是关于描述您正在连接的远程目标的预期状态。在服务方面,如果您想确保某个特定的服务已启动并始终在启动时启动(并且理所当然地由 systemd 管理),您所要做的就是:

    - name: Make sure etcd is started and enabled
      systemd:
        name: etcd
        state: started
        enabled: true
    

    此任务将:

    • 在启动时启用etcd(如果尚未启用)
    • 如果 etcd 尚未启动,则启动它
    • 什么都不做,如果它已启用并启动,则只报告“OK”。

    更一般地说,当已经有一个 ansible 模块在做这项工作时,您应该避免使用 shell/command

    【讨论】:

      【解决方案2】:

      你可以在这里使用 service_facts 模块

      例如

      - hosts: hostgroup
        gather_facts: false
        become: yes 
        tasks:
        - name: Return service state information as fact data
          service_facts:
      
        - name: Show the status of etcd service
          debug:
            var: ansible_facts.services['etcd.service']['state']
      
        - name: Start etcd service if its not running
          service:
            name: etcd.service
            state: started
          when: ansible_facts.services['etcd.service']['state'] != 'running'
      

      【讨论】:

      • 你上一个任务的when 子句有什么意义? service(几乎每个 ansible 模块)是幂等的。如果服务已经启动,它不会做任何事情,只是报告 OK。
      • @Zeitounator 是的,你是对的。感谢您的回复。仍然“何时”用作任务中的信息。
      • IMO 一个冗余信息:“如果服务未启动,则启动该服务”,这已经是模块所做的。此外,这会迫使您收集服务事实。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-20
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 2011-05-03
      • 1970-01-01
      相关资源
      最近更新 更多