Debian Codegraph @

ansible_collections/community/general/plugins/modules/alternatives.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2014, Gabe Mulley <[email protected]>
4 # Copyright (c) 2015, David Wittman <[email protected]>
5 # Copyright (c) 2022, Marius Rieder <[email protected]>
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 from __future__ import annotations
10
11 DOCUMENTATION = r"""
12 module: alternatives
13 short_description: Manages alternative programs for common commands
14 description:
15 - Manages symbolic links using the C(update-alternatives) tool.
16 - Useful when multiple programs are installed but provide similar functionality (for example, different editors).
17 author:
18 - Marius Rieder (@jiuka)
19 - David Wittman (@DavidWittman)
20 - Gabe Mulley (@mulby)
21 extends_documentation_fragment:
22 - community.general._attributes
23 attributes:
24 check_mode:
25 support: full
26 diff_mode:
27 support: full
28 options:
29 name:
30 description:
31 - The generic name of the link.
32 type: str
33 required: true
34 path:
35 description:
36 - The path to the real executable that the link should point to.
37 type: path
38 family:
39 description:
40 - The family groups similar alternatives. This option is available only on RHEL-based distributions.
41 type: str
42 version_added: 10.1.0
43 link:
44 description:
45 - The path to the symbolic link that should point to the real executable.
46 - This option is always required on RHEL-based distributions. On Debian-based distributions this option is required
47 when the alternative O(name) is unknown to the system.
48 type: path
49 priority:
50 description:
51 - The priority of the alternative. If no priority is given for creation V(50) is used as a fallback.
52 type: int
53 state:
54 description:
55 - V(present) - install the alternative (if not already installed), but do not set it as the currently selected alternative
56 for the group.
57 - V(selected) - install the alternative (if not already installed), and set it as the currently selected alternative
58 for the group.
59 - V(auto) - install the alternative (if not already installed), and set the group to auto mode. Added in community.general
60 5.1.0.
61 - V(absent) - removes the alternative. Added in community.general 5.1.0.
62 choices: [present, selected, auto, absent]
63 default: selected
64 type: str
65 version_added: 4.8.0
66 subcommands:
67 description:
68 - A list of subcommands.
69 - Each subcommand needs a name, a link and a path parameter.
70 - Subcommands are also named C(slaves) or C(followers), depending on the version of C(alternatives).
71 type: list
72 elements: dict
73 aliases: ['slaves']
74 suboptions:
75 name:
76 description:
77 - The generic name of the subcommand.
78 type: str
79 required: true
80 path:
81 description:
82 - The path to the real executable that the subcommand should point to.
83 type: path
84 required: true
85 link:
86 description:
87 - The path to the symbolic link that should point to the real subcommand executable.
88 type: path
89 required: true
90 version_added: 5.1.0
91 requirements: [update-alternatives]
92 """
93
94 EXAMPLES = r"""
95 - name: Correct java version selected
96 community.general.alternatives:
97 name: java
98 path: /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java
99
100 - name: Select java-11-openjdk.x86_64 family
101 community.general.alternatives:
102 name: java
103 family: java-11-openjdk.x86_64
104 when: ansible_os_family == 'RedHat'
105
106 - name: Alternatives link created
107 community.general.alternatives:
108 name: hadoop-conf
109 link: /etc/hadoop/conf
110 path: /etc/hadoop/conf.ansible
111
112 - name: Make java 32 bit an alternative with low priority
113 community.general.alternatives:
114 name: java
115 path: /usr/lib/jvm/java-7-openjdk-i386/jre/bin/java
116 priority: -10
117
118 - name: Install Python 3.5 but do not select it
119 community.general.alternatives:
120 name: python
121 path: /usr/bin/python3.5
122 link: /usr/bin/python
123 state: present
124
125 - name: Install Python 3.5 and reset selection to auto
126 community.general.alternatives:
127 name: python
128 path: /usr/bin/python3.5
129 link: /usr/bin/python
130 state: auto
131
132 - name: keytool is a subcommand of java
133 community.general.alternatives:
134 name: java
135 link: /usr/bin/java
136 path: /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java
137 subcommands:
138 - name: keytool
139 link: /usr/bin/keytool
140 path: /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/keytool
141 """
142
143 import os
144 import re
145
146 from ansible.module_utils.basic import AnsibleModule
147
148
149 class AlternativeState:
150 PRESENT = "present"
151 SELECTED = "selected"
152 ABSENT = "absent"
153 AUTO = "auto"
154
155 @classmethod
156 def to_list(cls):
157 return [cls.PRESENT, cls.SELECTED, cls.ABSENT, cls.AUTO]
158
159
160 class AlternativesModule:
161 _UPDATE_ALTERNATIVES = None
162
163 def __init__(self, module):
164 self.module = module
165 self.result = dict(changed=False, diff=dict(before=dict(), after=dict()))
166 self.module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
167 self.messages = []
168 self.run()
169
170 @property
171 def mode_present(self):
172 return self.module.params.get("state") in [
173 AlternativeState.PRESENT,
174 AlternativeState.SELECTED,
175 AlternativeState.AUTO,
176 ]
177
178 @property
179 def mode_selected(self):
180 return self.module.params.get("state") == AlternativeState.SELECTED
181
182 @property
183 def mode_auto(self):
184 return self.module.params.get("state") == AlternativeState.AUTO
185
186 def run(self):
187 self.parse()
188
189 if self.mode_present:
190 # Check if we need to (re)install
191 subcommands_parameter = self.module.params["subcommands"]
192 priority_parameter = self.module.params["priority"]
193 if self.path is not None and (
194 self.path not in self.current_alternatives
195 or (
196 priority_parameter is not None
197 and self.current_alternatives[self.path].get("priority") != priority_parameter
198 )
199 or (
200 subcommands_parameter is not None
201 and (
202 not all(
203 s in subcommands_parameter for s in self.current_alternatives[self.path].get("subcommands")
204 )
205 or not all(
206 s in self.current_alternatives[self.path].get("subcommands") for s in subcommands_parameter
207 )
208 )
209 )
210 ):
211 self.install()
212
213 # Check if we need to set the preference
214 is_same_path = self.path is not None and self.current_path == self.path
215 is_same_family = False
216 if self.current_path is not None and self.current_path in self.current_alternatives:
217 current_alternative = self.current_alternatives[self.current_path]
218 is_same_family = current_alternative.get("family") == self.family
219
220 if self.mode_selected and not (is_same_path or is_same_family):
221 self.set()
222
223 # Check if we need to reset to auto
224 if self.mode_auto and self.current_mode == "manual":
225 self.auto()
226 else:
227 # Check if we need to uninstall
228 if self.path in self.current_alternatives:
229 self.remove()
230
231 self.result["msg"] = " ".join(self.messages)
232 self.module.exit_json(**self.result)
233
234 def install(self):
235 if not os.path.exists(self.path):
236 self.module.fail_json(msg=f"Specified path {self.path} does not exist")
237 if not self.link:
238 self.module.fail_json(
239 msg="Needed to install the alternative, but unable to do so as we are missing the link"
240 )
241
242 cmd = [self.UPDATE_ALTERNATIVES, "--install", self.link, self.name, self.path, str(self.priority)]
243 if self.family is not None:
244 cmd.extend(["--family", self.family])
245
246 if self.module.params["subcommands"] is not None:
247 subcommands = [["--slave", subcmd["link"], subcmd["name"], subcmd["path"]] for subcmd in self.subcommands]
248 cmd += [item for sublist in subcommands for item in sublist]
249
250 self.result["changed"] = True
251 self.messages.append(f"Install alternative '{self.path}' for '{self.name}'.")
252
253 if not self.module.check_mode:
254 self.module.run_command(cmd, check_rc=True)
255
256 if self.module._diff:
257 self.result["diff"]["after"] = dict(
258 state=AlternativeState.PRESENT,
259 path=self.path,
260 family=self.family,
261 priority=self.priority,
262 link=self.link,
263 )
264 if self.subcommands:
265 self.result["diff"]["after"].update(dict(subcommands=self.subcommands))
266
267 def remove(self):
268 cmd = [self.UPDATE_ALTERNATIVES, "--remove", self.name, self.path]
269 self.result["changed"] = True
270 self.messages.append(f"Remove alternative '{self.path}' from '{self.name}'.")
271
272 if not self.module.check_mode:
273 self.module.run_command(cmd, check_rc=True)
274
275 if self.module._diff:
276 self.result["diff"]["after"] = dict(state=AlternativeState.ABSENT)
277
278 def set(self):
279 # Path takes precedence over family as it is more specific
280 if self.path is None:
281 arg = self.family
282 else:
283 arg = self.path
284
285 cmd = [self.UPDATE_ALTERNATIVES, "--set", self.name, arg]
286 self.result["changed"] = True
287 self.messages.append(f"Set alternative '{arg}' for '{self.name}'.")
288
289 if not self.module.check_mode:
290 self.module.run_command(cmd, check_rc=True)
291
292 if self.module._diff:
293 self.result["diff"]["after"]["state"] = AlternativeState.SELECTED
294
295 def auto(self):
296 cmd = [self.UPDATE_ALTERNATIVES, "--auto", self.name]
297 self.messages.append(f"Set alternative to auto for '{self.name}'.")
298 self.result["changed"] = True
299
300 if not self.module.check_mode:
301 self.module.run_command(cmd, check_rc=True)
302
303 if self.module._diff:
304 self.result["diff"]["after"]["state"] = AlternativeState.PRESENT
305
306 @property
307 def name(self):
308 return self.module.params.get("name")
309
310 @property
311 def path(self):
312 return self.module.params.get("path")
313
314 @property
315 def family(self):
316 return self.module.params.get("family")
317
318 @property
319 def link(self):
320 return self.module.params.get("link") or self.current_link
321
322 @property
323 def priority(self):
324 if self.module.params.get("priority") is not None:
325 return self.module.params.get("priority")
326 return self.current_alternatives.get(self.path, {}).get("priority", 50)
327
328 @property
329 def subcommands(self):
330 if self.module.params.get("subcommands") is not None:
331 return self.module.params.get("subcommands")
332 elif self.path in self.current_alternatives and self.current_alternatives[self.path].get("subcommands"):
333 return self.current_alternatives[self.path].get("subcommands")
334 return None
335
336 @property
337 def UPDATE_ALTERNATIVES(self):
338 if self._UPDATE_ALTERNATIVES is None:
339 self._UPDATE_ALTERNATIVES = self.module.get_bin_path("update-alternatives", True)
340 return self._UPDATE_ALTERNATIVES
341
342 def parse(self):
343 self.current_mode = None
344 self.current_path = None
345 self.current_link = None
346 self.current_alternatives = {}
347
348 # Run `update-alternatives --display <name>` to find existing alternatives
349 (rc, display_output, dummy) = self.module.run_command([self.UPDATE_ALTERNATIVES, "--display", self.name])
350
351 if rc != 0:
352 self.module.debug(f"No current alternative found. '{self.UPDATE_ALTERNATIVES}' exited with {rc}")
353 return
354
355 current_mode_regex = re.compile(r"\s-\s(?:status\sis\s)?(\w*)(?:\smode|.)$", re.MULTILINE)
356 current_path_regex = re.compile(r"^\s*link currently points to (.*)$", re.MULTILINE)
357 current_link_regex = re.compile(r"^\s*link \w+ is (.*)$", re.MULTILINE)
358 subcmd_path_link_regex = re.compile(r"^\s*(?:slave|follower) (\S+) is (.*)$", re.MULTILINE)
359
360 alternative_regex = re.compile(
361 r"^(\/.*)\s-\s(?:family\s(\S+)\s)?priority\s(\d+)((?:\s+(?:slave|follower).*)*)", re.MULTILINE
362 )
363 subcmd_regex = re.compile(r"^\s+(?:slave|follower) (.*): (.*)$", re.MULTILINE)
364
365 match = current_mode_regex.search(display_output)
366 if not match:
367 self.module.debug("No current mode found in output")
368 return
369 self.current_mode = match.group(1)
370
371 match = current_path_regex.search(display_output)
372 if not match:
373 self.module.debug("No current path found in output")
374 else:
375 self.current_path = match.group(1)
376
377 match = current_link_regex.search(display_output)
378 if not match:
379 self.module.debug("No current link found in output")
380 else:
381 self.current_link = match.group(1)
382
383 subcmd_path_map = dict(subcmd_path_link_regex.findall(display_output))
384 if not subcmd_path_map and self.subcommands:
385 subcmd_path_map = {s["name"]: s["link"] for s in self.subcommands}
386
387 for path, family, prio, subcmd in alternative_regex.findall(display_output):
388 self.current_alternatives[path] = dict(
389 priority=int(prio),
390 family=family,
391 subcommands=[
392 dict(name=name, path=spath, link=subcmd_path_map.get(name))
393 for name, spath in subcmd_regex.findall(subcmd)
394 if spath != "(null)"
395 ],
396 )
397
398 if self.module._diff:
399 if self.path in self.current_alternatives:
400 self.result["diff"]["before"].update(
401 dict(
402 state=AlternativeState.PRESENT,
403 path=self.path,
404 priority=self.current_alternatives[self.path].get("priority"),
405 link=self.current_link,
406 )
407 )
408 if self.current_alternatives[self.path].get("subcommands"):
409 self.result["diff"]["before"].update(
410 dict(subcommands=self.current_alternatives[self.path].get("subcommands"))
411 )
412 if self.current_mode == "manual" and self.current_path != self.path:
413 self.result["diff"]["before"].update(dict(state=AlternativeState.SELECTED))
414 else:
415 self.result["diff"]["before"].update(dict(state=AlternativeState.ABSENT))
416
417
418 def main():
419 module = AnsibleModule(
420 argument_spec=dict(
421 name=dict(type="str", required=True),
422 path=dict(type="path"),
423 family=dict(type="str"),
424 link=dict(type="path"),
425 priority=dict(type="int"),
426 state=dict(
427 type="str",
428 choices=AlternativeState.to_list(),
429 default=AlternativeState.SELECTED,
430 ),
431 subcommands=dict(
432 type="list",
433 elements="dict",
434 aliases=["slaves"],
435 options=dict(
436 name=dict(type="str", required=True),
437 path=dict(type="path", required=True),
438 link=dict(type="path", required=True),
439 ),
440 ),
441 ),
442 supports_check_mode=True,
443 required_one_of=[("path", "family")],
444 )
445
446 AlternativesModule(module)
447
448
449 if __name__ == "__main__":
450 main()