List ALL Ansible variables for a host or group with an ad hoc command?

ansible -m debug -a "var=hostvars[inventory_hostname]" seems to work. Valid variable sources (host_vars, group_vars, _meta in a dynamic inventory, etc.) are all taken into account.

With dynamic inventory script hosts.sh:

#!/bin/sh
if test "$1" = "--host"; then
        echo {}
else
        cat <<EOF
{
  "ungrouped": [ "x.example.com", "y.example.com" ],
  "group1": [ "a.example.com" ],
  "group2": [ "b.example.com" ],
  "groups": {
    "children": [ "group1", "group2" ],
    "vars": { "ansible_ssh_user": "user" }
  },
  "_meta": {
    "hostvars": {
      "a.example.com": { "ansible_ssh_host": "10.0.0.1" },
      "b.example.com": { "ansible_ssh_host": "10.0.0.2" }
    }
  }
}
EOF
fi

You can get:

$ chmod +x hosts.sh
$ ansible -i hosts.sh a.example.com -m debug -a "var=hostvars[inventory_hostname]"
a.example.com | success >> {
    "var": {
        "hostvars": {
            "ansible_ssh_host": "10.0.0.1", 
            "ansible_ssh_user": "user", 
            "group_names": [
                "group1", 
                "groups"
            ], 
            "groups": {
                "all": [
                    "x.example.com", 
                    "y.example.com", 
                    "a.example.com", 
                    "b.example.com"
                ], 
                "group1": [
                    "a.example.com"
                ], 
                "group2": [
                    "b.example.com"
                ], 
                "groups": [
                    "a.example.com", 
                    "b.example.com"
                ], 
                "ungrouped": [
                    "x.example.com", 
                    "y.example.com"
                ]
            }, 
            "inventory_hostname": "a.example.com", 
            "inventory_hostname_short": "a"
        }
    }
}

FYI: This github project shows you how to list 90% of variables across all hosts. I find it more globally useful than single host commands. The README includes instructions for building a simple inventory report. It's even more valuable to run this at the end of a playbook to see all the Facts. To also debug Task behaviour use register:


Adding a small tip to the really good answer above, if you want to programmatically poke around you can

Use the existing answer for hostvars:

ansible -m debug myhost -a "var=hostvars[inventory_hostname].ansible_version"

But ansible_facts is empty because debug doesn't run the setup module. So you need to try something extra like jq after trimming the output to make it valid json.

ansible -m setup myhost | sed 's#.*SUCCESS =>##' | jq .ansible_facts.ansible_all_ipv4_addresses

I thought people might find this useful when investigating the giant wall of text that comes back in ansible facts when you just want one thing like jq .ansible_facts.ansible_devices.vda.size

Tags:

Ansible