risotto/ansible/inventory.py

137 lines
4.8 KiB
Python
Raw Normal View History

2022-10-01 22:33:11 +02:00
#!/usr/bin/env python
'''
Example custom dynamic inventory script for Ansible, in Python.
'''
from argparse import ArgumentParser
2022-12-21 16:35:58 +01:00
from json import load as json_load, dumps, JSONEncoder
2022-10-01 22:33:11 +02:00
from os import remove
from os.path import isfile
2022-12-21 16:35:58 +01:00
from traceback import print_exc
2023-06-22 16:19:44 +02:00
from sys import stderr, argv
2022-10-01 22:33:11 +02:00
2022-12-21 16:35:58 +01:00
from risotto.machine import load, TIRAMISU_CACHE, VALUES_CACHE, INFORMATIONS_CACHE, ROUGAIL_NAMESPACE, ROUGAIL_NAMESPACE_DESCRIPTION
from tiramisu import Config
2022-10-01 22:33:11 +02:00
from tiramisu.error import PropertiesOptionError
from rougail.utils import normalize_family
2022-12-21 16:35:58 +01:00
from rougail import RougailSystemdTemplate, RougailConfig
2022-10-01 22:33:11 +02:00
from rougail.template.base import RougailLeader, RougailExtra
2022-12-21 16:35:58 +01:00
DEBUG = False
2022-10-01 22:33:11 +02:00
class RougailEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, RougailLeader):
return obj._follower
if isinstance(obj, RougailExtra):
return obj._suboption
if isinstance(obj, PropertiesOptionError):
return 'PropertiesOptionError'
return JSONEncoder.default(self, obj)
class RisottoInventory(object):
def __init__(self):
parser = ArgumentParser()
parser.add_argument('--list', action='store_true')
parser.add_argument('--host', action='store')
2022-12-21 16:35:58 +01:00
parser.add_argument('--nocache', action='store_true')
parser.add_argument('--debug', action='store_true')
2023-06-22 16:19:44 +02:00
parser.add_argument('--pretty_print', action='store_true')
parser.add_argument('--quite', action='store_true')
2022-10-01 22:33:11 +02:00
self.args = parser.parse_args()
2022-12-21 16:35:58 +01:00
if self.args.debug:
global DEBUG
DEBUG = True
2022-10-01 22:33:11 +02:00
2023-06-22 16:19:44 +02:00
def run(self):
2022-12-21 16:35:58 +01:00
if self.args.list and self.args.host:
raise Exception('cannot have --list and --host together')
if self.args.list or self.args.nocache:
2022-10-01 22:33:11 +02:00
if isfile(TIRAMISU_CACHE):
remove(TIRAMISU_CACHE)
if isfile(VALUES_CACHE):
remove(VALUES_CACHE)
2022-12-21 16:35:58 +01:00
if isfile(INFORMATIONS_CACHE):
remove(INFORMATIONS_CACHE)
2023-06-22 16:19:44 +02:00
config = load(TIRAMISU_CACHE,
VALUES_CACHE,
INFORMATIONS_CACHE,
)
2022-12-21 16:35:58 +01:00
if self.args.list:
2023-06-22 16:19:44 +02:00
return self.do_inventory(config)
2022-10-01 22:33:11 +02:00
elif self.args.host:
2023-06-22 16:19:44 +02:00
return self.get_vars(config, self.args.host)
2022-10-01 22:33:11 +02:00
raise Exception('pfff')
2023-06-22 16:19:44 +02:00
def do_inventory(self,
config: Config,
) -> dict:
servers = [subconfig.doc() for subconfig in config.option.list('optiondescription') if subconfig.information.get('module') == 'host']
2022-10-01 22:33:11 +02:00
return dumps({
'group': {
'hosts': servers,
'vars': {
# FIXME
'ansible_ssh_host': '192.168.0.29',
2022-10-01 22:33:11 +02:00
'ansible_ssh_user': 'root',
'ansible_python_interpreter': '/usr/bin/python3'
}
}
})
2023-06-22 16:19:44 +02:00
def get_vars(self,
config: Config,
host_name: str,
) -> dict:
2022-10-01 22:33:11 +02:00
ret = {}
2022-12-21 16:35:58 +01:00
rougailconfig = RougailConfig.copy()
rougailconfig['variable_namespace'] = ROUGAIL_NAMESPACE
rougailconfig['variable_namespace_description'] = ROUGAIL_NAMESPACE_DESCRIPTION
2023-06-22 16:19:44 +02:00
for subconfig in config.option.list('optiondescription'):
server_name = subconfig.description()
module_name = subconfig.option(subconfig.information.get('provider:global:module_name')).value.get()
2022-12-21 16:35:58 +01:00
if module_name == 'host' and server_name != host_name:
2022-10-01 22:33:11 +02:00
continue
engine = RougailSystemdTemplate(subconfig, rougailconfig)
2023-06-22 16:19:44 +02:00
engine.load_variables(with_flatten=False)
2022-12-21 16:35:58 +01:00
if module_name != 'host' and engine.rougail_variables_dict['general']['host'] != host_name:
2022-10-01 22:33:11 +02:00
continue
ret[server_name] = engine.rougail_variables_dict
2023-06-22 16:19:44 +02:00
ret['modules'] = config.information.get('modules')
ret['delete_old_image'] = False
2022-10-01 22:33:11 +02:00
ret['configure_host'] = True
ret['only_machine'] = None
2023-01-23 20:23:32 +01:00
ret['copy_templates'] = False
ret['copy_tests'] = False
2023-06-22 16:19:44 +02:00
ret['host_install_dir'] = ret[host_name]['general']['host_install_dir']
2022-10-01 22:33:11 +02:00
return dumps(ret, cls=RougailEncoder)
# Get the inventory.
2023-06-22 16:19:44 +02:00
def main():
2022-12-21 16:35:58 +01:00
try:
inv = RisottoInventory()
2023-06-22 16:19:44 +02:00
values = inv.run()
if inv.args.pretty_print:
from pprint import pprint
from json import loads
pprint(loads(values))
elif not inv.args.quite:
2023-06-22 16:19:44 +02:00
print(values)
2022-12-21 16:35:58 +01:00
except Exception as err:
if DEBUG:
print_exc()
2023-06-22 16:19:44 +02:00
print('---', file=stderr)
extra=''
else:
extra=f'\nmore informations with commandline "{" ".join(argv)} --debug"'
print(f'{err}{extra}', file=stderr)
exit(1)
2022-10-01 22:33:11 +02:00
2023-06-22 16:19:44 +02:00
main()