DEV Community

rndmh3ro
rndmh3ro

Posted on • Originally published at zufallsheld.de on

TIL how to get a plaintext list of Ansible hosts

There was a need to iterate over the hosts in an Ansible inventory-file (don’t ask). After fiddling around with grep and sed, I found an easier method:

ansible-inventory --list all | jq " ._meta.hostvars| keys[]"

Enter fullscreen mode Exit fullscreen mode

ansible-inventory --list all lists all hosts including their variables in a nice big json response.

jq " ._meta.hostvars" then filtersonly for these variables:

{
  "host01": {
    "list_variable": [
      "195.13.41.220",
      "195.13.41.221",
      ]
    }
}

Enter fullscreen mode Exit fullscreen mode

Now I only need the host01-part, the keys of this dictionary. jq’s keys[] function does this.

> ansible-inventory --list all | jq " ._meta.hostvars| keys[]"
"host01"
"host02"
"host03"
"host04"
"host05"
"host06"

Enter fullscreen mode Exit fullscreen mode

Top comments (0)