Ansible Custom Facts

I like Ansible. It’s not perfect but nothing is. Recently I was playing around with the tinc vpn system and wanted a way to set a custom fact per virtual machine based on the vms public ip address. I figured the best way to do that would be to setup a custom fact. It turns out there isn’t that much documentation on just how to do that, or I simply can’t find it. So I’m going to describe what I did in order to setup and use a custom fact.

A bash script

I just wanted a simple script to parse the ip address of the server and return a private ip based on the last octet of the address.

Loading the custom fact

So, the first time that file is loaded onto the server Ansible setup won’t have it yet (unless it was loaded up in a previous role) so if you do load the facts file in the same role you’ll have to use setup in the task list to load the custom fact.

Here’s a snippet of my playbook. It’s creating the facts.d directory, copying over the script, and finally re-running setup with the ansible_local filter.

I should be registering a variable and only reload the ansible_local if the facts.d scripts have changed on this particular run.