I am trying to run if else statement inside shell module in ansible playbook but looks like my else statement is not executing in any case.
- name: verify application/database processes are not running
shell: if ps -eaf | egrep 'apache|http'|grep -v grep > /dev/null echo 'process_running';else echo 'process_not_running';fi
ignore_errors: false
register: app_process_check
Please correct me here.
If you only want to ensure that a service is running you don't need to check it yourself, ansible can handle this for you.
Ansible will start it if it is no running, and will do nothing if it already runs.
If you need to check this for another reason you can do the check in ansible instead of the shell:
Afterward you can use this with
running_processes.changed
(or move the check itself to the next task).Fix the if-then-else statement. The keyword then is missing. I've added ps parameter -x to include "processes which do not have a controlling terminal" (which normally web servers do not). The script below works as expected
Then use the script in Ansible. You might want to use Literal block scalar to improve the code's readability. For example
gives, if Apache is running
otherwise
Instead of using command:/shell: consider the ansible.builtin.service_facts: module. ansible.docs page for service_facts
From that page:
From there you can access various facts about configured services.
ansible_facts.services['httpd']
oransible_facts.services['apache']