Files
skato-ansible/main.py

90 lines
2.8 KiB
Python

import click
from pathlib import Path, PurePath, PurePosixPath, PureWindowsPath, PosixPath, WindowsPath
from whereami import PROJ_ROOT
from custtypes import ExecutedPath, IdlePath
import yaml as yams
from anodes import RemoteNode, ControlNode
# from typing import TypeAlias as Neotype
# from typing import Literal
# import configparser as ini
# from cerberus import Validator as constrain_by
# import skansible_types as skato
# @NOTE https://docs.python.org/3/library/configparser.html#quick-start
class Config:
path: ExecutedPath = PROJ_ROOT / "config.ini"
config = Config()
@click.group()
def skansible():
pass
@click.group()
@click.argument("hostname", nargs=-1, type=str)
@click.option("-g", "--group", type=str, show_default=True)
@click.option("-p", "--password", type=str, prompt=True, prompt_required=False)
@click.option("-a", "--api", type=str)
@click.option("-k", "--key", multiple=True)
@click.option("-t", "--tag", multiple=True, type=str)
@click.option("-n", "--fqdn", type=(str, None))
@click.option("-s", "--service", type=(str, None))
def addhost(hostname, password, api, key, group = "ungrouped", service = None, fqdn = None, tags = None):
hosts_model = dict()
hosts_model[group]["hosts"] = dict()
for name in hostname:
hosts_model[group]["hosts"][name] = None
with open(str(PROJ_ROOT / "hosts.yml")) as hosts_file:
yams.dump(hosts_model, hosts_file)
cnode = ControlNode()
if fqdn is not None:
rnode = RemoteNode(cnode, api, password, fqdn)
else:
if isinstance(hostname, (tuple, list)):
if len(hostname) > 0 and len(hostname) < 2:
rnode = RemoteNode(cnode, api, password, hostname[0])
else:
raise ValueError
elif isinstance(hostname, str):
rnode = RemoteNode(cnode, api, password, hostname)
else:
raise TypeError
if tag is not None:
if isinstance(tag, (tuple, list)) and len(tag) > 0:
rnode.add_tags(*tag)
if key is not None:
if isinstance(key, tuple) and len(key) > 0:
rnode.import_keys(key)
if service is not None:
rnode.service = service
if group == "ungrouped":
if isinstance(hostname, (tuple, list)):
if len(hostname) > 0 and len(hostname) < 2:
filepath = PurePath(str(cnode.invvar_data[1]), hostname[0])
else:
raise ValueError
elif isinstance(hostname, str):
filepath = PurePath(str(cnode.invvar_data[1]), hostname)
else:
raise TypeError
else:
filepath = PurePath(str(cnode.invvar_data[0]), group)
inv_model = rnode.itemize()
with open(str(filepath), "w") as inv_file:
yams.dump(inv_model, inv_file)
print((hosts_model, inv_model))
skansible.add_command(addhost)
if __name__ == "__main__":
skansible()