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
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
:Running:
ansible-playbook test.yml | grep "###" | cut -d'#' -f4
should result in something like:
Your use case may vary with the
###
tokens and table column layout (using Linuxcolumn
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 likeps -ef | grep -v grep | grep [n]ginx
if you take that route overpgrep
.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.