rougail-output-ansible/src/rougail/output_ansible/__init__.py
2024-12-09 10:51:46 +01:00

122 lines
4.7 KiB
Python

"""
Silique (https://www.silique.fr)
Copyright (C) 2022-2024
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 <http://www.gnu.org/licenses/>.
"""
from typing import Optional
from json import dumps
from tiramisu import groups
from .i18n import _
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"]
def exporter(self) -> None:
super().exporter()
self.json_to_ansible()
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 hosts namespace "{0}"').format(self.host_namespace))
else:
try:
hosts_config.option('hostnames').name()
except AttributeError:
self.errors.append(_('malformated hosts namespace "{0}", should has "hostnames"').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:
for idx, host in enumerate(hosts['hosts']):
index = str(idx + 1)
if idx < 9:
index = '0' + index
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}
ret['_meta']['hostvars'][host].update(self.dico)
self.dico = ret
RougailOutput = RougailOutputAnsible
__all__ = ("RougailOutputAnsible",)