首页 > 解决方案 > 如何将此临时命令编写为剧本

问题描述

我编写了一个临时命令来检查 NGINX 状态,发现它的状态是活动的(因为ActiveState值为active)。
现在,我想知道我们如何从 Ansible 剧本中实现同样的目标。
我只想从 Ansible 剧本中知道我的 NGINX 是否处于活动状态,apache 是否处于活动状态。

临时命令:

ansible -b webserver -m service -a "name=nginx"

ip-172-31-34-68.ap-south-1.compute.internal | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "name": "nginx",
    "status": {
        "ActiveEnterTimestamp": "Thu 2021-03-18 18:00:55 UTC",
        "ActiveEnterTimestampMonotonic": "14598079",
        "ActiveExitTimestampMonotonic": "0",
        "ActiveState": "active",
        "After": "tmp.mount sysinit.target basic.target -.mount systemd-tmpfiles-setup.service network.target remote-fs.target systemd-journald.socket nss-lookup.target system.slice"
    }  
}

标签: ansible

解决方案


这个 ad-hoc 命令的等价物是service_facts模块。

所以剧本是:

- hosts: webserver
  gather_facts: no

  tasks:
    - service_facts:
  
    - debug:
        var: ansible_facts.services[item].state
      loop: "{{ services }}"
      vars:
        services:
          - nginx
          - apache

如文档中所述,状态略有不同,但您肯定会在以下位置找到等价物running

服务的状态。, running,stoppedunknown.

来源:https ://docs.ansible.com/ansible/2.9/modules/service_facts_module.html#return-ansible_facts/services/state


推荐阅读