55 lines
1.5 KiB
Python
55 lines
1.5 KiB
Python
|
#!/usr/bin/env python3
|
||
|
from json import dumps, loads
|
||
|
from os import environ
|
||
|
|
||
|
|
||
|
def get_tfstate(path = 'terraform.tfstate'):
|
||
|
with open(path, 'r') as f:
|
||
|
return loads(f.read())
|
||
|
|
||
|
|
||
|
def gen_kube_inv(tf = get_tfstate()):
|
||
|
kube_ids = []
|
||
|
hosts = []
|
||
|
inv = {}
|
||
|
|
||
|
for res in tf.get('resources', []):
|
||
|
if res.get('type') != 'proxmox_virtual_environment_container':
|
||
|
continue
|
||
|
|
||
|
name = res.get('name', 'unknown').replace('-', '_')
|
||
|
if inv.get('name') == None:
|
||
|
inv[name] = {'hosts':[]}
|
||
|
|
||
|
for ins in res.get('instances', []):
|
||
|
attrs = ins.get('attributes', {})
|
||
|
host = (attrs
|
||
|
.get('initialization', [{}])[0]
|
||
|
.get('ip_config', [{}])[0]
|
||
|
.get('ipv4', [{}])[0]
|
||
|
.get('address', 'unknown')
|
||
|
.split('/')[0]
|
||
|
)
|
||
|
inv[name]['hosts'].append(host)
|
||
|
kube_ids.append(attrs['id'])
|
||
|
hosts.append(host)
|
||
|
|
||
|
inv['kubes'] = {'hosts': hosts}
|
||
|
return inv, kube_ids
|
||
|
|
||
|
|
||
|
if __name__ == '__main__':
|
||
|
try:
|
||
|
inv, kube_ids = gen_kube_inv()
|
||
|
except KeyError as exc:
|
||
|
print('Malformed terraform.tfstate detected, try running terraform import')
|
||
|
raise exc
|
||
|
|
||
|
proxmox_endpoint = environ.get('TF_VAR_endpoint')
|
||
|
if proxmox_endpoint:
|
||
|
proxmox = proxmox_endpoint.split('/')[2].split(':')[0]
|
||
|
inv['_meta'] = {'hostvars': {proxmox: {'kube_ids': kube_ids}}}
|
||
|
inv['proxmox'] = {'hosts': [proxmox]}
|
||
|
|
||
|
print(dumps(inv, indent=2))
|