Convert Ansible YAML inventory to JSON using Python
python3 -c 'import sys, yaml, json; json.dump(yaml.load(sys.stdin, Loader=yaml.FullLoader), sys.stdout, indent=4)' < hosts.yaml > hosts.json
Check if new JSON inventory is correct:
ansible all -i hosts.json --list-hosts
So the inventory in YAML:
--- # start
control:
hosts:
ubuntu-c:
ansible_connection: local
centos:
hosts:
centos1:
ansible_port: 2222
centos2:
centos3:
vars:
ansible_user: root
ubuntu:
hosts:
ubuntu1:
ubuntu2:
ubuntu3:
vars:
ansible_become: true
ansible_become_pass: password
linux:
children:
centos:
ubuntu:
... # end
Becomes the following inventory in JSON:
{
"control": {
"hosts": {
"ubuntu-c": {
"ansible_connection": "local"
}
}
},
"centos": {
"hosts": {
"centos1": {
"ansible_port": 2222
},
"centos2": null,
"centos3": null
},
"vars": {
"ansible_user": "root"
}
},
"ubuntu": {
"hosts": {
"ubuntu1": null,
"ubuntu2": null,
"ubuntu3": null
},
"vars": {
"ansible_become": true,
"ansible_become_pass": "password"
}
},
"linux": {
"children": {
"centos": null,
"ubuntu": null
}
}
}