How to list groups that host is member of?

2019-02-18 12:07发布

问题:

I have a very complex Ansible setup with thousands of servers and hundreds of groups various servers are member of (dynamic inventory file).

Is there any way to easily display all groups that a specific host is member of?

I know how to list all groups and their members:

ansible localhost -m debug -a 'var=groups'

But I want to do this not for ALL hosts, but only for a single one.

回答1:

Create a playbook called 'showgroups' (executable file) containing:

#!/usr/bin/env ansible-playbook

- hosts: all
  gather_facts: no
  tasks:
  - name: show the groups the host(s) are in
    debug:
      msg: "{{group_names}}"

You can run it like this to show the groups of one particular host (-l) in your inventory (-i):

 ./showgroups -i develop -l jessie.fritz.box 


回答2:

There is group_names magic variable:

Additionally, group_names is a list (array) of all the groups the current host is in. This can be used in templates using Jinja2 syntax to make template source files that vary based on the group membership (or role) of the host



回答3:

cat /etc/ansible/hosts | grep -e [[] && ansible all --list-hosts



标签: ansible