skip to Main Content

I am trying to get the status of a process from each host of a specific group and print the hostname and process status in table format.

[nginx]
172.1.0.1
172.1.0.2


---
hosts: all
tasks:
  - name: Get process status
    shell: ps -ef| grep [n]ginx
    register: nginx_status
    when: '"nginx" in group_names'

Expecting array/table format like as below(I’m using shell command return code here to define UP or DOWN).

Ex:

jinja2 template to capture output:

{% for output in nginx_status.stdout_lines %}
{{ output.hostname }}  {{ if output.rc == 0 UP else DOWN }}
{% endfor %}

The template is not mandatory, Final output is all that I am expecting.

Final output:
HOST      NGINX
172.1.0.1 UP
172.1.0.2 DOWN

In the end, consolidated output from each group should be like.

HOST      NGINX Some-x Some-Y
172.1.0.1 UP     DOWN  UP
172.1.0.2 DOWN   UP    NA(Not Applicable)

2

Answers


  1. If the goal is to get the output printed to the console, then try filtering the output of running a playbook. There are ways to do this purely in ansible, but it gets more involved with using map.

    test.yml:

    ---
    - hosts: nginx
      tasks:
        - name: Get process status
          command: pgrep nginx
          register: proc_status
          changed_when: false
          failed_when: false
    
        - debug:
            msg: "###HOST           NGINX###"
          run_once: true
    
        - debug:
            msg: "###{{ ansible_host }} {{ (proc_status.rc == 0) | ternary('UP', 'DOWN') }}###"
    

    Running: ansible-playbook test.yml | grep "###" | cut -d'#' -f4
    should result in something like:

    HOST           NGINX
    192.168.15.101 UP
    192.168.15.102 DOWN
    

    Your use case may vary with the ### tokens and table column layout (using Linux column command?), but this should provide the basics for solving the problem.

    Note that your original ps -ef | grep ... does not filter itself from the results so will always give a match. You’d need to adjust with something like ps -ef | grep -v grep | grep [n]ginx if you take that route over pgrep.

    Login or Signup to reply.
  2. I’m answering because I don’t have enough rep to comment.

    "If I use delegation with localhost to append in the same file then {{ ansible_host }} will become localhost instead of each host IP. – SNR"

    "{{ inventory_hostname }}" will still be what it says on the tin, even on "delegate_to: localhost" tasks.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search