user1016765
user1016765

Reputation: 3063

ansible-inventory --list host groups command line

I would like to obtain the list of host group names (only) from ansible-inventory, however I'm having to use grep to trim down the list based on known group name patterns - e.g.

ansible-inventory -i inventory/production --list --yaml | grep webserver_.*:$

ansible-playbook my-playbook.yml -i inventory/production --list-hosts

Is there a clean way to extract just the group names from inventory?

Example hosts.yml:

# NGINX
webserver_1:
  hosts:
    ws1.public.example.com

webserver_2:
  hosts:
    ws2.public.example.com

webserver_2:
  hosts:
    ws2.public.example.com

# EC2 back-ends
backend_ec2_1:
  hosts:
    be1.internal.example.com

backend_ec2_2:
  hosts:
    be2.internal.example.com

backend_ec2_3:
  hosts:
    be3.internal.example.com

[Ansible v2.9.7]

Upvotes: 2

Views: 5217

Answers (2)

Tarun Hasija
Tarun Hasija

Reputation: 34

This command lists the groups defined in the inventory

ansible localhost -m debug -a 'var=groups.keys()' -i inventory/production/

Upvotes: 1

larsks
larsks

Reputation: 312868

You could use the jq command to parse the json output from ansible-inventory --list, like this:

$ ansible-inventory -i hosts --list | jq .all.children
[
  "backend_ec2_1",
  "backend_ec2_2",
  "backend_ec2_3",
  "ungrouped",
  "webserver_1",
  "webserver_2"
]

Or if you want just bare names:

$ ansible-inventory -i hosts --list | jq -r '.all.children[]'
backend_ec2_1
backend_ec2_2
backend_ec2_3
ungrouped
webserver_1
webserver_2

Upvotes: 5

Related Questions