exemple: inventory refactory
This commit is contained in:
36
example/ansible/inventory/multipass.py
Executable file
36
example/ansible/inventory/multipass.py
Executable file
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import sys
|
||||
import subprocess
|
||||
import json
|
||||
import re
|
||||
|
||||
out = subprocess.run(["multipass", "list", "--format=json"], capture_output=True)
|
||||
if out.returncode != 0:
|
||||
print(f"ERR executing multipass list: {out.returncode}")
|
||||
sys.exit(out.returncode)
|
||||
|
||||
instances = json.loads(out.stdout)
|
||||
ret = {
|
||||
"_meta": {"hostvars": {}},
|
||||
"linux": {"hosts": []}
|
||||
}
|
||||
|
||||
for instance in instances['list']:
|
||||
if instance['state'] != "Running":
|
||||
continue
|
||||
|
||||
release = instance['release'].replace(' ', '').replace('.', '').lower()
|
||||
if release not in ret:
|
||||
ret[release] = {"hosts": []}
|
||||
|
||||
group = re.search('^[a-z]+', instance['name']).group()
|
||||
if group not in ret:
|
||||
ret[group] = {"hosts": []}
|
||||
|
||||
ret['_meta']['hostvars'][instance['name']] = {"ansible_host": instance['ipv4'][0] }
|
||||
ret['linux']['hosts'].append(instance['name'])
|
||||
ret[release]['hosts'].append(instance['name'])
|
||||
ret[group]['hosts'].append(instance['name'])
|
||||
|
||||
print(json.dumps(ret))
|
||||
Reference in New Issue
Block a user