Ansible Hostgroups from FreeIPA

Ansible provides management for a large array of servers using ssh as the access mechanism. This is a good match for  FreeIPA.  However, by default Ansible uses a flat file to store groups of hosts.  How can we get that info from FreeIPA?


If you want to run the `uptime` command on all web servers, you would define a fragment of /etc/ansible/hosts  like this:


And then run

ansible webservers -a uptime

In order to get ansible to use a different scheme, use a dynamic inventory.  I wrote a proof of concept one  that uses the hostgroup definitions from my IPA server to populate a json file.  The format of the file is specified in this tutorial:

My Sample ignores the command line parameters, and just returns the whole set of hostgroups.

#Apache License...


import json
from ipalib import api
inventory = {}
result =api.Command.hostgroup_find()['result']
for hostgroup in result:
    inventory[hostgroup['cn'][0]] = { 'hosts': [host for host in hostgroup['member_host']]}
    for host in hostgroup['member_host']:
        hostvars[host] = {}
inventory['_meta'] = {'hostvars': hostvars}
inv_string = json.dumps( inventory)
print inv_string

I copied it to /etc/ansible/ and ran:


$ ansible -i /etc/ansible/ packstacked -a uptime | success | rc=0 >>
20:42:33 up 141 days, 20:43, 2 users, load average: 0.22, 0.15, 0.14 | success | rc=0 >>
20:42:34 up 52 days, 3:17, 1 user, load average: 0.01, 0.03, 0.05 | success | rc=0 >>
20:42:35 up 51 days, 6:07, 2 users, load average: 0.00, 0.03, 0.05

As I said, this was a proof of concept. It does not do everything that you might want to have an inventory do. I plan on fleshing it out and submitting to the Ansible plugin repo. Meanwhile, you can look at the other examples.

If you are curious, here is the output from when I run my plugin:

$ python | python -mjson.tool
    "_meta": {
        "hostvars": {
            "": {},
            "": {},
            "": {},
            "": {},
            "": {}
    "keystone-ha-cluster": {
        "hosts": [
    "packstacked": {
        "hosts": [

One thought on “Ansible Hostgroups from FreeIPA

  1. You may want to take a look at this ->

    ipaqe-dyndir is a simple script that reads the config file used by freeipa integration test framework and prepares a dynamic inventory for ansible.

    The script implements command –list returning an json formatted information about the whole inventory. The information includes inventory metadata, thus making ansible call the script only once.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.