Debian Codegraph @

lib/ansible/modules/package_facts.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
4 # most of it copied from AWX's scan_packages module
5
6 from __future__ import annotations
7
8
9 DOCUMENTATION = """
10 module: package_facts
11 short_description: Package information as facts
12 description:
13 - Return information about installed packages as facts.
14 options:
15 manager:
16 description:
17 - The package manager(s) used by the system so we can query the package information.
18 This is a list and can support multiple package managers per system, since version 2.8.
19 - The V(portage) and V(pkg) options were added in version 2.8.
20 - The V(apk) option was added in version 2.11.
21 - The V(pkg_info) option was added in version 2.13.
22 - Aliases were added in 2.18, to support using C(manager={{ansible_facts['pkg_mgr']}})
23 default: ['auto']
24 choices:
25 auto: Depending on O(strategy), will match the first or all package managers provided, in order
26 rpm: For RPM based distros, requires RPM Python bindings, not installed by default on Suse or Fedora 41+ (python3-rpm)
27 yum: Alias to rpm
28 dnf: Alias to rpm
29 dnf5: Alias to rpm
30 zypper: Alias to rpm
31 apt: For DEB based distros, C(python-apt) package must be installed on targeted hosts
32 portage: Handles ebuild packages, it requires the C(qlist) utility, which is part of 'app-portage/portage-utils'
33 pkg: libpkg front end (FreeBSD)
34 pkg5: Alias to pkg
35 pkgng: Alias to pkg
36 pacman: Archlinux package manager/builder
37 apk: Alpine Linux package manager
38 pkg_info: OpenBSD package manager
39 openbsd_pkg: Alias to pkg_info
40 type: list
41 elements: str
42 strategy:
43 description:
44 - This option controls how the module queries the package managers on the system.
45 choices:
46 first: returns only information for the first supported package manager available.
47 all: returns information for all supported and available package managers on the system.
48 default: 'first'
49 type: str
50 version_added: "2.8"
51 version_added: "2.5"
52 requirements:
53 - See details per package manager in the O(manager) option.
54 author:
55 - Matthew Jones (@matburt)
56 - Brian Coca (@bcoca)
57 - Adam Miller (@maxamillion)
58 extends_documentation_fragment:
59 - action_common_attributes
60 - action_common_attributes.facts
61 attributes:
62 check_mode:
63 support: full
64 diff_mode:
65 support: none
66 facts:
67 support: full
68 platform:
69 platforms: posix
70 """
71
72 EXAMPLES = """
73 - name: Gather the package facts
74 ansible.builtin.package_facts:
75 manager: auto
76
77 - name: Print the package facts
78 ansible.builtin.debug:
79 var: ansible_facts.packages
80
81 - name: Check whether a package called foobar is installed
82 ansible.builtin.debug:
83 msg: "{{ ansible_facts.packages['foobar'] | length }} versions of foobar are installed!"
84 when: "'foobar' in ansible_facts.packages"
85
86 """
87
88 RETURN = """
89 ansible_facts:
90 description: Facts to add to ansible_facts.
91 returned: always
92 type: complex
93 contains:
94 packages:
95 description:
96 - Maps the package name to a non-empty list of dicts with package information.
97 - Every dict in the list corresponds to one installed version of the package.
98 - The fields described below are present for all package managers. Depending on the
99 package manager, there might be more fields for a package.
100 returned: when operating system level package manager is specified or auto detected manager
101 type: dict
102 contains:
103 name:
104 description: The package's name.
105 returned: always
106 type: str
107 version:
108 description: The package's version.
109 returned: always
110 type: str
111 source:
112 description: Where information on the package came from.
113 returned: always
114 type: str
115 sample: |-
116 {
117 "packages": {
118 "kernel": [
119 {
120 "name": "kernel",
121 "source": "rpm",
122 "version": "3.10.0",
123 ...
124 },
125 {
126 "name": "kernel",
127 "source": "rpm",
128 "version": "3.10.0",
129 ...
130 },
131 ...
132 ],
133 "kernel-tools": [
134 {
135 "name": "kernel-tools",
136 "source": "rpm",
137 "version": "3.10.0",
138 ...
139 }
140 ],
141 ...
142 }
143 }
144 # Sample rpm
145 {
146 "packages": {
147 "kernel": [
148 {
149 "arch": "x86_64",
150 "epoch": null,
151 "name": "kernel",
152 "release": "514.26.2.el7",
153 "source": "rpm",
154 "version": "3.10.0"
155 },
156 {
157 "arch": "x86_64",
158 "epoch": null,
159 "name": "kernel",
160 "release": "514.16.1.el7",
161 "source": "rpm",
162 "version": "3.10.0"
163 },
164 {
165 "arch": "x86_64",
166 "epoch": null,
167 "name": "kernel",
168 "release": "514.10.2.el7",
169 "source": "rpm",
170 "version": "3.10.0"
171 },
172 {
173 "arch": "x86_64",
174 "epoch": null,
175 "name": "kernel",
176 "release": "514.21.1.el7",
177 "source": "rpm",
178 "version": "3.10.0"
179 },
180 {
181 "arch": "x86_64",
182 "epoch": null,
183 "name": "kernel",
184 "release": "693.2.2.el7",
185 "source": "rpm",
186 "version": "3.10.0"
187 }
188 ],
189 "kernel-tools": [
190 {
191 "arch": "x86_64",
192 "epoch": null,
193 "name": "kernel-tools",
194 "release": "693.2.2.el7",
195 "source": "rpm",
196 "version": "3.10.0"
197 }
198 ],
199 "kernel-tools-libs": [
200 {
201 "arch": "x86_64",
202 "epoch": null,
203 "name": "kernel-tools-libs",
204 "release": "693.2.2.el7",
205 "source": "rpm",
206 "version": "3.10.0"
207 }
208 ],
209 }
210 }
211 # Sample deb
212 {
213 "packages": {
214 "libbz2-1.0": [
215 {
216 "version": "1.0.6-5",
217 "source": "apt",
218 "arch": "amd64",
219 "name": "libbz2-1.0"
220 }
221 ],
222 "patch": [
223 {
224 "version": "2.7.1-4ubuntu1",
225 "source": "apt",
226 "arch": "amd64",
227 "name": "patch"
228 }
229 ],
230 }
231 }
232 # Sample pkg_info
233 {
234 "packages": {
235 "curl": [
236 {
237 "name": "curl",
238 "source": "pkg_info",
239 "version": "7.79.0"
240 }
241 ],
242 "intel-firmware": [
243 {
244 "name": "intel-firmware",
245 "source": "pkg_info",
246 "version": "20210608v0"
247 }
248 ],
249 }
250 }
251 """
252
253 import re
254 import json
255
256 from ansible.module_utils.common.text.converters import to_native, to_text
257 from ansible.module_utils.basic import AnsibleModule
258 from ansible.module_utils.common.locale import get_best_parsable_locale
259 from ansible.module_utils.facts.packages import CLIMgr, RespawningLibMgr, get_all_pkg_managers
260
261
262 ALIASES = {
263 'rpm': ['dnf', 'dnf5', 'yum' , 'zypper'],
264 'pkg': ['pkg5', 'pkgng'],
265 'pkg_info': ['openbsd_pkg'],
266 }
267
268
269 class RPM(CLIMgr):
270
271 CLI = 'rpm'
272
273 @staticmethod
274 def _none(v):
275 # When this class used the python3-rpm language bindings,
276 # `None` was converted to `str(None)` during output.
277 # The CLI does this conversion from `None` -> `(none)`,
278 # so this function is used to maintain the previous API output
279 # behavior.
280 return 'None' if v == '(none)' else v
281
282 def list_installed(self):
283 rc, stdout, stderr = module.run_command(
284 ['rpm', '-qa', '--qf', '%{NAME}|%{VERSION}|%{RELEASE}|%{EPOCH}|%{ARCH}\n'],
285 handle_exceptions=False,
286 )
287 if rc != 0:
288 raise Exception("Unable to list packages rc=%s : %s" % (rc, stderr))
289 return stdout.strip().split('\n')
290
291 def get_package_details(self, package):
292 name, version, release, epoch, arch = package.split('|')
293 return {
294 'name': self._none(name),
295 'version': self._none(version),
296 'release': self._none(release),
297 'epoch': self._none(epoch),
298 'arch': self._none(arch),
299 }
300
301
302 class APT(RespawningLibMgr):
303
304 LIB = 'apt'
305 CLI_BINARIES = ['apt', 'apt-get', 'aptitude']
306
307 def __init__(self):
308 self._cache = None
309 super(APT, self).__init__()
310
311 @property
312 def pkg_cache(self):
313 if self._cache is not None:
314 return self._cache
315
316 self._cache = self._lib.Cache()
317 return self._cache
318
319 def list_installed(self):
320 # Store the cache to avoid running pkg_cache() for each item in the comprehension, which is very slow
321 cache = self.pkg_cache
322 return [pk for pk in cache.keys() if cache[pk].is_installed]
323
324 def get_package_details(self, package):
325 ac_pkg = self.pkg_cache[package].installed
326 return dict(name=package, version=ac_pkg.version, arch=ac_pkg.architecture, category=ac_pkg.section, origin=ac_pkg.origins[0].origin)
327
328
329 class PACMAN(CLIMgr):
330
331 CLI = 'pacman'
332
333 def list_installed(self):
334 locale = get_best_parsable_locale(module)
335 rc, out, err = module.run_command([self._cli, '-Qi'], environ_update=dict(LC_ALL=locale), handle_exceptions=False)
336 if rc != 0 or err:
337 raise Exception("Unable to list packages rc=%s : %s" % (rc, err))
338 return out.split("\n\n")[:-1]
339
340 def get_package_details(self, package):
341 # parse values of details that might extend over several lines
342 raw_pkg_details = {}
343 last_detail = None
344 for line in package.splitlines():
345 m = re.match(r"([\w ]*[\w]) +: (.*)", line)
346 if m:
347 last_detail = m.group(1)
348 raw_pkg_details[last_detail] = m.group(2)
349 else:
350 # append value to previous detail
351 raw_pkg_details[last_detail] = raw_pkg_details[last_detail] + " " + line.lstrip()
352
353 provides = None
354 if raw_pkg_details['Provides'] != 'None':
355 provides = [
356 p.split('=')[0]
357 for p in raw_pkg_details['Provides'].split(' ')
358 ]
359
360 return {
361 'name': raw_pkg_details['Name'],
362 'version': raw_pkg_details['Version'],
363 'arch': raw_pkg_details['Architecture'],
364 'provides': provides,
365 }
366
367
368 class PKG(CLIMgr):
369
370 CLI = 'pkg'
371 atoms = ['name', 'version', 'origin', 'installed', 'automatic', 'arch', 'category', 'prefix', 'vital']
372
373 def list_installed(self):
374 rc, out, err = module.run_command([self._cli, 'query', "%%%s" % '\t%'.join(['n', 'v', 'R', 't', 'a', 'q', 'o', 'p', 'V'])], handle_exceptions=False)
375 if rc != 0 or err:
376 raise Exception("Unable to list packages rc=%s : %s" % (rc, err))
377 return out.splitlines()
378
379 def get_package_details(self, package):
380
381 pkg = dict(zip(self.atoms, package.split('\t')))
382
383 if 'arch' in pkg:
384 try:
385 pkg['arch'] = pkg['arch'].split(':')[2]
386 except IndexError:
387 pass
388
389 if 'automatic' in pkg:
390 pkg['automatic'] = bool(int(pkg['automatic']))
391
392 if 'category' in pkg:
393 pkg['category'] = pkg['category'].split('/', 1)[0]
394
395 if 'version' in pkg:
396 if ',' in pkg['version']:
397 pkg['version'], pkg['port_epoch'] = pkg['version'].split(',', 1)
398 else:
399 pkg['port_epoch'] = 0
400
401 if '_' in pkg['version']:
402 pkg['version'], pkg['revision'] = pkg['version'].split('_', 1)
403 else:
404 pkg['revision'] = '0'
405
406 if 'vital' in pkg:
407 pkg['vital'] = bool(int(pkg['vital']))
408
409 return pkg
410
411
412 class PORTAGE(CLIMgr):
413
414 CLI = 'qlist'
415 atoms = ['category', 'name', 'version', 'ebuild_revision', 'slots', 'prefixes', 'sufixes']
416
417 def list_installed(self):
418 rc, out, err = module.run_command(' '.join([self._cli, '-Iv', '|', 'xargs', '-n', '1024', 'qatom']), use_unsafe_shell=True, handle_exceptions=False)
419 if rc != 0:
420 raise RuntimeError("Unable to list packages rc=%s : %s" % (rc, to_native(err)))
421 return out.splitlines()
422
423 def get_package_details(self, package):
424 return dict(zip(self.atoms, package.split()))
425
426
427 class APK(CLIMgr):
428
429 CLI = 'apk'
430
431 def list_installed(self):
432 cmd = [self._cli, 'query', '--installed', '--fields', 'name,version', '--format', 'json', '*']
433 rc, out, err = module.run_command(cmd, handle_exceptions=False)
434 if rc != 0:
435 raise Exception(f"Unable to list packages rc={rc} : {err}")
436 return json.loads(out)
437
438 def get_package_details(self, package):
439 version, release = package.get('version', '').rsplit("-", 1)
440 return {'name': package.get('name', ''), 'version': version, 'release': release}
441
442
443 class PKG_INFO(CLIMgr):
444
445 CLI = 'pkg_info'
446
447 def list_installed(self):
448 rc, out, err = module.run_command([self._cli, '-a'], handle_exceptions=False)
449 if rc != 0 or err:
450 raise Exception("Unable to list packages rc=%s : %s" % (rc, err))
451 return out.splitlines()
452
453 def get_package_details(self, package):
454 raw_pkg_details = {'name': package, 'version': ''}
455 details = package.split(maxsplit=1)[0].rsplit('-', maxsplit=1)
456
457 try:
458 return {
459 'name': details[0],
460 'version': details[1],
461 }
462 except IndexError:
463 return raw_pkg_details
464
465
466 def main():
467
468 # get supported pkg managers
469 PKG_MANAGERS = get_all_pkg_managers()
470 PKG_MANAGER_NAMES = sorted([x.lower() for x in PKG_MANAGERS.keys()])
471 # add aliases
472 PKG_MANAGER_NAMES.extend([alias for alist in ALIASES.values() for alias in alist])
473
474 # start work
475 global module
476
477 # choices are not set for 'manager' as they are computed dynamically and validated below instead of in argspec
478 module = AnsibleModule(argument_spec=dict(manager={'type': 'list', 'elements': 'str', 'default': ['auto']},
479 strategy={'choices': ['first', 'all'], 'default': 'first'}),
480 supports_check_mode=True)
481 packages = {}
482 results = {'ansible_facts': {}}
483 managers = [x.lower() for x in module.params['manager']]
484 strategy = module.params['strategy']
485
486 if 'auto' in managers:
487 # keep order from user, we do dedupe below
488 managers.extend(PKG_MANAGER_NAMES)
489 managers.remove('auto')
490
491 unsupported = set(managers).difference(PKG_MANAGER_NAMES)
492 if unsupported:
493 if 'auto' in module.params['manager']:
494 msg = 'Could not auto detect a usable package manager, check warnings for details.'
495 else:
496 msg = 'Unsupported package managers requested: %s' % (', '.join(unsupported))
497 module.fail_json(msg=msg)
498
499 found = 0
500 seen = set()
501 for pkgmgr in managers:
502
503 if strategy == 'first' and found:
504 break
505
506 # substitute aliases for aliased
507 for aliased in ALIASES.keys():
508 if pkgmgr in ALIASES[aliased]:
509 pkgmgr = aliased
510 break
511
512 # dedupe as per above
513 if pkgmgr in seen:
514 continue
515
516 seen.add(pkgmgr)
517
518 manager = PKG_MANAGERS[pkgmgr]()
519 try:
520 packages_found = {}
521 if manager.is_available(handle_exceptions=False):
522 try:
523 packages_found = manager.get_packages()
524 except Exception as e:
525 module.warn('Failed to retrieve packages with %s: %s' % (pkgmgr, to_text(e)))
526
527 # only consider 'found' if it results in something
528 if packages_found:
529 found += 1
530 for k in packages_found.keys():
531 if k in packages:
532 packages[k].extend(packages_found[k])
533 else:
534 packages[k] = packages_found[k]
535 else:
536 module.warn('Found "%s" but no associated packages' % (pkgmgr))
537
538 except Exception as e:
539 if pkgmgr in module.params['manager']:
540 module.warn('Requested package manager %s was not usable by this module: %s' % (pkgmgr, to_text(e)))
541
542 if found == 0:
543 msg = ('Could not detect a supported package manager from the following list: %s, '
544 'or the required Python library is not installed. Check warnings for details.' % managers)
545 module.fail_json(msg=msg)
546
547 # Set the facts, this will override the facts in ansible_facts that might exist from previous runs
548 # when using operating system level or distribution package managers
549 results['ansible_facts']['packages'] = packages
550
551 module.exit_json(**results)
552
553
554 if __name__ == '__main__':
555 main()