Debian Codegraph @

lib/ansible/modules/apt.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: (c) 2012, Flowroute LLC
4 # Written by Matthew Williams <[email protected]>
5 # Based on yum module written by Seth Vidal <skvidal at fedoraproject.org>
6
7 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
8
9 from __future__ import annotations
10
11
12 DOCUMENTATION = """
13 ---
14 module: apt
15 short_description: Manages apt-packages
16 seealso:
17 - module: ansible.builtin.deb822_repository
18 description:
19 - Manages I(apt) packages (such as for Debian/Ubuntu).
20 version_added: "0.0.2"
21 options:
22 auto_install_module_deps:
23 description:
24 - Automatically install dependencies required to run this module.
25 type: bool
26 default: yes
27 version_added: 2.19
28 name:
29 description:
30 - A list of package names, like V(foo), or package specifier with version, like V(foo=1.0) or V(foo>=1.0).
31 Name wildcards (fnmatch) like V(apt*) and version wildcards like V(foo=1.0*) are also supported.
32 - Do not use single or double quotes around the version when referring to the package name with a specific version, such as V(foo=1.0) or V(foo>=1.0).
33 aliases: [ package, pkg ]
34 type: list
35 elements: str
36 state:
37 description:
38 - Indicates the desired package state. V(latest) ensures that the latest version is installed. V(build-dep) ensures the package build dependencies
39 are installed. V(fixed) attempt to correct a system with broken dependencies in place.
40 type: str
41 default: present
42 choices: [ absent, build-dep, latest, present, fixed ]
43 update_cache:
44 description:
45 - Run the equivalent of C(apt-get update) before the operation. Can be run as part of the package installation or as a separate step.
46 - Default is not to update the cache.
47 aliases: [ update-cache ]
48 type: bool
49 update_cache_retries:
50 description:
51 - Amount of retries if the cache update fails. Also see O(update_cache_retry_max_delay).
52 type: int
53 default: 5
54 version_added: '2.10'
55 update_cache_retry_max_delay:
56 description:
57 - Use an exponential backoff delay for each retry (see O(update_cache_retries)) up to this max delay in seconds.
58 type: int
59 default: 12
60 version_added: '2.10'
61 cache_valid_time:
62 description:
63 - Update the apt cache if it is older than the O(cache_valid_time). This option is set in seconds.
64 - As of Ansible 2.4, if explicitly set, this sets O(update_cache=yes).
65 type: int
66 default: 0
67 purge:
68 description:
69 - Will force purging of configuration files if O(state=absent) or O(autoremove=yes).
70 type: bool
71 default: 'no'
72 default_release:
73 description:
74 - Corresponds to the C(-t) option for I(apt) and sets pin priorities.
75 aliases: [ default-release ]
76 type: str
77 install_recommends:
78 description:
79 - Corresponds to the C(--no-install-recommends) option for C(apt). V(true) installs recommended packages. V(false) does not install
80 recommended packages. By default, Ansible will use the same defaults as the operating system. Suggested packages are never installed.
81 aliases: [ install-recommends ]
82 type: bool
83 force:
84 description:
85 - 'Corresponds to the C(--force-yes) to C(apt-get) and implies O(allow_unauthenticated=yes) and O(allow_downgrade=yes).'
86 - "This option will disable checking both the packages' signatures and the certificates of the web servers they are downloaded from."
87 - 'This option *is not* the equivalent of passing the C(-f) flag to C(apt-get) on the command line.'
88 - '**This is a destructive operation with the potential to destroy your system, and it should almost never be used.**
89 Please also see C(man apt-get) for more information.'
90 type: bool
91 default: 'no'
92 clean:
93 description:
94 - Run the equivalent of C(apt-get clean) to clear out the local repository of retrieved package files. It removes everything but
95 the lock file from C(/var/cache/apt/archives/) and C(/var/cache/apt/archives/partial/).
96 - Can be run as part of the package installation (clean runs before install) or as a separate step.
97 type: bool
98 default: 'no'
99 version_added: "2.13"
100 allow_unauthenticated:
101 description:
102 - Ignore if packages cannot be authenticated. This is useful for bootstrapping environments that manage their own apt-key setup.
103 - 'O(allow_unauthenticated) is only supported with O(state): V(install)/V(present).'
104 aliases: [ allow-unauthenticated ]
105 type: bool
106 default: 'no'
107 version_added: "2.1"
108 allow_downgrade:
109 description:
110 - Corresponds to the C(--allow-downgrades) option for I(apt).
111 - This option enables the named package and version to replace an already installed higher version of that package.
112 - Note that setting O(allow_downgrade=true) can make this module behave in a non-idempotent way.
113 - (The task could end up with a set of packages that does not match the complete list of specified packages to install).
114 - 'O(allow_downgrade) is only supported by C(apt) and will be ignored if C(aptitude) is detected or specified.'
115 aliases: [ allow-downgrade, allow_downgrades, allow-downgrades ]
116 type: bool
117 default: 'no'
118 version_added: "2.12"
119 allow_change_held_packages:
120 description:
121 - Allows changing the version of a package which is on the apt hold list.
122 type: bool
123 default: 'no'
124 version_added: '2.13'
125 upgrade:
126 description:
127 - If yes or safe, performs an aptitude safe-upgrade.
128 - If full, performs an aptitude full-upgrade.
129 - If dist, performs an apt-get dist-upgrade.
130 - 'Note: This does not upgrade a specific package, use state=latest for that.'
131 - 'Note: Since 2.4, apt-get is used as a fall-back if aptitude is not present.'
132 version_added: "1.1"
133 choices: [ dist, full, 'no', safe, 'yes' ]
134 default: 'no'
135 type: str
136 dpkg_options:
137 description:
138 - Add C(dpkg) options to C(apt) command. Defaults to C(-o "Dpkg::Options::=--force-confdef" -o "Dpkg::Options::=--force-confold").
139 - Options should be supplied as comma separated list.
140 default: force-confdef,force-confold
141 type: str
142 deb:
143 description:
144 - Path to a .deb package on the remote machine.
145 - If C(://) in the path, ansible will attempt to download deb before installing. (Version added 2.1)
146 - Requires the C(xz-utils) package to extract the control file of the deb package to install.
147 type: path
148 required: false
149 version_added: "1.6"
150 autoremove:
151 description:
152 - If V(true), remove unused dependency packages for all module states except V(build-dep). It can also be used as the only option.
153 - Previous to version 2.4, O(autoclean) was also an alias for O(autoremove), now it is its own separate command.
154 See documentation for further information.
155 type: bool
156 default: 'no'
157 version_added: "2.1"
158 autoclean:
159 description:
160 - If V(true), cleans the local repository of retrieved package files that can no longer be downloaded.
161 type: bool
162 default: 'no'
163 version_added: "2.4"
164 policy_rc_d:
165 description:
166 - Force the exit code of C(/usr/sbin/policy-rc.d).
167 - For example, if O(policy_rc_d=101) the installed package will not trigger a service start.
168 - If C(/usr/sbin/policy-rc.d) already exists, it is backed up and restored after the package installation.
169 - If V(null), the C(/usr/sbin/policy-rc.d) is not created/changed.
170 type: int
171 default: null
172 version_added: "2.8"
173 only_upgrade:
174 description:
175 - Only upgrade a package if it is already installed.
176 type: bool
177 default: 'no'
178 version_added: "2.1"
179 fail_on_autoremove:
180 description:
181 - 'Corresponds to the C(--no-remove) option for C(apt).'
182 - 'If V(true), it is ensured that no packages will be removed or the task will fail.'
183 - 'O(fail_on_autoremove) is only supported with O(state) except V(absent).'
184 - 'O(fail_on_autoremove) is only supported by C(apt) and will be ignored if C(aptitude) is detected or specified.'
185 type: bool
186 default: 'no'
187 version_added: "2.11"
188 force_apt_get:
189 description:
190 - Force usage of apt-get instead of aptitude.
191 type: bool
192 default: 'no'
193 version_added: "2.4"
194 lock_timeout:
195 description:
196 - How many seconds will this action wait to acquire a lock on the apt db.
197 - Sometimes there is a transitory lock and this will retry at least until timeout is hit.
198 type: int
199 default: 60
200 version_added: "2.12"
201 requirements:
202 - python3-apt
203 - aptitude (before 2.4)
204 author: "Matthew Williams (@mgwilliams)"
205 extends_documentation_fragment: action_common_attributes
206 attributes:
207 check_mode:
208 support: full
209 diff_mode:
210 support: full
211 platform:
212 platforms: debian
213 notes:
214 - Three of the upgrade modes (V(full), V(safe) and its alias V(true)) required C(aptitude) up to 2.3, since 2.4 C(apt-get) is used as a fall-back.
215 - In most cases, packages installed with I(apt) will start newly installed services by default. Most distributions have mechanisms to avoid this.
216 For example when installing Postgresql-9.5 in Debian 9, creating an executable shell script (/usr/sbin/policy-rc.d) that throws
217 a return code of 101 will stop Postgresql 9.5 starting up after install. Remove the file or its execute permission afterward.
218 - The C(apt-get) commandline supports implicit regex matches here but we do not because it can let typos through easier
219 (If you typo C(foo) as C(fo) apt-get would install packages that have "fo" in their name with a warning and a prompt for the user.
220 Since there are no warnings and prompts before installing, we disallow this. Use an explicit fnmatch pattern if you want wildcarding).
221 - When used with a C(loop:) each package will be processed individually, it is much more efficient to pass the list directly to the O(name) option.
222 - When O(default_release) is used, an implicit priority of 990 is used. This is the same behavior as C(apt-get -t).
223 - When an exact version is specified, an implicit priority of 1001 is used.
224 - If the interpreter can't import C(python3-apt) the module will check for it in system-owned interpreters as well.
225 If the dependency can't be found, depending on the value of O(auto_install_module_deps) the module will attempt to install it.
226 If the dependency is found or installed, the module will be respawned under the correct interpreter.
227 - From ansible-core 2.21, if the apt lists directory is absent, the module will recreate it by running C(apt-get update).
228 """
229
230 EXAMPLES = """
231 - name: Install apache httpd (state=present is optional)
232 ansible.builtin.apt:
233 name: apache2
234 state: present
235
236 - name: Update repositories cache and install "foo" package
237 ansible.builtin.apt:
238 name: foo
239 update_cache: yes
240
241 - name: Remove "foo" package
242 ansible.builtin.apt:
243 name: foo
244 state: absent
245
246 - name: Install the package "foo"
247 ansible.builtin.apt:
248 name: foo
249
250 - name: Install a list of packages
251 ansible.builtin.apt:
252 pkg:
253 - foo
254 - foo-tools
255
256 - name: Install the version '1.00' of package "foo"
257 ansible.builtin.apt:
258 name: foo=1.00
259
260 - name: Update the repository cache and update package "nginx" to latest version using default release squeeze-backport
261 ansible.builtin.apt:
262 name: nginx
263 state: latest
264 default_release: squeeze-backports
265 update_cache: yes
266
267 - name: Install the version '1.18.0' of package "nginx" and allow potential downgrades
268 ansible.builtin.apt:
269 name: nginx=1.18.0
270 state: present
271 allow_downgrade: yes
272
273 - name: Install zfsutils-linux with ensuring conflicted packages (e.g. zfs-fuse) will not be removed.
274 ansible.builtin.apt:
275 name: zfsutils-linux
276 state: latest
277 fail_on_autoremove: yes
278
279 - name: Install latest version of "openjdk-6-jdk" ignoring "install-recommends"
280 ansible.builtin.apt:
281 name: openjdk-6-jdk
282 state: latest
283 install_recommends: no
284
285 - name: Update all packages to their latest version
286 ansible.builtin.apt:
287 name: "*"
288 state: latest
289
290 - name: Upgrade the OS (apt-get dist-upgrade)
291 ansible.builtin.apt:
292 upgrade: dist
293
294 - name: Run the equivalent of "apt-get update" as a separate step
295 ansible.builtin.apt:
296 update_cache: yes
297
298 - name: Only run "update_cache=yes" if the last one is more than 3600 seconds ago
299 ansible.builtin.apt:
300 update_cache: yes
301 cache_valid_time: 3600
302
303 - name: Pass options to dpkg on run
304 ansible.builtin.apt:
305 upgrade: dist
306 update_cache: yes
307 dpkg_options: 'force-confold,force-confdef'
308
309 - name: Install a .deb package
310 ansible.builtin.apt:
311 deb: /tmp/mypackage.deb
312
313 - name: Install the build dependencies for package "foo"
314 ansible.builtin.apt:
315 pkg: foo
316 state: build-dep
317
318 - name: Install a .deb package from the internet
319 ansible.builtin.apt:
320 deb: https://example.com/python-ppq_0.1-1_all.deb
321
322 - name: Remove useless packages from the cache
323 ansible.builtin.apt:
324 autoclean: yes
325
326 - name: Remove dependencies that are no longer required
327 ansible.builtin.apt:
328 autoremove: yes
329
330 - name: Remove dependencies that are no longer required and purge their configuration files
331 ansible.builtin.apt:
332 autoremove: yes
333 purge: true
334
335 - name: Run the equivalent of "apt-get clean" as a separate step
336 ansible.builtin.apt:
337 clean: yes
338 """
339
340 RETURN = """
341 cache_updated:
342 description: if the cache was updated or not
343 returned: success, in some cases
344 type: bool
345 sample: True
346 cache_update_time:
347 description: time of the last cache update (0 if unknown)
348 returned: success, in some cases
349 type: int
350 sample: 1425828348000
351 stdout:
352 description: output from apt
353 returned: success, when needed
354 type: str
355 sample: |-
356 Reading package lists...
357 Building dependency tree...
358 Reading state information...
359 The following extra packages will be installed:
360 apache2-bin ...
361 stderr:
362 description: error output from apt
363 returned: success, when needed
364 type: str
365 sample: "AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to ..."
366 """ # NOQA
367
368 # added to stave off future warnings about apt api
369 import warnings
370 warnings.filterwarnings('ignore', "apt API not stable yet", FutureWarning)
371
372 import datetime
373 import fnmatch
374 import locale as locale_module
375 import os
376 import re
377 import secrets
378 import shlex
379 import shutil
380 import sys
381 import tempfile
382 import time
383
384 from ansible.module_utils.basic import AnsibleModule
385 from ansible.module_utils.common.file import S_IRWXU_RXG_RXO
386 from ansible.module_utils.common.locale import get_best_parsable_locale
387 from ansible.module_utils.common.respawn import has_respawned, probe_interpreters_for_module, respawn_module
388 from ansible.module_utils.common.text.converters import to_native, to_text
389 from ansible.module_utils.urls import fetch_file
390
391 DPKG_OPTIONS = 'force-confdef,force-confold'
392 APT_GET_ZERO = "\n0 upgraded, 0 newly installed, 0 to remove"
393 APTITUDE_ZERO = "\n0 packages upgraded, 0 newly installed, 0 to remove"
394 APT_LISTS_PATH = "/var/lib/apt/lists"
395 APT_UPDATE_SUCCESS_STAMP_PATH = "/var/lib/apt/periodic/update-success-stamp"
396
397 CLEAN_OP_CHANGED_STR = dict(
398 autoremove='The following packages will be REMOVED',
399 # "Del python3-q 2.4-1 [24 kB]"
400 autoclean='Del ',
401 )
402
403
404 HAS_PYTHON_APT = False
405 try:
406 import apt
407 import apt.debfile
408 import apt_pkg
409 HAS_PYTHON_APT = True
410 except ImportError:
411 apt = apt_pkg = None
412
413
414 class PolicyRcD(object):
415 """
416 This class is a context manager for the /usr/sbin/policy-rc.d file.
417 It allow the user to prevent dpkg to start the corresponding service when installing
418 a package.
419 https://people.debian.org/~hmh/invokerc.d-policyrc.d-specification.txt
420 """
421
422 def __init__(self, module):
423 # we need the module for later use (eg. fail_json)
424 self.m = module
425
426 # if policy_rc_d is null then we don't need to modify policy-rc.d
427 if self.m.params['policy_rc_d'] is None:
428 return
429
430 # if the /usr/sbin/policy-rc.d already exists
431 # we will back it up during package installation
432 # then restore it
433 if os.path.exists('/usr/sbin/policy-rc.d'):
434 self.backup_dir = tempfile.mkdtemp(prefix="ansible")
435 else:
436 self.backup_dir = None
437
438 def __enter__(self):
439 """
440 This method will be called when we enter the context, before we call `apt-get …`
441 """
442
443 # if policy_rc_d is null then we don't need to modify policy-rc.d
444 if self.m.params['policy_rc_d'] is None:
445 return
446
447 # if the /usr/sbin/policy-rc.d already exists we back it up
448 if self.backup_dir:
449 try:
450 shutil.move('/usr/sbin/policy-rc.d', self.backup_dir)
451 except Exception:
452 self.m.fail_json(msg="Fail to move /usr/sbin/policy-rc.d to %s" % self.backup_dir)
453
454 # we write /usr/sbin/policy-rc.d so it always exits with code policy_rc_d
455 try:
456 with open('/usr/sbin/policy-rc.d', 'w') as policy_rc_d:
457 policy_rc_d.write('#!/bin/sh\nexit %d\n' % self.m.params['policy_rc_d'])
458
459 os.chmod('/usr/sbin/policy-rc.d', S_IRWXU_RXG_RXO)
460 except Exception:
461 self.m.fail_json(msg="Failed to create or chmod /usr/sbin/policy-rc.d")
462
463 def __exit__(self, type, value, traceback):
464 """
465 This method will be called when we exit the context, after `apt-get …` is done
466 """
467
468 # if policy_rc_d is null then we don't need to modify policy-rc.d
469 if self.m.params['policy_rc_d'] is None:
470 return
471
472 if self.backup_dir:
473 # if /usr/sbin/policy-rc.d already exists before the call to __enter__
474 # we restore it (from the backup done in __enter__)
475 try:
476 shutil.move(os.path.join(self.backup_dir, 'policy-rc.d'),
477 '/usr/sbin/policy-rc.d')
478 os.rmdir(self.backup_dir)
479 except Exception:
480 self.m.fail_json(msg="Fail to move back %s to /usr/sbin/policy-rc.d"
481 % os.path.join(self.backup_dir, 'policy-rc.d'))
482 else:
483 # if there wasn't a /usr/sbin/policy-rc.d file before the call to __enter__
484 # we just remove the file
485 try:
486 os.remove('/usr/sbin/policy-rc.d')
487 except Exception:
488 self.m.fail_json(msg="Fail to remove /usr/sbin/policy-rc.d (after package manipulation)")
489
490
491 def package_split(pkgspec):
492 parts = re.split(r'(>?=)', pkgspec, maxsplit=1)
493 if len(parts) > 1:
494 return parts
495 return parts[0], None, None
496
497
498 def package_version_compare(version, other_version):
499 try:
500 return apt_pkg.version_compare(version, other_version)
501 except AttributeError:
502 return apt_pkg.VersionCompare(version, other_version)
503
504
505 def package_best_match(pkgname, version_cmp, version, release, cache):
506 policy = apt_pkg.Policy(cache)
507
508 policy.read_pinfile(apt_pkg.config.find_file("Dir::Etc::preferences"))
509 policy.read_pindir(apt_pkg.config.find_file("Dir::Etc::preferencesparts"))
510
511 if release:
512 # 990 is the priority used in `apt-get -t`
513 policy.create_pin('Release', pkgname, release, 990)
514 if version_cmp == "=":
515 # Installing a specific version from command line overrides all pinning
516 # We don't mimic this exactly, but instead set a priority which is higher than all APT built-in pin priorities.
517 policy.create_pin('Version', pkgname, version, 1001)
518 pkg = cache[pkgname]
519 pkgver = policy.get_candidate_ver(pkg)
520 if not pkgver:
521 return None
522 # Check if the available version matches the requested version
523 if version_cmp == "=" and not fnmatch.fnmatch(pkgver.ver_str, version):
524 # Even though we put in a pin policy, it can be ignored if there is no
525 # possible candidate.
526 return None
527 if version_cmp == ">=" and not apt_pkg.version_compare(pkgver.ver_str, version) >= 0:
528 return None
529 return pkgver.ver_str
530
531
532 def package_status(m, pkgname, version_cmp, version, default_release, cache, state):
533 """
534 :return: A tuple of (installed, installed_version, version_installable, has_files). *installed* indicates whether
535 the package (regardless of version) is installed. *installed_version* indicates whether the installed package
536 matches the provided version criteria. *version_installable* provides the latest matching version that can be
537 installed. In the case of virtual packages where we can't determine an applicable match, True is returned.
538 *has_files* indicates whether the package has files on the filesystem (even if not installed, meaning a purge is
539 required).
540 """
541 try:
542 # get the package from the cache, as well as the
543 # low-level apt_pkg.Package object which contains
544 # state fields not directly accessible from the
545 # higher-level apt.package.Package object.
546 pkg = cache[pkgname]
547 ll_pkg = cache._cache[pkgname] # the low-level package object
548 except KeyError:
549 if state == 'install':
550 try:
551 provided_packages = cache.get_providing_packages(pkgname)
552 if provided_packages:
553 # When this is a virtual package satisfied by only
554 # one installed package, return the status of the target
555 # package to avoid requesting re-install
556 if cache.is_virtual_package(pkgname) and len(provided_packages) == 1:
557 package = provided_packages[0]
558 installed, installed_version, version_installable, has_files = \
559 package_status(m, package.name, version_cmp, version, default_release, cache, state='install')
560 if installed:
561 return installed, installed_version, version_installable, has_files
562
563 # Otherwise return nothing so apt will sort out
564 # what package to satisfy this with
565 return False, False, True, False
566
567 m.fail_json(msg="No package matching '%s' is available" % pkgname)
568 except AttributeError:
569 # python-apt version too old to detect virtual packages
570 # mark as not installed and let apt-get install deal with it
571 return False, False, True, False
572 else:
573 return False, False, None, False
574 try:
575 has_files = len(pkg.installed_files) > 0
576 except UnicodeDecodeError:
577 has_files = True
578 except AttributeError:
579 has_files = False # older python-apt cannot be used to determine non-purged
580
581 try:
582 package_is_installed = ll_pkg.current_state == apt_pkg.CURSTATE_INSTALLED
583 except AttributeError: # python-apt 0.7.X has very weak low-level object
584 try:
585 # might not be necessary as python-apt post-0.7.X should have current_state property
586 package_is_installed = pkg.is_installed
587 except AttributeError:
588 # assume older version of python-apt is installed
589 package_is_installed = pkg.isInstalled
590
591 version_best = package_best_match(pkgname, version_cmp, version, default_release, cache._cache)
592 version_is_installed = False
593 version_installable = None
594 if package_is_installed:
595 try:
596 installed_version = pkg.installed.version
597 except AttributeError:
598 installed_version = pkg.installedVersion
599
600 # Check if the installed version already matches the requested version
601 if version_cmp == "=":
602 version_is_installed = fnmatch.fnmatch(installed_version, version)
603 elif version_cmp == ">=":
604 version_is_installed = apt_pkg.version_compare(installed_version, version) >= 0
605 else:
606 version_is_installed = True
607
608 # Check if a better version is available
609 if version_best and installed_version != version_best:
610 version_installable = version_best
611 else:
612 version_installable = version_best
613
614 return package_is_installed, version_is_installed, version_installable, has_files
615
616
617 def expand_dpkg_options(dpkg_options_compressed):
618 options_list = dpkg_options_compressed.split(',')
619 dpkg_options = ""
620 for dpkg_option in options_list:
621 dpkg_options = '%s -o "Dpkg::Options::=--%s"' \
622 % (dpkg_options, dpkg_option)
623 return dpkg_options.strip()
624
625
626 def expand_pkgspec_from_fnmatches(m, pkgspec, cache):
627 # Note: apt-get does implicit regex matching when an exact package name
628 # match is not found. Something like this:
629 # matches = [pkg.name for pkg in cache if re.match(pkgspec, pkg.name)]
630 # (Should also deal with the ':' for multiarch like the fnmatch code below)
631 #
632 # We have decided not to do similar implicit regex matching but might take
633 # a PR to add some sort of explicit regex matching:
634 # https://github.com/ansible/ansible-modules-core/issues/1258
635 new_pkgspec = []
636 if pkgspec:
637 for pkgspec_pattern in pkgspec:
638
639 if not isinstance(pkgspec_pattern, str):
640 m.fail_json(msg="Invalid type for package name, expected string but got %s" % type(pkgspec_pattern))
641
642 pkgname_pattern, version_cmp, version = package_split(pkgspec_pattern)
643
644 # note that none of these chars is allowed in a (debian) pkgname
645 if frozenset('*?[]!').intersection(pkgname_pattern):
646 # handle multiarch pkgnames, the idea is that "apt*" should
647 # only select native packages. But "apt*:i386" should still work
648 if ":" not in pkgname_pattern:
649 # Filter the multiarch packages from the cache only once
650 try:
651 pkg_name_cache = _non_multiarch # pylint: disable=used-before-assignment
652 except NameError:
653 pkg_name_cache = _non_multiarch = [pkg.name for pkg in cache if ':' not in pkg.name] # noqa: F841
654 else:
655 # Create a cache of pkg_names including multiarch only once
656 try:
657 pkg_name_cache = _all_pkg_names # pylint: disable=used-before-assignment
658 except NameError:
659 pkg_name_cache = _all_pkg_names = [pkg.name for pkg in cache] # noqa: F841
660
661 matches = fnmatch.filter(pkg_name_cache, pkgname_pattern)
662
663 if not matches:
664 m.fail_json(msg="No package(s) matching '%s' available" % to_text(pkgname_pattern))
665 else:
666 new_pkgspec.extend(matches)
667 else:
668 # No wildcards in name
669 new_pkgspec.append(pkgspec_pattern)
670 return new_pkgspec
671
672
673 def parse_diff(output):
674 diff = to_native(output).splitlines()
675 try:
676 # check for start marker from aptitude
677 diff_start = diff.index('Resolving dependencies...')
678 except ValueError:
679 try:
680 # check for start marker from apt-get
681 diff_start = diff.index('Reading state information...')
682 except ValueError:
683 # show everything
684 diff_start = -1
685 try:
686 # check for end marker line from both apt-get and aptitude
687 diff_end = next(i for i, item in enumerate(diff) if re.match('[0-9]+ (packages )?upgraded', item))
688 except StopIteration:
689 diff_end = len(diff)
690 diff_start += 1
691 diff_end += 1
692 return {'prepared': '\n'.join(diff[diff_start:diff_end])}
693
694
695 def mark_installed(m: AnsibleModule, packages: list[str], manual: bool) -> None:
696 """Mark packages as manually or automatically installed."""
697 if not packages:
698 return
699
700 if manual:
701 mark_msg = "manually"
702 mark_op = "manual"
703 else:
704 mark_msg = "auto"
705 mark_op = "auto"
706
707 apt_mark_cmd_path = m.get_bin_path("apt-mark")
708
709 # https://github.com/ansible/ansible/issues/40531
710 if apt_mark_cmd_path is None:
711 m.warn(f"Could not find apt-mark binary, not marking package(s) as {mark_msg} installed.")
712 return
713
714 cmd = [apt_mark_cmd_path, mark_op] + packages
715 rc, out, err = m.run_command(cmd)
716
717 if rc != 0:
718 m.fail_json(msg=f"Command {shlex.join(cmd)!r} failed.", stdout=out, stderr=err, rc=rc)
719
720
721 def install(m, pkgspec, cache, upgrade=False, default_release=None,
722 install_recommends=None, force=False,
723 dpkg_options=expand_dpkg_options(DPKG_OPTIONS),
724 build_dep=False, fixed=False, autoremove=False, fail_on_autoremove=False, only_upgrade=False,
725 allow_unauthenticated=False, allow_downgrade=False, allow_change_held_packages=False):
726 pkg_list = []
727 packages = ""
728 pkgspec = expand_pkgspec_from_fnmatches(m, pkgspec, cache)
729 package_names = []
730 for package in pkgspec:
731 if build_dep:
732 # Let apt decide what to install
733 pkg_list.append("'%s'" % package)
734 continue
735
736 name, version_cmp, version = package_split(package)
737 package_names.append(name)
738 installed, installed_version, version_installable, has_files = package_status(m, name, version_cmp, version, default_release, cache, state='install')
739
740 if not installed and only_upgrade:
741 # only_upgrade upgrades packages that are already installed
742 # since this package is not installed, skip it
743 continue
744
745 if not installed_version and not version_installable:
746 status = False
747 data = dict(msg="no available installation candidate for %s" % package)
748 return (status, data)
749
750 if version_installable and ((not installed and not only_upgrade) or upgrade or not installed_version):
751 if version_installable is not True:
752 pkg_list.append("'%s=%s'" % (name, version_installable))
753 elif version:
754 pkg_list.append("'%s=%s'" % (name, version))
755 else:
756 pkg_list.append("'%s'" % name)
757 elif installed_version and version_installable and version_cmp == "=":
758 # This happens when the package is installed, a newer version is
759 # available, and the version is a wildcard that matches both
760 #
761 # This is legacy behavior, and isn't documented (in fact it does
762 # things documentations says it shouldn't). It should not be relied
763 # upon.
764 pkg_list.append("'%s=%s'" % (name, version))
765 packages = ' '.join(pkg_list)
766
767 if packages:
768 if force:
769 force_yes = '--force-yes'
770 else:
771 force_yes = ''
772
773 if m.check_mode:
774 check_arg = '--simulate'
775 else:
776 check_arg = ''
777
778 if autoremove:
779 autoremove = '--auto-remove'
780 else:
781 autoremove = ''
782
783 if fail_on_autoremove:
784 fail_on_autoremove = '--no-remove'
785 else:
786 fail_on_autoremove = ''
787
788 if only_upgrade:
789 only_upgrade = '--only-upgrade'
790 else:
791 only_upgrade = ''
792
793 if fixed:
794 fixed = '--fix-broken'
795 else:
796 fixed = ''
797
798 if build_dep:
799 cmd = "%s -y %s %s %s %s %s %s build-dep %s" % (APT_GET_CMD, dpkg_options, only_upgrade, fixed, force_yes, fail_on_autoremove, check_arg, packages)
800 else:
801 cmd = "%s -y %s %s %s %s %s %s %s install %s" % \
802 (APT_GET_CMD, dpkg_options, only_upgrade, fixed, force_yes, autoremove, fail_on_autoremove, check_arg, packages)
803
804 if default_release:
805 cmd += " -t '%s'" % (default_release,)
806
807 if install_recommends is False:
808 cmd += " -o APT::Install-Recommends=no"
809 elif install_recommends is True:
810 cmd += " -o APT::Install-Recommends=yes"
811 # install_recommends is None uses the OS default
812
813 if allow_unauthenticated:
814 cmd += " --allow-unauthenticated"
815
816 if allow_downgrade:
817 cmd += " --allow-downgrades"
818
819 if allow_change_held_packages:
820 cmd += " --allow-change-held-packages"
821
822 with PolicyRcD(m):
823 rc, out, err = m.run_command(cmd)
824
825 if m._diff:
826 diff = parse_diff(out)
827 else:
828 diff = {}
829 status = True
830
831 changed = True
832 if build_dep:
833 changed = APT_GET_ZERO not in out
834
835 data = dict(changed=changed, stdout=out, stderr=err, diff=diff)
836 if rc:
837 status = False
838 data = dict(msg="'%s' failed: %s" % (cmd, err), stdout=out, stderr=err, rc=rc)
839 else:
840 status = True
841 data = dict(changed=False)
842
843 if not build_dep and not m.check_mode:
844 mark_installed(m, package_names, manual=True)
845
846 return (status, data)
847
848
849 def get_field_of_deb(m, deb_file, field="Version"):
850 cmd_dpkg = m.get_bin_path("dpkg", True)
851 cmd = cmd_dpkg + " --field %s %s" % (deb_file, field)
852 rc, stdout, stderr = m.run_command(cmd)
853 if rc != 0:
854 m.fail_json(msg="%s failed" % cmd, stdout=stdout, stderr=stderr)
855 return to_native(stdout).strip('\n')
856
857
858 def install_recommended_packages(cache: apt.Cache, recommended_packages: str) -> list[str]:
859 deps_to_install = []
860 for recommend_one_of in apt_pkg.parse_depends(recommended_packages, False):
861 for name, version, op in recommend_one_of:
862 try:
863 pkg = cache[name]
864 except KeyError:
865 # no package found, continue with next recommended package
866 continue
867
868 if pkg.is_installed and version and op and apt_pkg.check_dep(pkg.installed.version, op, version):
869 # package is installed and the version is the same, continue with next recommended package
870 break
871
872 if not pkg.candidate:
873 # no candidate found, continue with next recommended package
874 continue
875
876 if version and op and not apt_pkg.check_dep(pkg.candidate.version, op, version):
877 # candidate version does not match the version, continue with next recommended package
878 continue
879
880 deps_to_install.append(name)
881 break
882 return deps_to_install
883
884
885 def install_deb(
886 m, debs, cache, force, fail_on_autoremove, install_recommends,
887 allow_unauthenticated,
888 allow_downgrade,
889 allow_change_held_packages,
890 dpkg_options,
891 lock_timeout,
892 ):
893 changed = False
894 deps_to_install = []
895 pkgs_to_install = []
896 for deb_file in debs.split(','):
897 try:
898 pkg = apt.debfile.DebPackage(deb_file, cache=apt.Cache())
899 pkg_name = get_field_of_deb(m, deb_file, "Package")
900 pkg_version = get_field_of_deb(m, deb_file, "Version")
901 if hasattr(apt_pkg, 'get_architectures') and len(apt_pkg.get_architectures()) > 1:
902 pkg_arch = get_field_of_deb(m, deb_file, "Architecture")
903 pkg_key = "%s:%s" % (pkg_name, pkg_arch)
904 else:
905 pkg_key = pkg_name
906 try:
907 installed_pkg = apt.Cache()[pkg_key]
908 installed_version = installed_pkg.installed.version
909 if package_version_compare(pkg_version, installed_version) == 0:
910 # Does not need to down-/upgrade, move on to next package
911 continue
912 except Exception:
913 # Must not be installed, continue with installation
914 pass
915 # Check if package is installable
916 if not pkg.check():
917 if force or ("later version" in pkg._failure_string and allow_downgrade):
918 pass
919 else:
920 m.fail_json(msg=pkg._failure_string)
921
922 # add any missing deps to the list of deps we need
923 # to install so they're all done in one shot
924 deps_to_install.extend(pkg.missing_deps)
925
926 except Exception as e:
927 m.fail_json(msg="Unable to install package: %s" % to_native(e))
928
929 # Install 'Recommends' of this deb file
930 if install_recommends:
931 pkg_recommends = get_field_of_deb(m, deb_file, "Recommends")
932 deps_to_install.extend(install_recommended_packages(cache, pkg_recommends))
933
934 # and add this deb to the list of packages to install
935 pkgs_to_install.append(deb_file)
936
937 # install the deps through apt
938 retvals = {}
939 if deps_to_install:
940 install_dpkg_options = f"{expand_dpkg_options(dpkg_options)} -o DPkg::Lock::Timeout={lock_timeout}"
941 (success, retvals) = install(m=m, pkgspec=deps_to_install, cache=cache,
942 install_recommends=install_recommends,
943 fail_on_autoremove=fail_on_autoremove,
944 allow_unauthenticated=allow_unauthenticated,
945 allow_downgrade=allow_downgrade,
946 allow_change_held_packages=allow_change_held_packages,
947 dpkg_options=install_dpkg_options)
948 if not success:
949 m.fail_json(**retvals)
950 # Mark the dependencies as auto installed
951 # https://github.com/ansible/ansible/issues/78123
952 mark_installed(m, deps_to_install, manual=False)
953 changed = retvals.get('changed', False)
954
955 if pkgs_to_install:
956 options = ' '.join(["--%s" % x for x in dpkg_options.split(",")])
957 if m.check_mode:
958 options += " --simulate"
959 if force:
960 options += " --force-all"
961
962 cmd = "dpkg %s -i %s" % (options, " ".join(pkgs_to_install))
963
964 with PolicyRcD(m):
965 rc, out, err = m.run_command(cmd)
966
967 if "stdout" in retvals:
968 stdout = retvals["stdout"] + out
969 else:
970 stdout = out
971 if "diff" in retvals:
972 diff = retvals["diff"]
973 if 'prepared' in diff:
974 diff['prepared'] += '\n\n' + out
975 else:
976 diff = parse_diff(out)
977 if "stderr" in retvals:
978 stderr = retvals["stderr"] + err
979 else:
980 stderr = err
981
982 if rc == 0:
983 m.exit_json(changed=True, stdout=stdout, stderr=stderr, diff=diff)
984 else:
985 m.fail_json(msg="%s failed" % cmd, stdout=stdout, stderr=stderr)
986 else:
987 m.exit_json(changed=changed, stdout=retvals.get('stdout', ''), stderr=retvals.get('stderr', ''), diff=retvals.get('diff', ''))
988
989
990 def remove(m, pkgspec, cache, purge=False, force=False,
991 dpkg_options=expand_dpkg_options(DPKG_OPTIONS), autoremove=False,
992 allow_change_held_packages=False):
993 pkg_list = []
994 pkgspec = expand_pkgspec_from_fnmatches(m, pkgspec, cache)
995 for package in pkgspec:
996 name, version_cmp, version = package_split(package)
997 installed, installed_version, upgradable, has_files = package_status(m, name, version_cmp, version, None, cache, state='remove')
998 if installed_version or (has_files and purge):
999 pkg_list.append("'%s'" % package)
1000 packages = ' '.join(pkg_list)
1001
1002 if not packages:
1003 m.exit_json(changed=False)
1004 else:
1005 if force:
1006 force_yes = '--force-yes'
1007 else:
1008 force_yes = ''
1009
1010 if purge:
1011 purge = '--purge'
1012 else:
1013 purge = ''
1014
1015 if autoremove:
1016 autoremove = '--auto-remove'
1017 else:
1018 autoremove = ''
1019
1020 if m.check_mode:
1021 check_arg = '--simulate'
1022 else:
1023 check_arg = ''
1024
1025 if allow_change_held_packages:
1026 allow_change_held_packages = '--allow-change-held-packages'
1027 else:
1028 allow_change_held_packages = ''
1029
1030 cmd = "%s -q -y %s %s %s %s %s %s remove %s" % (
1031 APT_GET_CMD,
1032 dpkg_options,
1033 purge,
1034 force_yes,
1035 autoremove,
1036 check_arg,
1037 allow_change_held_packages,
1038 packages
1039 )
1040
1041 with PolicyRcD(m):
1042 rc, out, err = m.run_command(cmd)
1043
1044 if m._diff:
1045 diff = parse_diff(out)
1046 else:
1047 diff = {}
1048 if rc:
1049 m.fail_json(msg="'apt-get remove %s' failed: %s" % (packages, err), stdout=out, stderr=err, rc=rc)
1050 m.exit_json(changed=True, stdout=out, stderr=err, diff=diff)
1051
1052
1053 def cleanup(m, purge=False, force=False, operation=None,
1054 dpkg_options=expand_dpkg_options(DPKG_OPTIONS)):
1055
1056 if operation not in frozenset(['autoremove', 'autoclean']):
1057 raise AssertionError('Expected "autoremove" or "autoclean" cleanup operation, got %s' % operation)
1058
1059 if force:
1060 force_yes = '--force-yes'
1061 else:
1062 force_yes = ''
1063
1064 if purge:
1065 purge = '--purge'
1066 else:
1067 purge = ''
1068
1069 if m.check_mode:
1070 check_arg = '--simulate'
1071 else:
1072 check_arg = ''
1073
1074 cmd = "%s -y %s %s %s %s %s" % (APT_GET_CMD, dpkg_options, purge, force_yes, operation, check_arg)
1075
1076 with PolicyRcD(m):
1077 rc, out, err = m.run_command(cmd)
1078
1079 if m._diff:
1080 diff = parse_diff(out)
1081 else:
1082 diff = {}
1083 if rc:
1084 m.fail_json(msg="'apt-get %s' failed: %s" % (operation, err), stdout=out, stderr=err, rc=rc)
1085
1086 changed = CLEAN_OP_CHANGED_STR[operation] in out
1087
1088 m.exit_json(changed=changed, stdout=out, stderr=err, diff=diff)
1089
1090
1091 def aptclean(m):
1092 clean_rc, clean_out, clean_err = m.run_command(['apt-get', 'clean'])
1093 clean_diff = parse_diff(clean_out) if m._diff else {}
1094
1095 if clean_rc:
1096 m.fail_json(msg="apt-get clean failed", stdout=clean_out, rc=clean_rc)
1097 if clean_err:
1098 m.fail_json(msg="apt-get clean failed: %s" % clean_err, stdout=clean_out, rc=clean_rc)
1099 return (clean_out, clean_err, clean_diff)
1100
1101
1102 def upgrade(m, mode="yes", force=False, default_release=None,
1103 use_apt_get=False,
1104 dpkg_options=expand_dpkg_options(DPKG_OPTIONS), autoremove=False, fail_on_autoremove=False,
1105 allow_unauthenticated=False,
1106 allow_downgrade=False,
1107 ):
1108
1109 if autoremove:
1110 autoremove = '--auto-remove'
1111 else:
1112 autoremove = ''
1113
1114 if m.check_mode:
1115 check_arg = '--simulate'
1116 else:
1117 check_arg = ''
1118
1119 apt_cmd = None
1120 prompt_regex = None
1121 if mode == "dist" or (mode == "full" and use_apt_get):
1122 # apt-get dist-upgrade
1123 apt_cmd = APT_GET_CMD
1124 upgrade_command = "dist-upgrade %s" % (autoremove)
1125 elif mode == "full" and not use_apt_get:
1126 # aptitude full-upgrade
1127 apt_cmd = APTITUDE_CMD
1128 upgrade_command = "full-upgrade"
1129 else:
1130 if use_apt_get:
1131 apt_cmd = APT_GET_CMD
1132 upgrade_command = "upgrade --with-new-pkgs %s" % (autoremove)
1133 else:
1134 # aptitude safe-upgrade # mode=yes # default
1135 apt_cmd = APTITUDE_CMD
1136 upgrade_command = "safe-upgrade"
1137 prompt_regex = r"(^Do you want to ignore this warning and proceed anyway\?|^\*\*\*.*\[default=.*\])"
1138
1139 if force:
1140 if apt_cmd == APT_GET_CMD:
1141 force_yes = '--force-yes'
1142 else:
1143 force_yes = '--assume-yes --allow-untrusted'
1144 else:
1145 force_yes = ''
1146
1147 if fail_on_autoremove:
1148 if apt_cmd == APT_GET_CMD:
1149 fail_on_autoremove = '--no-remove'
1150 else:
1151 m.warn("APTITUDE does not support '--no-remove', ignoring the 'fail_on_autoremove' parameter.")
1152 fail_on_autoremove = ''
1153 else:
1154 fail_on_autoremove = ''
1155
1156 allow_unauthenticated = '--allow-unauthenticated' if allow_unauthenticated else ''
1157
1158 if allow_downgrade:
1159 if apt_cmd == APT_GET_CMD:
1160 allow_downgrade = '--allow-downgrades'
1161 else:
1162 m.warn("APTITUDE does not support '--allow-downgrades', ignoring the 'allow_downgrade' parameter.")
1163 allow_downgrade = ''
1164 else:
1165 allow_downgrade = ''
1166
1167 if apt_cmd is None:
1168 if use_apt_get:
1169 apt_cmd = APT_GET_CMD
1170 else:
1171 m.fail_json(msg="Unable to find APTITUDE in path. Please make sure "
1172 "to have APTITUDE in path or use 'force_apt_get=True'")
1173 apt_cmd_path = m.get_bin_path(apt_cmd, required=True)
1174
1175 cmd = '%s -y %s %s %s %s %s %s %s' % (
1176 apt_cmd_path,
1177 dpkg_options,
1178 force_yes,
1179 fail_on_autoremove,
1180 allow_unauthenticated,
1181 allow_downgrade,
1182 check_arg,
1183 upgrade_command,
1184 )
1185
1186 if default_release:
1187 cmd += " -t '%s'" % (default_release,)
1188
1189 with PolicyRcD(m):
1190 rc, out, err = m.run_command(cmd, prompt_regex=prompt_regex)
1191
1192 if m._diff:
1193 diff = parse_diff(out)
1194 else:
1195 diff = {}
1196 if rc:
1197 m.fail_json(msg="'%s %s' failed: %s" % (apt_cmd, upgrade_command, err), stdout=out, rc=rc)
1198 if (apt_cmd == APT_GET_CMD and APT_GET_ZERO in out) or (apt_cmd == APTITUDE_CMD and APTITUDE_ZERO in out):
1199 m.exit_json(changed=False, msg=out, stdout=out, stderr=err)
1200 m.exit_json(changed=True, msg=out, stdout=out, stderr=err, diff=diff)
1201
1202
1203 def get_cache_mtime():
1204 """Return mtime of a valid apt cache file.
1205 Stat the apt cache file and if no cache file is found return 0
1206 :returns: ``int``
1207 """
1208 cache_time = 0
1209 if os.path.exists(APT_UPDATE_SUCCESS_STAMP_PATH):
1210 cache_time = os.stat(APT_UPDATE_SUCCESS_STAMP_PATH).st_mtime
1211 elif os.path.exists(APT_LISTS_PATH):
1212 cache_time = os.stat(APT_LISTS_PATH).st_mtime
1213 return cache_time
1214
1215
1216 def get_updated_cache_time():
1217 """Return the mtime time stamp and the updated cache time.
1218 Always retrieve the mtime of the apt cache or set the `cache_mtime`
1219 variable to 0
1220 :returns: ``tuple``
1221 """
1222 cache_mtime = get_cache_mtime()
1223 mtimestamp = datetime.datetime.fromtimestamp(cache_mtime)
1224 updated_cache_time = int(time.mktime(mtimestamp.timetuple()))
1225 return mtimestamp, updated_cache_time
1226
1227
1228 def recreate_cache(module, max_retries=2):
1229 retries = 0
1230 update_cmd = ['apt-get', 'update', '-q']
1231 while retries < max_retries:
1232 rc, stdout, stderr = module.run_command(update_cmd)
1233 retries += 1
1234 if rc == 0:
1235 break
1236 return rc, stdout, stderr
1237
1238
1239 # https://github.com/ansible/ansible-modules-core/issues/2951
1240 def get_cache(module):
1241 """Attempt to get the cache object and update till it works"""
1242 cache = None
1243 try:
1244 cache = apt.Cache()
1245 except SystemError as e:
1246 if '/var/lib/apt/lists/' in to_native(e).lower():
1247 # update cache until files are fixed or retries exceeded
1248 rc, stdout, stderr = recreate_cache(module)
1249 if rc != 0:
1250 module.fail_json(msg=f'Updating the cache to correct corrupt package lists failed:\n{to_native(e)}\n{stdout + stderr}', rc=rc)
1251 # try again
1252 cache = apt.Cache()
1253 else:
1254 module.fail_json(msg=to_native(e))
1255
1256 # Check if the cache is valid
1257 if not os.path.isdir(apt_pkg.config.find_dir("Dir::State::Lists")):
1258 rc, stdout, stderr = recreate_cache(module)
1259 if rc != 0:
1260 module.fail_json(msg=f'Failed to recreate the cache: {stdout + stderr}', rc=rc)
1261 cache = apt.Cache()
1262 return cache
1263
1264
1265 def main():
1266 module = AnsibleModule(
1267 argument_spec=dict(
1268 state=dict(type='str', default='present', choices=['absent', 'build-dep', 'fixed', 'latest', 'present']),
1269 update_cache=dict(type='bool', aliases=['update-cache']),
1270 update_cache_retries=dict(type='int', default=5),
1271 update_cache_retry_max_delay=dict(type='int', default=12),
1272 cache_valid_time=dict(type='int', default=0),
1273 purge=dict(type='bool', default=False),
1274 package=dict(type='list', elements='str', aliases=['pkg', 'name']),
1275 deb=dict(type='path'),
1276 default_release=dict(type='str', aliases=['default-release']),
1277 install_recommends=dict(type='bool', aliases=['install-recommends']),
1278 force=dict(type='bool', default=False),
1279 upgrade=dict(type='str', choices=['dist', 'full', 'no', 'safe', 'yes'], default='no'),
1280 dpkg_options=dict(type='str', default=DPKG_OPTIONS),
1281 autoremove=dict(type='bool', default=False),
1282 autoclean=dict(type='bool', default=False),
1283 fail_on_autoremove=dict(type='bool', default=False),
1284 policy_rc_d=dict(type='int', default=None),
1285 only_upgrade=dict(type='bool', default=False),
1286 force_apt_get=dict(type='bool', default=False),
1287 clean=dict(type='bool', default=False),
1288 allow_unauthenticated=dict(type='bool', default=False, aliases=['allow-unauthenticated']),
1289 allow_downgrade=dict(type='bool', default=False, aliases=['allow-downgrade', 'allow_downgrades', 'allow-downgrades']),
1290 allow_change_held_packages=dict(type='bool', default=False),
1291 lock_timeout=dict(type='int', default=60),
1292 auto_install_module_deps=dict(type='bool', default=True),
1293 ),
1294 mutually_exclusive=[['deb', 'package', 'upgrade']],
1295 required_one_of=[['autoremove', 'deb', 'package', 'update_cache', 'upgrade']],
1296 supports_check_mode=True,
1297 )
1298
1299 # We screenscrape apt-get and aptitude output for information so we need
1300 # to make sure we use the best parsable locale when running commands
1301 # also set apt specific vars for desired behaviour
1302 locale = get_best_parsable_locale(module)
1303 locale_module.setlocale(locale_module.LC_ALL, locale)
1304 # APT related constants
1305 APT_ENV_VARS = dict(
1306 DEBIAN_FRONTEND='noninteractive',
1307 DEBIAN_PRIORITY='critical',
1308 LANG=locale,
1309 LC_ALL=locale,
1310 LC_MESSAGES=locale,
1311 LC_CTYPE=locale,
1312 LANGUAGE=locale,
1313 )
1314 module.run_command_environ_update = APT_ENV_VARS
1315
1316 global APTITUDE_CMD
1317 APTITUDE_CMD = module.get_bin_path("aptitude", False)
1318 global APT_GET_CMD
1319 APT_GET_CMD = module.get_bin_path("apt-get")
1320
1321 p = module.params
1322 install_recommends = p['install_recommends']
1323 dpkg_options = f"{expand_dpkg_options(p['dpkg_options'])} -o DPkg::Lock::Timeout={p['lock_timeout']}"
1324
1325 if not HAS_PYTHON_APT:
1326 # This interpreter can't see the apt Python library- we'll do the following to try and fix that:
1327 # 1) look in common locations for system-owned interpreters that can see it; if we find one, respawn under it
1328 # 2) finding none, try to install a matching python3-apt package for the current interpreter version;
1329 # we limit to the current interpreter version to try and avoid installing a whole other Python just
1330 # for apt support
1331 # 3) if we installed a support package, try to respawn under what we think is the right interpreter (could be
1332 # the current interpreter again, but we'll let it respawn anyway for simplicity)
1333 # 4) if still not working, return an error and give up (some corner cases not covered, but this shouldn't be
1334 # made any more complex than it already is to try and cover more, eg, custom interpreters taking over
1335 # system locations)
1336
1337 apt_pkg_name = 'python3-apt'
1338
1339 if has_respawned():
1340 # this shouldn't be possible; short-circuit early if it happens...
1341 module.fail_json(msg="{0} must be installed and visible from {1}.".format(apt_pkg_name, sys.executable))
1342
1343 interpreters = ['/usr/bin/python3', '/usr/bin/python']
1344
1345 interpreter = probe_interpreters_for_module(interpreters, 'apt')
1346
1347 if interpreter:
1348 # found the Python bindings; respawn this module under the interpreter where we found them
1349 respawn_module(interpreter)
1350 # this is the end of the line for this process, it will exit here once the respawned module has completed
1351
1352 # don't make changes if we're in check_mode
1353 if module.check_mode:
1354 module.fail_json(
1355 msg=f"{apt_pkg_name} must be installed to use check mode. "
1356 "If run normally this module can auto-install it, "
1357 "see the auto_install_module_deps option.",
1358 )
1359 elif p['auto_install_module_deps']:
1360 # We skip cache update in auto install the dependency if the
1361 # user explicitly declared it with update_cache=no.
1362 if module.params.get('update_cache') is False:
1363 module.warn("Auto-installing missing dependency without updating cache: %s" % apt_pkg_name)
1364 else:
1365 module.warn("Updating cache and auto-installing missing dependency: %s" % apt_pkg_name)
1366 module.run_command([APT_GET_CMD, 'update'], check_rc=True)
1367
1368 # try to install the apt Python binding
1369 apt_pkg_cmd = [APT_GET_CMD, 'install', apt_pkg_name, '-y', '-q', dpkg_options]
1370
1371 if install_recommends is False:
1372 apt_pkg_cmd.extend(["-o", "APT::Install-Recommends=no"])
1373 elif install_recommends is True:
1374 apt_pkg_cmd.extend(["-o", "APT::Install-Recommends=yes"])
1375 # install_recommends is None uses the OS default
1376
1377 module.run_command(apt_pkg_cmd, check_rc=True)
1378
1379 # try again to find the bindings in common places
1380 interpreter = probe_interpreters_for_module(interpreters, 'apt')
1381
1382 if interpreter:
1383 # found the Python bindings; respawn this module under the interpreter where we found them
1384 # NB: respawn is somewhat wasteful if it's this interpreter, but simplifies the code
1385 respawn_module(interpreter)
1386 # this is the end of the line for this process, it will exit here once the respawned module has completed
1387
1388 # we've done all we can do; just tell the user it's busted and get out
1389 py_version = sys.version.replace("\n", "")
1390 module.fail_json(
1391 msg=f"Could not import the {apt_pkg_name} module using {sys.executable} ({py_version}). "
1392 f"Ensure {apt_pkg_name} package is installed (either manually or via the auto_install_module_deps option) "
1393 f"or that you have specified the correct ansible_python_interpreter. (attempted {interpreters}).",
1394 )
1395
1396 if p['clean'] is True:
1397 aptclean_stdout, aptclean_stderr, aptclean_diff = aptclean(module)
1398 # If there is nothing else to do exit. This will set state as
1399 # changed based on if the cache was updated.
1400 if not p['package'] and p['upgrade'] == 'no' and not p['deb']:
1401 module.exit_json(
1402 changed=True,
1403 msg=aptclean_stdout,
1404 stdout=aptclean_stdout,
1405 stderr=aptclean_stderr,
1406 diff=aptclean_diff
1407 )
1408
1409 if p['upgrade'] == 'no':
1410 p['upgrade'] = None
1411
1412 use_apt_get = p['force_apt_get']
1413
1414 if not use_apt_get and not APTITUDE_CMD:
1415 use_apt_get = True
1416
1417 updated_cache = False
1418 updated_cache_time = 0
1419 allow_unauthenticated = p['allow_unauthenticated']
1420 allow_downgrade = p['allow_downgrade']
1421 allow_change_held_packages = p['allow_change_held_packages']
1422 autoremove = p['autoremove']
1423 fail_on_autoremove = p['fail_on_autoremove']
1424 autoclean = p['autoclean']
1425
1426 # max times we'll retry
1427 deadline = time.time() + p['lock_timeout']
1428
1429 # keep running on lock issues unless timeout or resolution is hit.
1430 while True:
1431
1432 # Get the cache object, this has 3 retries built in
1433 cache = get_cache(module)
1434
1435 try:
1436 if p['default_release']:
1437 try:
1438 apt_pkg.config['APT::Default-Release'] = p['default_release']
1439 except AttributeError:
1440 apt_pkg.Config['APT::Default-Release'] = p['default_release']
1441 # reopen cache w/ modified config
1442 cache.open(progress=None)
1443
1444 mtimestamp, updated_cache_time = get_updated_cache_time()
1445 # Cache valid time is default 0, which will update the cache if
1446 # needed and `update_cache` was set to true
1447 updated_cache = False
1448 if p['update_cache'] or p['cache_valid_time']:
1449 now = datetime.datetime.now()
1450 tdelta = datetime.timedelta(seconds=p['cache_valid_time'])
1451 if not mtimestamp + tdelta >= now:
1452 # Retry to update the cache with exponential backoff
1453 err = ''
1454 update_cache_retries = module.params.get('update_cache_retries')
1455 update_cache_retry_max_delay = module.params.get('update_cache_retry_max_delay')
1456 randomize = secrets.randbelow(1000) / 1000.0
1457
1458 for retry in range(update_cache_retries):
1459 try:
1460 if not module.check_mode:
1461 cache.update()
1462 break
1463 except apt.cache.FetchFailedException as fetch_failed_exc:
1464 err = fetch_failed_exc
1465 module.warn(
1466 f"Failed to update cache after {retry + 1} retries due "
1467 f"to {to_native(fetch_failed_exc)}, retrying"
1468 )
1469
1470 # Use exponential backoff plus a little bit of randomness
1471 delay = 2 ** retry + randomize
1472 if delay > update_cache_retry_max_delay:
1473 delay = update_cache_retry_max_delay + randomize
1474 time.sleep(delay)
1475 module.warn(f"Sleeping for {int(round(delay))} seconds, before attempting to refresh the cache again")
1476 else:
1477 msg = (
1478 f"Failed to update apt cache after {update_cache_retries} retries: "
1479 f"{err if err else 'unknown reason'}"
1480 )
1481 module.fail_json(msg=msg)
1482
1483 cache.open(progress=None)
1484 mtimestamp, post_cache_update_time = get_updated_cache_time()
1485 if module.check_mode or updated_cache_time != post_cache_update_time:
1486 updated_cache = True
1487 updated_cache_time = post_cache_update_time
1488
1489 # If there is nothing else to do exit. This will set state as
1490 # changed based on if the cache was updated.
1491 if not p['package'] and not p['upgrade'] and not p['deb']:
1492 module.exit_json(
1493 changed=updated_cache,
1494 cache_updated=updated_cache,
1495 cache_update_time=updated_cache_time
1496 )
1497
1498 force_yes = p['force']
1499
1500 if p['upgrade']:
1501 upgrade(
1502 module,
1503 p['upgrade'],
1504 force_yes,
1505 p['default_release'],
1506 use_apt_get,
1507 dpkg_options,
1508 autoremove,
1509 fail_on_autoremove,
1510 allow_unauthenticated,
1511 allow_downgrade
1512 )
1513
1514 if p['deb']:
1515 if p['state'] != 'present':
1516 module.fail_json(msg="deb only supports state=present")
1517 if '://' in p['deb']:
1518 p['deb'] = fetch_file(module, p['deb'])
1519 install_deb(module, p['deb'], cache,
1520 install_recommends=install_recommends,
1521 allow_unauthenticated=allow_unauthenticated,
1522 allow_change_held_packages=allow_change_held_packages,
1523 allow_downgrade=allow_downgrade,
1524 force=force_yes,
1525 fail_on_autoremove=fail_on_autoremove,
1526 dpkg_options=p['dpkg_options'],
1527 lock_timeout=p['lock_timeout']
1528 )
1529
1530 unfiltered_packages = p['package'] or ()
1531 packages = [package.strip() for package in unfiltered_packages if package != '*']
1532 all_installed = '*' in unfiltered_packages
1533 latest = p['state'] == 'latest'
1534
1535 if latest and all_installed:
1536 if packages:
1537 module.fail_json(msg='unable to install additional packages when upgrading all installed packages')
1538 upgrade(
1539 module,
1540 'yes',
1541 force_yes,
1542 p['default_release'],
1543 use_apt_get,
1544 dpkg_options,
1545 autoremove,
1546 fail_on_autoremove,
1547 allow_unauthenticated,
1548 allow_downgrade
1549 )
1550
1551 if packages:
1552 for package in packages:
1553 if package.count('=') > 1:
1554 module.fail_json(msg="invalid package spec: %s" % package)
1555
1556 if not packages:
1557 if autoclean:
1558 cleanup(module, p['purge'], force=force_yes, operation='autoclean', dpkg_options=dpkg_options)
1559 if autoremove:
1560 cleanup(module, p['purge'], force=force_yes, operation='autoremove', dpkg_options=dpkg_options)
1561
1562 if p['state'] in ('latest', 'present', 'build-dep', 'fixed'):
1563 state_upgrade = False
1564 state_builddep = False
1565 state_fixed = False
1566 if p['state'] == 'latest':
1567 state_upgrade = True
1568 if p['state'] == 'build-dep':
1569 state_builddep = True
1570 if p['state'] == 'fixed':
1571 state_fixed = True
1572
1573 success, retvals = install(
1574 module,
1575 packages,
1576 cache,
1577 upgrade=state_upgrade,
1578 default_release=p['default_release'],
1579 install_recommends=install_recommends,
1580 force=force_yes,
1581 dpkg_options=dpkg_options,
1582 build_dep=state_builddep,
1583 fixed=state_fixed,
1584 autoremove=autoremove,
1585 fail_on_autoremove=fail_on_autoremove,
1586 only_upgrade=p['only_upgrade'],
1587 allow_unauthenticated=allow_unauthenticated,
1588 allow_downgrade=allow_downgrade,
1589 allow_change_held_packages=allow_change_held_packages,
1590 )
1591
1592 # Store if the cache has been updated
1593 retvals['cache_updated'] = updated_cache
1594 # Store when the update time was last
1595 retvals['cache_update_time'] = updated_cache_time
1596
1597 if success:
1598 module.exit_json(**retvals)
1599 else:
1600 module.fail_json(**retvals)
1601 elif p['state'] == 'absent':
1602 remove(
1603 module,
1604 packages,
1605 cache,
1606 p['purge'],
1607 force=force_yes,
1608 dpkg_options=dpkg_options,
1609 autoremove=autoremove,
1610 allow_change_held_packages=allow_change_held_packages
1611 )
1612
1613 except apt.cache.LockFailedException as lockFailedException:
1614 if time.time() < deadline:
1615 continue
1616 module.fail_json(msg="Failed to lock apt for exclusive operation: %s" % lockFailedException)
1617 except apt.cache.FetchFailedException as fetchFailedException:
1618 module.fail_json(msg="Could not fetch updated apt files: %s" % fetchFailedException)
1619
1620 # got here w/o exception and/or exit???
1621 module.fail_json(msg='Unexpected code path taken, we really should have exited before, this is a bug')
1622
1623
1624 if __name__ == "__main__":
1625 main()