For my lab I would like to check services on multiple servers for specific users. Ideally to have following data
- user
- status
- service name
Unfortunately, there is no native way to accomplish this with Ansible. With bash it's possible: ps -u user1,user2,user3 -xco user,stat,command
which works as intended.
But PS is not that simple. It will not check services for users if one user does not exists. Could you please direct me in the right way, maybe I'm making things harder here.
CodePudding user response:
I understand your question that you are not for looking for how to get services in specific status, but the state of processes running under specific users.
You could use the following approach to gather all available local users
---
- hosts: localhost
become: yes
gather_facts: false
vars:
SERVICES_IN_INTEREST: # here Ansible Tower only
- "nginx"
- "awx"
tasks:
- name: Gather available local users
getent:
database: passwd
# Debugging output to get familar with the data structure
- name: Show all gathered local user information
debug:
var: getent_passwd
- name: Show gathered local user names only
debug:
msg: "{{ item }}"
loop: "{{ getent_passwd.keys() | list }}"
Since one may not interested in all processes running under root or other users but specific services, a list of services in interest is introduced.
- name: Get list of processes of all available local users
shell:
cmd: "ps -u {{ item }} -o user,stat,command --no-header | sort | uniq"
loop: "{{ getent_passwd.keys() | list }}" # all local users
when: item in SERVICES_IN_INTEREST
register: result
changed_when: false
- name: Show result
debug:
msg: "{{ item.stdout }}"
with_items: "{{ result.results }}"
when: item.item in SERVICES_IN_INTEREST
The behavior could also be change to users in interest if necessary.