How to write this ad-hoc command as a playbook

Viewed 165

I wrote an ad-hoc command for checking NGINX status and found that its status is active (since the ActiveState value is active).
Now, I would like to know how we can achieve the same from an Ansible playbook.
I just want to know whether my NGINX is active or not, apache is active or not, from an Ansible playbook.

Adhoc cmd:

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"
    }  
}
1 Answers

The equivalent to this ad-hoc command is the service_facts module.

So the playbook would be:

- hosts: webserver
  gather_facts: no

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

As raised in the documentation, the state are a little bit different but you'll surely find an equivalent in running:

State of the service. Either running, stopped, or unknown.

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

Related