How to use json file consisting of host info as input to ansible inventory

ansible-inventory

I am trying to use the following json file as input to ansible host inventory but I get error when I run the playbook.
JSON File:

{
   "instances":{
       "host": 10.66.70.33
   }
}

Playbook:

hosts: "{{ instances.host }}"
remote_user: root #vars:

When I run the play book I get the following errors. I am not sure where I am doing wrong. I am new to Ansible. Please advice I guess i am doing some silly mistake.

[WARNING]: Could not match supplied host pattern, ignoring: all
[WARNING]: provided hosts list is empty, only localhost is available
ERROR! The field 'hosts' has an invalid value, which includes an
undefined variable. The error was: 'instances' is undefined

I am running the playbook as follows:

ansible-playbook -i <path>/test.json <path>test_playbook.yml

Best Answer

Ansible's yaml plugin will actually parse a JSON file, and has done so for years.

It's barely documented but you can see in the parameters section of the yaml plugin docs, .json is listed as a valid extension.

The JSON format has the same semantics as the YAML format. Note: not the same format as the dynamic inventory!

So your JSON should look like,

{
   "instances": {
      "hosts": {
         "10.66.70.33": null
      }
   }
}

Note: it's "hosts" rather than "host" and each address is a dictionary/hash key with the values being host-specific vars.

Taking the first example from Working with Inventory docs,

all:
  hosts:
    mail.example.com:
  children:
    webservers:
      hosts:
        foo.example.com:
        bar.example.com:
    dbservers:
      hosts:
        one.example.com:
        two.example.com:
        three.example.com:

would look like,

{
  "all": {
    "hosts": {
      "mail.example.com": null
    },
    "children": {
      "webservers": {
        "hosts": {
          "foo.example.com": null,
          "bar.example.com": null
        }
      },
      "dbservers": {
        "hosts": {
          "one.example.com": null,
          "two.example.com": null,
          "three.example.com": null
        }
      }
    }
  }
}

Those nulls are odd-looking but in the YAML example you'll see the trailing colon which does indeed mean each of those hosts are effectively dictionary/hash keys.

For the curious, the JSON-then-YAML loading code is in parsing/utils/yaml.py and the actual parsing is in parsing/inventory/yaml.py.