Ansible RESTful Dynamic Inventory with Node.js

Most examples of Ansible Dynamic Inventory are coded in Python or Bash, but if you want to access a RESTful API to get your inventory, e.g. from OpenStack Nova Compute API, then the language of the web – aka Javascript – could be a better approach.

So, lets first have a look at a simple example in Javascript of how the inventory data is constructed:

If we run this script we get the following results:

Running this from Ansible gives us:

So, lets take the next step and write an inventory script to pull fixed or floating IP addresses from the OpenStack Nova Compute RESTful API.  Here’s my script to demo this:

This script first authenticates the user for the tenant, then calls the Nova RESTful API with the authentication token, getting a list of servers and their details.  The inventory is then generated from either the fixed or floating IP addresses.

Run this script to see the JSON it generates:

Which, from my OpenStack, generates:

We can now run this from Ansible using:

Success!

So, in summary, Javascript and Node.js (or io.js) are suitable candidates for Ansible Dynamic Inventory scripting, especially when you want to get data from a RESTful API.

Leave a Reply

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