Using if else statement inside shell module in ansible playbook
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.
- name: ensure apache is started
service:
name: apache2
state: started
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:
- name: check if apache is running
shell: ps -eaf
register: running_processes
changed_when: >
('apache' in running_processes.stdout) or
('httpd' in running_processes.stdout)
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
#!/bin/sh
if ps -axef | egrep 'apache|http' | grep -v grep > /dev/null; then
echo 'process_running'
else
echo 'process_not_running'
fi
Then use the script in Ansible. You might want to use Literal block scalar to improve the code's readability. For example
- name: verify application/database processes are not running
shell: |
if ps -axef | egrep 'apache|http' | grep -v grep > /dev/null; then
echo 'process_running'
else
echo 'process_not_running'
fi
ignore_errors: false
register: app_process_check
- debug:
var: app_process_check.stdout
gives, if Apache is running
app_process_check.stdout: process_running
otherwise
app_process_check.stdout: process_not_running