Debian Codegraph @

ansible_collections/community/general/plugins/test/a_module.py

raw
1 # Copyright (c) 2021, Felix Fontein <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 from __future__ import annotations
6
7 DOCUMENTATION = """
8 name: a_module
9 short_description: Test whether a given string refers to an existing module or action plugin
10 version_added: 4.0.0
11 author: Felix Fontein (@felixfontein)
12 description:
13 - Test whether a given string refers to an existing module or action plugin.
14 - This can be useful in roles, which can use this to ensure that required modules are present ahead of time.
15 options:
16 _input:
17 description: A string denoting a fully qualified collection name (FQCN) of a module or action plugin.
18 type: string
19 required: true
20 """
21
22 EXAMPLES = """
23 - name: Make sure that community.aws.route53 is available
24 ansible.builtin.assert:
25 that:
26 - >
27 'community.aws.route53' is community.general.a_module
28
29 - name: Make sure that community.general.does_not_exist is not a module or action plugin
30 ansible.builtin.assert:
31 that:
32 - "'community.general.does_not_exist' is not community.general.a_module"
33 """
34
35 RETURN = """
36 _value:
37 description: Whether the module or action plugin denoted by the input exists.
38 type: boolean
39 """
40
41 import typing as t
42 from collections.abc import Callable
43
44 from ansible.errors import AnsibleFilterError
45 from ansible.plugins.loader import action_loader, module_loader
46
47 try:
48 from ansible.errors import AnsiblePluginRemovedError
49 except ImportError:
50 AnsiblePluginRemovedError = Exception # type: ignore
51
52
53 def a_module(term: t.Any) -> bool:
54 """
55 Example:
56 - 'community.general.ufw' is community.general.a_module
57 - 'community.general.does_not_exist' is not community.general.a_module
58 """
59 if not isinstance(term, str):
60 raise AnsibleFilterError(f"Parameter must be a string, got {term!r} of type {type(term)}")
61 try:
62 for loader in (action_loader, module_loader):
63 data = loader.find_plugin(term)
64 if data is not None:
65 return True
66 return False
67 except AnsiblePluginRemovedError:
68 return False
69
70
71 class TestModule:
72 """Ansible jinja2 tests"""
73
74 def tests(self) -> dict[str, Callable]:
75 return {
76 "a_module": a_module,
77 }