Tutchapon Sirisaeng
Tutchapon Sirisaeng

Reputation: 45

How to check any services exists by Ansible?

I want to check the service exists in the terminal host.

So, I just did the playbook as below.

---

- hosts: '{{ host }}'
  become: yes
  vars:
    servicename:
  tasks:

  - name: Check if Service Exists
    stat: 'path=/etc/init.d/{{ servicename }}'
    register: servicestatus
    with_items: '{{ servicename }}'

  - name: Show service service status
    debug:
      msg: '{{ servicename }} is exists.'
    with_items: '{{ servicename }}'
    when: servicestatus.stat.exists

Then, I try to execute this playbook to my host that was running Nginx already as below.

ansible-playbook cheknginxservice.yml -i /etc/ansible/hosts -e 'host=hostname' -e 'servicename=nginx'

And I got the error like this.

 FAILED! => {"failed": true, "msg": "The conditional check 'servicestatus.stat.exists' failed. The error was: error while evaluating conditional (servicestatus.stat.exists): 'dict object' has no attribute 'stat'\n\nThe error appears to have been in '/home/centos/cheknginxservice.yml': line 13, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n    with_items: '{{ servicename }}'\n  - name: Show service servicestatus\n    ^ here\n"}
        to retry, use: --limit @/home/centos/cheknginxservice.retry

So, I think the problem is about stat module when using the condition involved.

Upvotes: 1

Views: 9892

Answers (1)

helloV
helloV

Reputation: 52393

Why are you using with_items? You plan to pass multiple services? It matters because the results will be a list if you use with_items. Just remove with_items and it will work. If you want to pass multiple services, then you have to loop through with_items and use item instead of servicename.

  - name: Check if Service Exists
    stat: 'path=/etc/init.d/{{ servicename }}'
    register: servicestatus

  - name: Show service service status
    debug:
      msg: '{{ servicename }} is exists.'
    when: servicestatus.stat.exists

There is no native way in Ansible to check the status of a service. You can use the shell module. Notice I used sudo. Your case may be different.

  - name: check for service status
    shell: sudo service {{ servicename }} status
    ignore_errors: true
    register: servicestatus

  - name: Show service service status
    debug:
      msg: '{{ servicename }} exists.'
    when: servicestatus.rc | int == 0

Upvotes: 3

Related Questions