How to list groups that host is member of?

2019-02-18 12:15发布

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.

标签: ansible
3条回答
等我变得足够好
2楼-- · 2019-02-18 12:31

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楼-- · 2019-02-18 12:36

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

查看更多
趁早两清
4楼-- · 2019-02-18 12:48

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 
查看更多
登录 后发表回答