preload
Aug 31

I needed script that generates dynamic inventory for ansible with hostnames provided by nova. I found this nice little script that generates valid inventory format though there was few missing features that i had to add for the script:

1) There was only one hardcoded network where one could retrieve address.
2) Only ip-addresses were generated for hostnames.

We use rfc6598 networks for management and instances might have two floating addresses from multiple network options due the multiple availability zones. Also I would need hostnames for inventory because some of the playbooks I use depends on variables like ansible_fqdn. Script reads ansible_host_groups and ansible_host_vars metadata from instances described ie. in heat template:

node1:
  type: OS::Nova::Server
    properties:
      name: node1.example.com
      metadata:
        ansible_host_groups: galera_cluster 
        ansible_host_vars: enviroment->Prod

And generates valid json format for Ansible dynamic inventory:

    "galera_cluster": {
        "hosts": [
            "100.80.129.107",
            "100.81.129.43",
            "100.80.129.109"
        ]
    },
    "_meta": {
        "hostvars": {
            "100.81.129.43": {
                "enviroment": [
                    "Prod"
                ]
            },

But I need to have nova provided hostname because of the nature of the current setup. I modified the script to take multiple networks as a list and get the instance name from nova. After this, inventory is generated with ansible_ssh_host option:

    "galera_cluster": {
        "hosts": [
            "node1.example.com",
            "node2.example.com",
            "node3.example.com"
        ]
    },
    "_meta": {
        "hostvars": {
            "node1.example.com": {
                "ansible_ssh_host": "100.80.129.107",
                "enviroment": [
                    "Prod"
                ]
            },

You can find the modified script here and original script and copyright from here