skip to Main Content

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.

  • Clean output but messy command line and need to know group name pattern ahead of time:

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

  • Clean command line and don’t need to know group name pattern, but messy output:

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]

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. This command lists the groups defined in the inventory

    ansible localhost -m debug -a 'var=groups.keys()' -i inventory/production/
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search