From a029e529a6f7eedda31204acb2b09119fc39dcb8 Mon Sep 17 00:00:00 2001 From: David Salvisberg Date: Wed, 4 Sep 2024 12:20:23 +0200 Subject: [PATCH] Suppresses Ansible warning when creating multiple Api instances --- CHANGELOG.rst | 4 ++++ pyproject.toml | 1 - src/suitable/api.py | 22 +++++++++++++++++++++- 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index f516216..cbe2291 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,6 +1,10 @@ Changelog --------- +- Avoids Ansible spamming us with warnings when creating multiple + `Api` instances. + [Daverball] + 0.20.2 (2024-09-03) ~~~~~~~~~~~~~~~~~~~ diff --git a/pyproject.toml b/pyproject.toml index 12ce189..bd081fe 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,7 +7,6 @@ log_level = "INFO" testpaths = ["tests"] filterwarnings = [ "ignore:The _yaml extension module is now located at yaml._yaml", - "ignore:AnsibleCollectionFinder has already been configured" ] [tool.coverage.run] diff --git a/src/suitable/api.py b/src/suitable/api.py index 63a297d..580297d 100644 --- a/src/suitable/api.py +++ b/src/suitable/api.py @@ -136,6 +136,15 @@ def __init__( Provide a custom path or sequence of path to look for ansible collections when loading/hooking the modules. + Ansible only initializes the module loader once, so it's not + possible to have multiple `Api` instances with different + values for this parameter. The first one will always be the + one that matters. + + Additionally if the loader has already been initialized prior + to the creation of the Api instance, then this parameter has + no effect at all. + Requires ansible-core >= 2.15 :param host_key_checking: @@ -237,8 +246,19 @@ def __init__( collections_path = [collections_path] if Version(__version__) >= Version('2.15'): + import warnings from ansible.plugins.loader import init_plugin_loader - init_plugin_loader(collections_path) + # NOTE: Ansible emits a warning here, but it's harmless to + # call this function multiple times, it just doesn't + # do anything the second time around. + # We don't want to propagate this warning. + with warnings.catch_warnings(): + warnings.filterwarnings( + 'ignore', + r'AnsibleCollectionFinder has already been configured', + UserWarning + ) + init_plugin_loader(collections_path) for module in list_ansible_modules(): ModuleRunner(module).hookup(self)