""" Silique (https://www.silique.fr) Copyright (C) 2022-2025 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . """ from typing import Optional from json import dumps from tiramisu import groups from rougail.utils import normalize_family from .i18n import _ from .__version__ import __version__ from ..output_json import RougailOutputJson class RougailOutputAnsible(RougailOutputJson): output_name = "ansible" def __init__( self, config: "Config", *, rougailconfig: "RougailConfig" = None, **kwargs, ) -> None: super().__init__(config, rougailconfig=rougailconfig, **kwargs) try: groups.namespace self.support_namespace = True except AttributeError: self.support_namespace = False self.host_namespace = self.rougailconfig["ansible.host_namespace"] self.namespace_is_hostname = self.rougailconfig["ansible.namespace_is_hostname"] def exporter(self) -> None: super().exporter() self.json_to_ansible() # never return code 1, error are in the output data return True def manage_errors(self) -> bool: if not super().manage_errors(): if not self.support_namespace: self.errors.append(_('no namespace configured')) hosts_config = self.config.option('hosts') try: if hosts_config.group_type() != groups.namespace: hosts_config = None except AttributeError: hosts_config = None if not hosts_config: self.errors.append(_('cannot find host namespace "{0}"').format(self.host_namespace)) else: try: hosts_config.option('hostnames').name() except AttributeError: self.errors.append(_('malformated host namespace "{0}", should have the "hostnames" key').format(self.host_namespace)) return super().manage_errors() return True def parse_family( self, conf, child, ): if self.read_write and conf.path() == self.host_namespace: self.config.property.read_only() super().parse_family(conf, child) if self.read_write and conf.path() == self.host_namespace: self.config.property.read_write() def json_to_ansible(self): ret = {"_meta": {"hostvars": {}}, "all": {"children": ["ungrouped"]}} if '_warnings' in self.dico: ret["_meta"]["hostvars"]["localhost"] = {'_warnings': self.dico.pop('_warnings')} ret["ungrouped"] = {"hosts": ["localhost"]} if '_errors' in self.dico: ret["_meta"]["hostvars"].setdefault("localhost", {})['_errors'] = self.dico.pop('_errors') if "ungrouped" not in ret: ret["ungrouped"] = {"hosts": ["localhost"]} if self.host_namespace in self.dico: hosts = self.dico.pop(self.host_namespace) if "hostnames" not in hosts: ret["_meta"]["hostvars"].setdefault("localhost", {}).setdefault('_errors', []).append(_('cannot find "hostnames" in "{0}" namespace').format(self.host_namespace)) if "ungrouped" not in ret: ret["ungrouped"] = {"hosts": ["localhost"]} hostnames = {} else: hostnames = hosts['hostnames'] ret_hosts = {} for name, hosts in hostnames.items(): if 'hosts' in hosts: if 'prefix_name' in hosts: host_name = hosts['prefix_name'] add_index = True elif len(hosts["hosts"]) == 1: host_name = hosts["hosts"][0] add_index = False else: raise Exception("cannot find prefix_name") for idx, host in enumerate(hosts['hosts']): index = str(idx + 1) if idx < 9: index = '0' + index if 'prefix_name' in hosts: host_name = hosts['prefix_name'] + index ret_hosts.setdefault(name, {})[host_name] = host ret.setdefault(name, {}).setdefault('hosts', []).append(host_name) else: ret["all"]["children"].append(name) ret[name] = hosts for hosts in ret_hosts.values(): for host, domain_name in hosts.items(): ret['_meta']['hostvars'][host] = {'ansible_host': domain_name} if self.namespace_is_hostname: host_namespace = normalize_family(host) if host_namespace in self.dico: ret['_meta']['hostvars'][host].update(self.dico[host_namespace]) else: ret['_meta']['hostvars'][host].update(self.dico) self.dico = ret RougailOutput = RougailOutputAnsible __all__ = ("RougailOutputAnsible",)