Ansible tips’n’tricks: gather facts in an ad-hoc fashion

There are times when I really need to get some ansible_facts from a host to work out details about, say the network card, storage, or Linux Distribution to continue coding. And I don’t want to/have the patience to run add a debug step in my Ansible playbook either :) Thankfully Ansible has just the right tool for the case, called ad-hoc command execution.

Since I can never remember how to gather ansible_facts I decided to write it down, hopefully this saves me (and you!) 5 minutes next time.

Setup

I am using ansible-5.9.0-1.fc36.noarch as provided by Fedora 36 (which includes ansible-core-2.12.10-1.fc36.noarch) on Linux x86-64. Vagrant 2.3.4 has been provided by the HashiCorp repository.

Gathering facts: using Vagrant’s dynamic Ansible inventory

If you are using the Ansible provisioner with your Vagrant box, Vagrant will create a suitable inventory for you. Assuming there is only a single VM defined in your Vagrantfile you can use the following command to gather facts:

ansible -i .vagrant/provisioners/ansible/inventory/ default -m setup
default | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "10.0.2.15"
        ],
        "ansible_all_ipv6_addresses": [
            "fe80::a00:27ff:fec0:f04e"
        ],
        "ansible_apparmor": {
            "status": "enabled"

If you have multiple VMs defined in your Vagrantfile you need to either specify all or the VM name as defined in the inventory.

Gathering facts without an inventory

If you have a VM you can SSH to there is an alternative option available to you: simply specify the IP address or DNS name of the VM as the Ansible inventory followed by a ",", like so:

ansible -i nginx, nginx -u ansible --private-key ~/.ssh/ansible -m ansible.builtin.setup | head
nginx | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "10.0.2.15",
            "192.168.56.43"
        ],
        "ansible_all_ipv6_addresses": [
            "fe80::a00:27ff:fe8d:7f5f",
            "fe80::a00:27ff:fe37:33f6"
        ],

That’s all there is to gathering ansible_facts in an ad-hoc fashion. Happy automating!

Advertisement