leylines/leylines-ansible/leylines_inv.py

64 lines
1.9 KiB
Python
Raw Normal View History

2021-06-15 08:37:57 +00:00
#!/usr/bin/env python3
import argparse
import json
import os
import sys
from leylines import SERVER_NODE_ID
from leylines.database import Database
2021-06-15 08:37:57 +00:00
XDG_CACHE_HOME = os.path.expanduser(os.environ.get("XDG_CACHE_HOME", "~/.cache"))
CACHE_DIR = os.path.join(XDG_CACHE_HOME, "leylines")
if not os.path.isdir(CACHE_DIR):
os.mkdir(CACHE_DIR, 0o700)
db = Database()
2021-06-15 08:37:57 +00:00
def get_ansible_config():
server_node = db.get_server_node()
nodes = [node for node in db.get_nodes() if node.ssh_key is not None]
for node in nodes:
nid = node.id
ssh_key = node.ssh_key
ssh_key_path = os.path.join(CACHE_DIR, f"{nid}.key")
if not os.path.isfile(ssh_key_path):
with open(ssh_key_path, "w") as f:
f.write(ssh_key)
return {
"leylines": {
"hosts": [node.name for node in nodes],
"vars": {
"ansible_ssh_user": "haskal",
"ansible_python_interpreter": "auto"
}
},
"_meta": {
"hostvars": {
node.name: {
"ansible_host": str(node.ip),
"ansible_ssh_private_key_file": os.path.join(CACHE_DIR, f"{node.id}.key"),
"leylines_resources":
" ".join([f"{res}=1" for res in db.get_node_resources(node.id)]),
"leylines_ip": str(node.ip),
"leylines_server_addr": str(server_node.ip),
"leylines_is_server": "yes" if node.id == server_node.id else "no"
} for node in nodes
}
}
}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="leylines ansible inventory plugin")
parser.add_argument("--list", action="store_true", help="List inventory")
args = parser.parse_args()
if args.list:
json.dump(get_ansible_config(), sys.stdout)
else:
raise Exception("no action specified")