diff --git a/awx_collection/plugins/module_utils/awxkit.py b/awx_collection/plugins/module_utils/awxkit.py index ad9c3a9cc4..5029d44526 100644 --- a/awx_collection/plugins/module_utils/awxkit.py +++ b/awx_collection/plugins/module_utils/awxkit.py @@ -4,6 +4,7 @@ __metaclass__ = type from .controller_api import ControllerModule from ansible.module_utils.basic import missing_required_lib +from os import getenv try: from awxkit.api.client import Connection @@ -42,7 +43,13 @@ class ControllerAWXKitModule(ControllerModule): if not self.apiV2Ref: if not self.authenticated: self.authenticate() - v2_index = get_registered_page('/api/v2/')(self.connection).get() + prefix = getenv('CONTROLLER_OPTIONAL_API_URLPATTERN_PREFIX', '/api/') + if not prefix.startswith('/'): + prefix = f"/{prefix}" + if not prefix.endswith('/'): + prefix = f"{prefix}/" + v2_path = f"{prefix}v2/" + v2_index = get_registered_page(v2_path)(self.connection).get() self.api_ref = ApiV2(connection=self.connection, **{'json': v2_index}) return self.api_ref diff --git a/awx_collection/test/awx/test_controller_api_urlpattern_prefix.py b/awx_collection/test/awx/test_controller_api_urlpattern_prefix.py new file mode 100644 index 0000000000..8500859150 --- /dev/null +++ b/awx_collection/test/awx/test_controller_api_urlpattern_prefix.py @@ -0,0 +1,36 @@ +from __future__ import absolute_import, division, print_function + +import os +from unittest import mock + +__metaclass__ = type + +import pytest + + +def mock_get_registered_page(prefix): + return mock.Mock(return_value=mock.Mock(get=mock.Mock(return_value={'prefix': prefix}))) + + +@pytest.mark.parametrize( + "env_prefix, controller_host, expected", + [ + # without CONTROLLER_OPTIONAL_API_URLPATTERN_PREFIX env variable + [None, "https://localhost", "/api/v2/"], + # with CONTROLLER_OPTIONAL_API_URLPATTERN_PREFIX env variable + ["/api/controller/", "https://localhost", "/api/controller/v2/"], + ["/api/controller", "https://localhost", "/api/controller/v2/"], + ["api/controller", "https://localhost", "/api/controller/v2/"], + ["/custom/path/", "https://localhost", "/custom/path/v2/"], + ], +) +def test_controller_awxkit_get_api_v2_object(collection_import, env_prefix, controller_host, expected): + controller_awxkit_class = collection_import('plugins.module_utils.awxkit').ControllerAWXKitModule + controller_awxkit = controller_awxkit_class(argument_spec={}, direct_params=dict(controller_host=controller_host)) + with mock.patch('plugins.module_utils.awxkit.get_registered_page', mock_get_registered_page): + if env_prefix: + with mock.patch.dict(os.environ, {"CONTROLLER_OPTIONAL_API_URLPATTERN_PREFIX": env_prefix}): + api_v2_object = controller_awxkit.get_api_v2_object() + else: + api_v2_object = controller_awxkit.get_api_v2_object() + assert getattr(api_v2_object, 'prefix') == expected