How to get system status using Ansible

Viewed 1494

I have a simple ansible playbook to get the status of the etcd service as below.

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

But at first this service might not be running

So I want to start the service if it is not running. So it must be a conditional check, here's what I did:


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

But this gives the error as below:

TASK [showing report] ********************************************************** ok: [35.236.98.212] => { "result.ansible_facts.services["etcd.service"].state": "VARIABLE IS NOT DEFINED!"

How can I check the Status of the etcd service, and if it it not running I want to start the service and if it is already running, leave it as it is.

Can someone please help me?

2 Answers

You're mixing up a lot of things IMO. shell effectively returns some info if you register the result. But the result will not contain any ansible_facts.services entry.

This name looks like what is returned by the service_facts module. You need to run it to populate the corresponding info in your host facts:

- name: Get service facts for all hosts in play
  service_facts:

- name: dummy task to show it worked
  debug:
    var: ansible_facts.services

Now you should also understand that ansible is about describing the expected state of the remote target you are connecting to. When it comes to services, if you want to make sure a specific one is started and will always be started on boot (and taking for granted it is managed by systemd), all you have to do is:

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

This task will:

  • enable etcd on boot if it was not already enabled
  • start etcd if it was not already started
  • do nothing and report simply "OK" if it was already enabled and started.

More generally, you should avoid using shell/command when there is already an ansible module doing the job.

You can use service_facts module here

For example

- 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'
Related