ansible_ipa_server: Fix ansible-test fake execution test findings

All imports that are only available after installing IPA need to be in a
try exception clause to be able to pass the fake execution test. The old
workaround "if 'ansible.executor' in sys.modules:" is not working with
this test anymore.

If the imports can not be done, all used and needed attributes are
defines with the value None.

The new function check_imports has been added to fail with module.fail_json
if an import exception occured and ANSIBLE_IPA_SERVER_MODULE_IMPORT_ERROR is
not None. This function needs to be called in all modules.

The `copyright` date is extended with `-2022`.
This commit is contained in:
Thomas Woerner
2022-11-08 16:26:48 +01:00
parent 0f0c098fa2
commit 446107f1cb

View File

@@ -3,9 +3,9 @@
# Authors: # Authors:
# Thomas Woerner <twoerner@redhat.com> # Thomas Woerner <twoerner@redhat.com>
# #
# Based on ipa-client-install code # Based on ipa-server-install code
# #
# Copyright (C) 2017 Red Hat # Copyright (C) 2017-2022 Red Hat
# see file 'COPYING' for use and warranty information # see file 'COPYING' for use and warranty information
# #
# This program is free software; you can redistribute it and/or modify # This program is free software; you can redistribute it and/or modify
@@ -23,12 +23,12 @@
from __future__ import (absolute_import, division, print_function) from __future__ import (absolute_import, division, print_function)
__metaclass__ = type __metaclass__ = type # pylint: disable=invalid-name
__all__ = ["IPAChangeConf", "certmonger", "sysrestore", "root_logger", __all__ = ["IPAChangeConf", "certmonger", "sysrestore", "root_logger",
"ipa_generate_password", "run", "ScriptError", "services", "ipa_generate_password", "run", "ScriptError", "services",
"tasks", "errors", "x509", "DOMAIN_LEVEL_0", "MIN_DOMAIN_LEVEL", "tasks", "errors", "x509", "DOMAIN_LEVEL_0", "MIN_DOMAIN_LEVEL",
"validate_domain_name", "MAX_DOMAIN_LEVEL", "validate_domain_name",
"no_matching_interface_for_ip_address_warning", "no_matching_interface_for_ip_address_warning",
"check_zone_overlap", "timeconf", "ntpinstance", "adtrust", "check_zone_overlap", "timeconf", "ntpinstance", "adtrust",
"bindinstance", "ca", "dns", "httpinstance", "installutils", "bindinstance", "ca", "dns", "httpinstance", "installutils",
@@ -41,28 +41,19 @@ __all__ = ["IPAChangeConf", "certmonger", "sysrestore", "root_logger",
"adtrustinstance", "IPAAPI_USER", "sync_time", "PKIIniLoader", "adtrustinstance", "IPAAPI_USER", "sync_time", "PKIIniLoader",
"default_subject_base", "default_ca_subject_dn", "default_subject_base", "default_ca_subject_dn",
"check_ldap_conf", "encode_certificate", "decode_certificate", "check_ldap_conf", "encode_certificate", "decode_certificate",
"check_available_memory", "getargspec", "get_min_idstart"] "check_available_memory", "getargspec", "get_min_idstart",
"paths", "api", "ipautil", "adtrust_imported", "NUM_VERSION",
"time_service", "kra_imported", "dsinstance", "IPA_PYTHON_VERSION",
"NUM_VERSION"]
import sys import sys
import logging
# HACK: workaround for Ansible 2.9 # Import getargspec from inspect or provide own getargspec for
# https://github.com/ansible/ansible/issues/68361 # Python 2 compatibility with Python 3.11+.
if 'ansible.executor' in sys.modules: try:
for attr in __all__:
setattr(sys.modules[__name__], attr, None)
else:
import logging
from contextlib import contextmanager as contextlib_contextmanager
from ansible.module_utils import six
import base64
# Import getargspec from inspect or provide own getargspec for
# Python 2 compatibility with Python 3.11+.
try:
from inspect import getargspec from inspect import getargspec
except ImportError: except ImportError:
from collections import namedtuple from collections import namedtuple
from inspect import getfullargspec from inspect import getfullargspec
@@ -80,6 +71,12 @@ else:
", use inspect.signature() API which can support them") ", use inspect.signature() API which can support them")
return ArgSpec(args, varargs, varkw, defaults) return ArgSpec(args, varargs, varkw, defaults)
try:
from contextlib import contextmanager as contextlib_contextmanager
from ansible.module_utils import six
import base64
from ipapython.version import NUM_VERSION, VERSION from ipapython.version import NUM_VERSION, VERSION
if NUM_VERSION < 30201: if NUM_VERSION < 30201:
@@ -211,23 +208,35 @@ else:
raise Exception("freeipa version '%s' is too old" % VERSION) raise Exception("freeipa version '%s' is too old" % VERSION)
logger = logging.getLogger("ipa-server-install") except ImportError as _err:
ANSIBLE_IPA_SERVER_MODULE_IMPORT_ERROR = str(_err)
def setup_logging(): for attr in __all__:
setattr(sys.modules[__name__], attr, None)
else:
ANSIBLE_IPA_SERVER_MODULE_IMPORT_ERROR = None
logger = logging.getLogger("ipa-server-install")
def setup_logging():
# logger.setLevel(logging.DEBUG) # logger.setLevel(logging.DEBUG)
standard_logging_setup( standard_logging_setup(
paths.IPASERVER_INSTALL_LOG, verbose=False, debug=False, paths.IPASERVER_INSTALL_LOG, verbose=False, debug=False,
filemode='a', console_format='%(message)s') filemode='a', console_format='%(message)s')
@contextlib_contextmanager
def redirect_stdout(stream): @contextlib_contextmanager
def redirect_stdout(stream):
sys.stdout = stream sys.stdout = stream
try: try:
yield stream yield stream
finally: finally:
sys.stdout = sys.__stdout__ sys.stdout = sys.__stdout__
class AnsibleModuleLog():
class AnsibleModuleLog():
def __init__(self, module): def __init__(self, module):
self.module = module self.module = module
_ansible_module_log = self _ansible_module_log = self
@@ -264,9 +273,10 @@ else:
self.module.debug(msg) self.module.debug(msg)
# self.module.warn(msg) # self.module.warn(msg)
# pylint: disable=too-few-public-methods, useless-object-inheritance
# pylint: disable=too-many-instance-attributes # pylint: disable=too-few-public-methods, useless-object-inheritance
class options_obj(object): # pylint: disable=invalid-name # pylint: disable=too-many-instance-attributes
class options_obj(object): # pylint: disable=invalid-name
def __init__(self): def __init__(self):
self._replica_install = False self._replica_install = False
self.dnssec_master = False # future unknown self.dnssec_master = False # future unknown
@@ -289,59 +299,62 @@ else:
for name in self.__dict__: for name in self.__dict__:
yield self, name yield self, name
# pylint: enable=too-few-public-methods, useless-object-inheritance
# pylint: enable=too-many-instance-attributes # pylint: enable=too-few-public-methods, useless-object-inheritance
options = options_obj()
installer = options
# pylint: disable=attribute-defined-outside-init
# ServerMasterInstall # pylint: enable=too-many-instance-attributes
options.add_sids = True options = options_obj()
options.add_agents = False installer = options
# Installable # pylint: disable=attribute-defined-outside-init
options.uninstalling = False
# ServerInstallInterface # ServerMasterInstall
options.description = "Server" options.add_sids = True
options.add_agents = False
options.kinit_attempts = 1 # Installable
options.fixed_primary = True options.uninstalling = False
options.permit = False
options.enable_dns_updates = False
options.no_krb5_offline_passwords = False
options.preserve_sssd = False
options.no_sssd = False
# ServerMasterInstall # ServerInstallInterface
options.force_join = False options.description = "Server"
options.servers = None
options.no_wait_for_dns = True
options.host_password = None
options.keytab = None
options.setup_ca = True
# always run sidgen task and do not allow adding agents on first master
options.add_sids = True
options.add_agents = False
# ADTrustInstallInterface options.kinit_attempts = 1
# no_msdcs is deprecated options.fixed_primary = True
options.no_msdcs = False options.permit = False
options.enable_dns_updates = False
options.no_krb5_offline_passwords = False
options.preserve_sssd = False
options.no_sssd = False
# For pylint # ServerMasterInstall
options.external_cert_files = None options.force_join = False
options.dirsrv_cert_files = None options.servers = None
options.no_wait_for_dns = True
options.host_password = None
options.keytab = None
options.setup_ca = True
# always run sidgen task and do not allow adding agents on first master
options.add_sids = True
options.add_agents = False
# Uninstall # ADTrustInstallInterface
options.ignore_topology_disconnect = False # no_msdcs is deprecated
options.ignore_last_of_role = False options.no_msdcs = False
# pylint: enable=attribute-defined-outside-init # For pylint
options.external_cert_files = None
options.dirsrv_cert_files = None
# pylint: disable=invalid-name # Uninstall
def api_Backend_ldap2(host_name, setup_ca, connect=False): options.ignore_topology_disconnect = False
options.ignore_last_of_role = False
# pylint: enable=attribute-defined-outside-init
# pylint: disable=invalid-name
def api_Backend_ldap2(host_name, setup_ca, connect=False):
# we are sure we have the configuration file ready. # we are sure we have the configuration file ready.
cfg = dict(context='installer', confdir=paths.ETC_IPA, in_server=True, cfg = dict(context='installer', confdir=paths.ETC_IPA, in_server=True,
host=host_name) host=host_name)
@@ -354,9 +367,11 @@ else:
if connect: if connect:
api.Backend.ldap2.connect() api.Backend.ldap2.connect()
# pylint: enable=invalid-name
def ds_init_info(ansible_log, fstore, domainlevel, dirsrv_config_file, # pylint: enable=invalid-name
def ds_init_info(ansible_log, fstore, domainlevel, dirsrv_config_file,
realm_name, host_name, domain_name, dm_password, realm_name, host_name, domain_name, dm_password,
idstart, idmax, subject_base, ca_subject, idstart, idmax, subject_base, ca_subject,
_no_hbac_allow, dirsrv_pkcs12_info, no_pkinit): _no_hbac_allow, dirsrv_pkcs12_info, no_pkinit):
@@ -387,7 +402,8 @@ else:
return _ds return _ds
def ansible_module_get_parsed_ip_addresses(ansible_module,
def ansible_module_get_parsed_ip_addresses(ansible_module,
param='ip_addresses'): param='ip_addresses'):
ip_addrs = [] ip_addrs = []
for _ip in ansible_module.params.get(param): for _ip in ansible_module.params.get(param):
@@ -399,7 +415,8 @@ else:
ip_addrs.append(ip_parsed) ip_addrs.append(ip_parsed)
return ip_addrs return ip_addrs
def encode_certificate(cert):
def encode_certificate(cert):
""" """
Encode a certificate using base64. Encode a certificate using base64.
@@ -413,7 +430,8 @@ else:
encoded = encoded.decode('ascii') encoded = encoded.decode('ascii')
return encoded return encoded
def decode_certificate(cert):
def decode_certificate(cert):
""" """
Decode a certificate using base64. Decode a certificate using base64.
@@ -431,3 +449,8 @@ else:
else: else:
cert = base64.b64decode(cert) cert = base64.b64decode(cert)
return cert return cert
def check_imports(module):
if ANSIBLE_IPA_SERVER_MODULE_IMPORT_ERROR is not None:
module.fail_json(msg=ANSIBLE_IPA_SERVER_MODULE_IMPORT_ERROR)