user12824423
user12824423

Reputation: 39

Ansible - when condition not working as expected

I stopped splunk on target server and I want Ansible to start it if it is not running based on the output of the first command. I got the status of splunk from the target server with the following command:

service splunk status | grep -i running | grep -v grep
# output:
splunkd is not running.

Snippet of the playbook:

- shell: service splunk status | grep -i running
  register: SERV

# - debug: var=SERV.stdout

- shell: echo OK
  register: ECHO

- debug: var=ECHO.stdout

# - debug: msg="SPLUNK is NOT Running and will be Started"

- service: name=splunk state=started
  when: SERV.stdout == "splunkd is not running."

The "when" condition does not work as expected. If Splunk is not running, the "when" condition works. But if splunk is running, Ansible still starts splunk.

Q: How can I configure the "when" condition so it will start splunk if 'Spunkd is not running.' is in the output of the first command?

Upvotes: 0

Views: 432

Answers (2)

BinaryMonster
BinaryMonster

Reputation: 1218

Maybe you could try Ansible Service module, reference docs

something like this should work, not sure if you are looking for something else.

- name: Start service splunk, if not started
  service:
    name: splunk
    state: started

Hope this is helpful.

Upvotes: 0

Kevin C
Kevin C

Reputation: 5750

Use this:

- service: 
    name: splunk 
    state: started
  when: "'splunkd is not running' in SERV.stdout" 

Upvotes: 0

Related Questions