Skip to content

Example 9

hosts.json

{
    "centos": {
        "hosts": {
            "provisioner": {
                "ansible_connection": "local"
            },
            "centos2": {
                "ansible_host": "192.168.77.22",
                "ansible_port": 2345
            }
        },
        "vars": {
            "ansible_become": true
        }
    },
    "ubuntu": {
        "hosts": {
            "ubuntu1": {
                "ansible_host": "192.168.77.23"
            }
        }
    }
}

Tip

The JSON representation of an inventory can become useful when obtained from an external REST API.

Try to execute the whoami command on all hosts.

ansible all -m command -a "whoami"
Bonus round

Try to reproduce the YAML inventory from the previous example using the JSON syntax. Since all keys must have corresponding values in JSON, use null for keys that were empty.

For bigger inventories you could automate this process eg. with a simple Python script.

import yaml
import json

with open('hosts.yml', 'r') as inv:
    data = yaml.full_load(inv)
    with open('hosts.json', 'w') as out:
        json.dump(data, out, indent=4)