1

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.

0
3

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).

2

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
0

Instead of using command:/shell: consider the ansible.builtin.service_facts: module. ansible.docs page for service_facts

From that page:

- name: Populate service facts
  service_facts:

- debug:
    var: ansible_facts.services

From there you can access various facts about configured services.

ansible_facts.services['httpd'] or ansible_facts.services['apache']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.