How to get service status by Ansible?

You can also use the service_facts module.

Example usage:

- name: collect facts about system services
  service_facts:
  register: services_state

- name: Debug
  debug:
    var: services_state

Example output:

...

TASK [Debug] ***************************************************************************************************************************************************************************************************************
ok: [local] => {
    "services_state": {
        "ansible_facts": {
            "services": {
                "cloud-init-local.service": {
                    "name": "cloud-init-local.service",
                    "source": "systemd",
                    "state": "stopped"
                },
                "firewalld.service": {
                    "name": "firewalld.service",
                    "source": "systemd",
                    "state": "stopped"
                },
                ...
            }
        }
    }
}

Just run the task service: name=httpd state=started with the option --check. This tells you, if the service needs to be started, which means that it is down. If the task shows no change, it is up already.

Example service is down, changed is true, because it needs to be started:

$ ansible -m service -a 'name=rpc/bind state=started' --check host
host | SUCCESS => {
    "changed": true, 
    "msg": "service state changed"
}

Example service is up, change is false, because nothings need to be done:

$ ansible -m service -a 'name=system-log state=started' --check host
host | SUCCESS => {
    "changed": false, 
    "name": "system-log", 
    "state": "started"
}

Use command module with service redis-server status and parse stdout.
Or use patched service module.

Tags:

Ansible