0

Via Ansible-Playbook I would like to check the existence (running) of a service first and then stop the service such as mongod.

Here is the code for stoping service:

- name: stop 
  service:
    name: mongod
    state: stopped

But if you run the above script for second time, then it gives you an error that the service is not running.

How can I check the status before running this script? How to ensure that the service is running and then stopping it.

I don't want to use neither "shell" or "command" options in the playbook, I want to use ansible modules.

Solutions at : How to get service status by Ansible? were using shell or command

Rodrigo Villalba Zayas
  • 5,326
  • 2
  • 23
  • 36
Papal
  • 155
  • 3
  • 8

2 Answers2

1

Unfortunately I couldn't find the answer so I stay with the old solution:

- name: Check if mongod is active
  command: systemctl status mongod
  register: deb_check
  ignore_errors: yes
  no_log: True
  failed_when: false
# I ignored all errors when the process is dead

- name: Stop mongof if it is active otherwise SKIP
  service:
    name: mongod
    state: stopped
  when: deb_check.stdout.find('dead') == -1

If you found a solution please advise.

Papal
  • 155
  • 3
  • 8
0

The correct answer is to work with handlers, they are especially there to avoid starting or stopping services multiple times as the handler will be only executed at the end of the play.

You can try something like that :

tasks:
    - name: Check if mongod is active
      command: systemctl status sshd
      register: deb_check
      ignore_errors: yes
      no_log: True
      failed_when: false

    - name: Raise a flag whenever the service should be stopped
      notify: stop mongod
      when: '"dead" in deb_check.stdout'
handlers:
    - name: stop mongod
      service:
          name: mongod
          state: stopped
slashcool
  • 168
  • 7