I want to get service like redis-server
running status by Ansible.
I know how to use Ansible service module to stop or start system service. But how can I get the current service status?
Use command module with service redis-server status and parse stdout.
A value is available; BOF for inserting the line at the beginning of the file. If specified regular expression has no matches, the line will be inserted at the end of the file.
Create a file that lists all nodes where this task is required to be executed. Create an Ansible. cfg file and make sure it is pointing to inventory file which lists IP addresses of nodes. Run the Ansible Adhoc command to fetch uptime.
service_facts module – Return service state information as fact data. Note. This module is part of ansible-core and included in all Ansible installations. In most cases, you can use the short module name service_facts even without specifying the collections: keyword.
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, changed
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"
}
A very short program for checking services using ansible -
- name: checking service status
hosts: www.linuxfoundation.org
tasks:
- name: checking service status
command: systemctl status "{{ item }}"
with_items:
- firewalld
- httpd
- vsftpd
- sshd
- postfix
register: result
ignore_errors: yes
- name: showing report
debug:
var: result
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With