Debian Codegraph @

lib/ansible/plugins/lookup/config.py

raw
1 # (c) 2017 Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3 from __future__ import annotations
4
5 DOCUMENTATION = """
6 name: config
7 author: Ansible Core Team
8 version_added: "2.5"
9 short_description: Display the 'resolved' Ansible option values.
10 description:
11 - Retrieves the value of an Ansible configuration setting, resolving all sources, from defaults, ansible.cfg, environment,
12 CLI, and variables, but not keywords.
13 - The values returned assume the context of the current host or C(inventory_hostname).
14 - You can use C(ansible-config list) to see the global available settings, add C(-t all) to also show plugin options.
15 positional: _terms
16 options:
17 _terms:
18 description: The option(s) to look up.
19 required: True
20 on_missing:
21 description: Action to take if term is missing from config
22 default: error
23 type: string
24 choices:
25 error: Issue an error message and raise fatal signal
26 warn: Issue a warning message and continue
27 skip: Silently ignore
28 plugin_type:
29 description: The type of the plugin referenced by 'plugin_name' option.
30 choices: ['become', 'cache', 'callback', 'cliconf', 'connection', 'httpapi', 'inventory', 'lookup', 'netconf', 'shell', 'vars']
31 type: string
32 version_added: '2.12'
33 plugin_name:
34 description: The name of the plugin for which you want to retrieve configuration settings.
35 type: string
36 version_added: '2.12'
37 show_origin:
38 description: Set this to return what configuration subsystem the value came from
39 (defaults, config file, environment, CLI, or variables).
40 type: bool
41 version_added: '2.16'
42 notes:
43 - Be aware that currently this lookup cannot take keywords nor delegation into account,
44 so for options that support keywords or are affected by delegation, it is at best a good guess or approximation.
45 """
46
47 EXAMPLES = """
48 - name: Show configured default become user
49 ansible.builtin.debug: msg="{{ lookup('ansible.builtin.config', 'DEFAULT_BECOME_USER')}}"
50
51 - name: print out role paths
52 ansible.builtin.debug:
53 msg: "These are the configured role paths: {{lookup('ansible.builtin.config', 'DEFAULT_ROLES_PATH')}}"
54
55 - name: find retry files, skip if missing that key
56 ansible.builtin.find:
57 paths: "{{lookup('ansible.builtin.config', 'RETRY_FILES_SAVE_PATH')|default(playbook_dir, True)}}"
58 patterns: "*.retry"
59
60 - name: see the colors
61 ansible.builtin.debug: msg="{{item}}"
62 loop: "{{lookup('ansible.builtin.config', 'COLOR_OK', 'COLOR_CHANGED', 'COLOR_SKIP', wantlist=True)}}"
63
64 - name: skip if bad value in var
65 ansible.builtin.debug: msg="{{ lookup('ansible.builtin.config', config_in_var, on_missing='skip')}}"
66 var:
67 config_in_var: UNKNOWN
68
69 - name: show remote user and port for ssh connection
70 ansible.builtin.debug: msg={{q("ansible.builtin.config", "remote_user", "port", plugin_type="connection", plugin_name="ssh", on_missing='skip')}}
71
72 - name: show remote_tmp setting for shell (sh) plugin
73 ansible.builtin.debug: msg={{q("ansible.builtin.config", "remote_tmp", plugin_type="shell", plugin_name="sh")}}
74 """
75
76 RETURN = """
77 _raw:
78 description:
79 - A list of value(s) of the key(s) in the config if show_origin is false (default)
80 - Optionally, a list of 2 element lists (value, origin) if show_origin is true
81 type: raw
82 """
83
84 from collections import ChainMap
85
86 import ansible.plugins.loader as plugin_loader
87
88 from ansible import constants as C
89 from ansible.module_utils.common.sentinel import Sentinel
90 from ansible.errors import AnsibleError, AnsibleUndefinedConfigEntry
91 from ansible.plugins.lookup import LookupBase
92
93
94 class LookupModule(LookupBase):
95
96 def run(self, terms, variables=None, **kwargs):
97
98 self.set_options(var_options=variables, direct=kwargs)
99
100 missing = self.get_option('on_missing')
101 ptype = self.get_option('plugin_type')
102 pname = self.get_option('plugin_name')
103 show_origin = self.get_option('show_origin')
104
105 if (ptype or pname) and not (ptype and pname):
106 raise AnsibleError('Both plugin_type and plugin_name are required, cannot use one without the other.')
107
108 ret = []
109
110 # primarily use task vars, but fallback to existing constants when needed
111 var_context = ChainMap(variables, vars(C))
112
113 for term in terms:
114 if not isinstance(term, str):
115 raise AnsibleError(f'Invalid setting identifier, {term!r} is not a {str}, its a {type(term)}.')
116
117 result = Sentinel
118 origin = None
119
120 # plugin creates settings on load, we ensure that happens here
121 if pname:
122 # this is cached so not too expensive
123 loader = getattr(plugin_loader, f'{ptype}_loader')
124 p = loader.get(pname, class_only=True)
125 if p is None:
126 raise AnsibleError(f"Unable to load {ptype} plugin {pname!r}.")
127 try:
128 result, origin = C.config.get_config_value_and_origin(term, plugin_type=ptype, plugin_name=pname, variables=var_context)
129 except AnsibleUndefinedConfigEntry as e:
130 match missing:
131 case 'error':
132 raise
133 case 'skip':
134 pass
135 case 'warn':
136 self._display.error_as_warning(msg=f"Skipping {term}.", exception=e)
137
138 if result is not Sentinel:
139 if show_origin:
140 ret.append([result, origin])
141 else:
142 ret.append(result)
143 return ret