Debian Codegraph @

lib/ansible/modules/apt_repository.py

raw
1 # encoding: utf-8
2
3 # Copyright: (c) 2012, Matt Wright <[email protected]>
4 # Copyright: (c) 2013, Alexander Saltanov <[email protected]>
5 # Copyright: (c) 2014, Rutger Spiertz <[email protected]>
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_repository
15 short_description: Add and remove APT repositories
16 description:
17 - Add or remove an APT repositories in Ubuntu and Debian.
18 extends_documentation_fragment: action_common_attributes
19 deprecated:
20 alternative: ansible.builtin.deb822_repository
21 why: The M(ansible.builtin.apt_repository) module is deprecated in favor of the M(ansible.builtin.deb822_repository) module.
22 removed_in: "2.25"
23 attributes:
24 check_mode:
25 support: full
26 diff_mode:
27 support: full
28 platform:
29 platforms: debian
30 notes:
31 - This module supports Debian Squeeze (version 6) as well as its successors and derivatives.
32 seealso:
33 - module: ansible.builtin.deb822_repository
34 options:
35 repo:
36 description:
37 - A source string for the repository.
38 type: str
39 required: true
40 state:
41 description:
42 - A source string state.
43 type: str
44 choices: [ absent, present ]
45 default: "present"
46 mode:
47 description:
48 - The octal mode for newly created files in C(sources.list.d).
49 - Default is what system uses (probably 0644).
50 type: raw
51 version_added: "1.6"
52 update_cache:
53 description:
54 - Run the equivalent of C(apt-get update) when a change occurs. Cache updates are run after making changes.
55 type: bool
56 default: "yes"
57 aliases: [ update-cache ]
58 update_cache_retries:
59 description:
60 - Amount of retries if the cache update fails. Also see O(update_cache_retry_max_delay).
61 type: int
62 default: 5
63 version_added: '2.10'
64 update_cache_retry_max_delay:
65 description:
66 - Use an exponential backoff delay for each retry (see O(update_cache_retries)) up to this max delay in seconds.
67 type: int
68 default: 12
69 version_added: '2.10'
70 validate_certs:
71 description:
72 - If V(false), SSL certificates for the target repo will not be validated. This should only be used
73 on personally controlled sites using self-signed certificates.
74 type: bool
75 default: 'yes'
76 version_added: '1.8'
77 filename:
78 description:
79 - Sets the name of the source list file in C(sources.list.d).
80 Defaults to a file name based on the repository source url.
81 The C(.list) extension will be automatically added.
82 type: str
83 version_added: '2.1'
84 codename:
85 description:
86 - Override the distribution codename to use for PPA repositories.
87 Should usually only be set when working with a PPA on
88 a non-Ubuntu target (for example, Debian or Mint).
89 type: str
90 version_added: '2.3'
91 install_python_apt:
92 description:
93 - Whether to automatically try to install the Python apt library or not, if it is not already installed.
94 Without this library, the module does not work.
95 - Runs C(apt-get install python3-apt).
96 - Only works with the system Python. If you are using a Python on the remote that is not
97 the system Python, set O(install_python_apt=false) and ensure that the Python apt library
98 for your Python version is installed some other way.
99 type: bool
100 default: true
101 author:
102 - Alexander Saltanov (@sashka)
103 version_added: "0.7"
104 requirements:
105 - python3-apt
106 - apt-key or gpg
107 """
108
109 EXAMPLES = """
110 - name: Add specified repository into sources list
111 ansible.builtin.apt_repository:
112 repo: deb http://archive.canonical.com/ubuntu hardy partner
113 state: present
114
115 - name: Add specified repository into sources list using specified filename
116 ansible.builtin.apt_repository:
117 repo: deb http://dl.google.com/linux/chrome/deb/ stable main
118 state: present
119 filename: google-chrome
120
121 - name: Add source repository into sources list
122 ansible.builtin.apt_repository:
123 repo: deb-src http://archive.canonical.com/ubuntu hardy partner
124 state: present
125
126 - name: Remove specified repository from sources list
127 ansible.builtin.apt_repository:
128 repo: deb http://archive.canonical.com/ubuntu hardy partner
129 state: absent
130
131 - name: Add nginx stable repository from PPA and install its signing key on Ubuntu target
132 ansible.builtin.apt_repository:
133 repo: ppa:nginx/stable
134
135 - name: Add nginx stable repository from PPA and install its signing key on Debian target
136 ansible.builtin.apt_repository:
137 repo: 'ppa:nginx/stable'
138 codename: trusty
139
140 - name: One way to avoid apt_key once it is removed from your distro
141 block:
142 - name: somerepo |no apt key
143 ansible.builtin.get_url:
144 url: https://download.example.com/linux/ubuntu/gpg
145 dest: /etc/apt/keyrings/somerepo.asc
146
147 - name: somerepo | apt source
148 ansible.builtin.apt_repository:
149 repo: "deb [arch=amd64 signed-by=/etc/apt/keyrings/somerepo.asc] https://download.example.com/linux/ubuntu {{ ansible_distribution_release }} stable"
150 state: present
151 """
152
153 RETURN = """
154 repo:
155 description: A source string for the repository
156 returned: always
157 type: str
158 sample: "deb https://artifacts.elastic.co/packages/6.x/apt stable main"
159
160 sources_added:
161 description: List of sources added
162 returned: success, sources were added
163 type: list
164 sample: ["/etc/apt/sources.list.d/artifacts_elastic_co_packages_6_x_apt.list"]
165 version_added: "2.15"
166
167 sources_removed:
168 description: List of sources removed
169 returned: success, sources were removed
170 type: list
171 sample: ["/etc/apt/sources.list.d/artifacts_elastic_co_packages_6_x_apt.list"]
172 version_added: "2.15"
173 """
174
175 import copy
176 import glob
177 import json
178 import os
179 import re
180 import secrets
181 import sys
182 import tempfile
183 import time
184
185 from ansible.module_utils.basic import AnsibleModule
186 from ansible.module_utils.common.file import S_IRWU_RG_RO as DEFAULT_SOURCES_PERM
187 from ansible.module_utils.common.respawn import has_respawned, probe_interpreters_for_module, respawn_module
188 from ansible.module_utils.common.text.converters import to_native
189 from ansible.module_utils.urls import fetch_url, is_fetch_success
190
191 from ansible.module_utils.common.locale import get_best_parsable_locale
192
193 try:
194 import apt
195 import apt_pkg
196 import aptsources.distro as aptsources_distro
197
198 distro = aptsources_distro.get_distro()
199
200 HAVE_PYTHON_APT = True
201 except ImportError:
202 apt = apt_pkg = aptsources_distro = distro = None
203
204 HAVE_PYTHON_APT = False
205
206 APT_KEY_DIRS = ['/etc/apt/keyrings', '/etc/apt/trusted.gpg.d', '/usr/share/keyrings']
207 VALID_SOURCE_TYPES = ('deb', 'deb-src')
208
209
210 def install_python_apt(module, apt_pkg_name):
211
212 if not module.check_mode:
213 apt_get_path = module.get_bin_path('apt-get')
214 if apt_get_path:
215 rc, so, se = module.run_command([apt_get_path, 'update'])
216 if rc != 0:
217 module.fail_json(msg="Failed to auto-install %s. Error was: '%s'" % (apt_pkg_name, se.strip()))
218 rc, so, se = module.run_command([apt_get_path, 'install', apt_pkg_name, '-y', '-q'])
219 if rc != 0:
220 module.fail_json(msg="Failed to auto-install %s. Error was: '%s'" % (apt_pkg_name, se.strip()))
221 else:
222 module.fail_json(msg="%s must be installed to use check mode" % apt_pkg_name)
223
224
225 class InvalidSource(Exception):
226 pass
227
228
229 # Simple version of aptsources.sourceslist.SourcesList.
230 # No advanced logic and no backups inside.
231 class SourcesList(object):
232 def __init__(self, module):
233 self.module = module
234 self.files = {} # group sources by file
235 self.files_mapping = {} # internal DS for tracking symlinks
236 # Repositories that we're adding -- used to implement mode param
237 self.new_repos = set()
238 self.default_file = apt_pkg.config.find_file('Dir::Etc::sourcelist')
239
240 # read sources.list if it exists
241 if os.path.isfile(self.default_file):
242 self.load(self.default_file)
243
244 # read sources.list.d
245 self.sources_dir = apt_pkg.config.find_dir('Dir::Etc::sourceparts')
246 for file in glob.iglob(f'{self.sources_dir}/*.list'):
247 if os.path.islink(file):
248 self.files_mapping[file] = os.readlink(file)
249 self.load(file)
250
251 def __iter__(self):
252 """Simple iterator to go over all sources. Empty, non-source, and other not valid lines will be skipped."""
253 for file, sources in self.files.items():
254 for n, valid, enabled, source, comment in sources:
255 if valid:
256 yield file, n, enabled, source, comment
257
258 def _expand_path(self, filename):
259 if '/' in filename:
260 return filename
261 else:
262 return os.path.abspath(os.path.join(self.sources_dir, filename))
263
264 def _suggest_filename(self, line):
265 def _cleanup_filename(s):
266 filename = self.module.params['filename']
267 if filename is not None:
268 return filename
269 return '_'.join(re.sub('[^a-zA-Z0-9]', ' ', s).split())
270
271 def _strip_username_password(s):
272 if '@' in s:
273 s = s.split('@', 1)
274 s = s[-1]
275 return s
276
277 # Drop options and protocols.
278 line = re.sub(r'\[[^\]]+\]', '', line)
279 line = re.sub(r'\w+://', '', line)
280
281 # split line into valid keywords
282 parts = [part for part in line.split() if part not in VALID_SOURCE_TYPES]
283
284 # Drop usernames and passwords
285 parts[0] = _strip_username_password(parts[0])
286
287 return '%s.list' % _cleanup_filename(' '.join(parts[:1]))
288
289 @staticmethod
290 def _validate_source(source: str) -> bool:
291 """
292 Validate a source string according to the SOURCES.LIST(5).
293 See: https://manpages.debian.org/trixie/apt/sources.list.5.en.html#ONE-LINE-STYLE_FORMAT
294 """
295 parts = source.split()
296
297 if not parts:
298 return False
299
300 # Extract the type and handle options
301 if parts[0] not in VALID_SOURCE_TYPES:
302 return False
303
304 # Check for options enclosed in square brackets
305 # The first element after the type might be the start of options
306 if len(parts) > 1 and parts[1].startswith('['):
307 if parts[1].endswith(']'):
308 # For single-word options
309 remaining_parts = parts[2:]
310 else:
311 # For multi-word options
312 end_bracket_index = -1
313 for i, part in enumerate(parts[2:], start=2):
314 if part.endswith(']'):
315 end_bracket_index = i
316 break
317
318 if end_bracket_index != -1:
319 remaining_parts = parts[end_bracket_index + 1:]
320 else:
321 # Malformed options, treat the whole thing as a single part for now.
322 remaining_parts = parts[1:]
323 return False
324 else:
325 remaining_parts = parts[1:]
326
327 if len(remaining_parts) < 2:
328 return False
329
330 # According to `sources.list(5)` man pages, only four fields are mandatory:
331 # * `Types` either `deb` or/and `deb-src`
332 # * `URIs` to repositories holding valid APT structure (unclear if multiple are allowed)
333 # * `Suites` usually being distribution codenames
334 # * `Component` most of the time `main`, but it's a section of the repository
335 if remaining_parts[1].endswith('/') and len(remaining_parts) > 2:
336 # Suites with trailing slash makes component optional
337 return False
338 if not remaining_parts[1].endswith('/') and len(remaining_parts) < 3:
339 # Invalid line format
340 return False
341
342 return True
343
344 def _parse(self, line, raise_if_invalid_or_disabled=False):
345 valid = False
346 enabled = True
347 source = ''
348 comment = ''
349
350 line = line.strip()
351 if line.startswith('#'):
352 enabled = False
353 line = line[1:]
354
355 # Check for another "#" in the line and treat a part after it as a comment.
356 i = line.find('#')
357 if i > 0:
358 comment = line[i + 1:].strip()
359 line = line[:i]
360
361 # Split a source into substring to make sure that it is source spec.
362 # Duplicated whitespaces in a valid source spec will be removed.
363 source = line.strip()
364 if source:
365 valid = self._validate_source(source)
366
367 if raise_if_invalid_or_disabled and (not valid or not enabled):
368 raise InvalidSource(line)
369
370 return valid, enabled, source, comment
371
372 def load(self, file):
373 group = []
374 with open(file, 'r') as f:
375 for n, line in enumerate(f):
376 valid, enabled, source, comment = self._parse(line)
377 group.append((n, valid, enabled, source, comment))
378 self.files[file] = group
379
380 def save(self):
381 for filename, sources in list(self.files.items()):
382 if sources:
383 d, fn = os.path.split(filename)
384 try:
385 os.makedirs(d)
386 except OSError as ex:
387 if not os.path.isdir(d):
388 self.module.fail_json("Failed to create directory %s: %s" % (d, to_native(ex)))
389
390 try:
391 fd, tmp_path = tempfile.mkstemp(prefix=".%s-" % fn, dir=d)
392 except OSError as ex:
393 raise Exception(f'Unable to create temp file at {d!r} for apt source.') from ex
394
395 f = os.fdopen(fd, 'w')
396 for n, valid, enabled, source, comment in sources:
397 chunks = []
398 if not enabled:
399 chunks.append('# ')
400 chunks.append(source)
401 if comment:
402 chunks.append(' # ')
403 chunks.append(comment)
404 chunks.append('\n')
405 line = ''.join(chunks)
406
407 try:
408 f.write(line)
409 except OSError as ex:
410 raise Exception(f"Failed to write to file {tmp_path!r}.") from ex
411 if filename in self.files_mapping:
412 # Write to symlink target instead of replacing symlink as a normal file
413 self.module.atomic_move(tmp_path, self.files_mapping[filename])
414 else:
415 self.module.atomic_move(tmp_path, filename)
416
417 # allow the user to override the default mode
418 if filename in self.new_repos:
419 this_mode = self.module.params.get('mode', DEFAULT_SOURCES_PERM)
420 self.module.set_mode_if_different(filename, this_mode, False)
421 else:
422 del self.files[filename]
423 if os.path.exists(filename):
424 os.remove(filename)
425
426 def dump(self):
427 dumpstruct = {}
428 for filename, sources in self.files.items():
429 if sources:
430 lines = []
431 for n, valid, enabled, source, comment in sources:
432 chunks = []
433 if not enabled:
434 chunks.append('# ')
435 chunks.append(source)
436 if comment:
437 chunks.append(' # ')
438 chunks.append(comment)
439 chunks.append('\n')
440 lines.append(''.join(chunks))
441 dumpstruct[filename] = ''.join(lines)
442 return dumpstruct
443
444 def _choice(self, new, old):
445 if new is None:
446 return old
447 return new
448
449 def modify(self, file, n, enabled=None, source=None, comment=None):
450 """
451 This function to be used with iterator, so we don't care of invalid sources.
452 If source, enabled, or comment is None, original value from line ``n`` will be preserved.
453 """
454 valid, enabled_old, source_old, comment_old = self.files[file][n][1:]
455 self.files[file][n] = (n, valid, self._choice(enabled, enabled_old), self._choice(source, source_old), self._choice(comment, comment_old))
456
457 def _add_valid_source(self, source_new, comment_new, file):
458 # We'll try to reuse disabled source if we have it.
459 # If we have more than one entry, we will enable them all - no advanced logic, remember.
460 self.module.log('adding source file: %s | %s | %s' % (source_new, comment_new, file))
461 found = False
462 for filename, n, enabled, source, comment in self:
463 if source == source_new:
464 self.modify(filename, n, enabled=True)
465 found = True
466
467 if not found:
468 if file is None:
469 file = self.default_file
470 else:
471 file = self._expand_path(file)
472
473 if file not in self.files:
474 self.files[file] = []
475
476 files = self.files[file]
477 files.append((len(files), True, True, source_new, comment_new))
478 self.new_repos.add(file)
479
480 def add_source(self, line, comment='', file=None):
481 source = self._parse(line, raise_if_invalid_or_disabled=True)[2]
482
483 # Prefer separate files for new sources.
484 self._add_valid_source(source, comment, file=file or self._suggest_filename(source))
485
486 def _remove_valid_source(self, source):
487 # If we have more than one entry, we will remove them all (not comment, remove!)
488 for filename, n, enabled, src, comment in self:
489 if source == src and enabled:
490 self.files[filename].pop(n)
491
492 def remove_source(self, line):
493 source = self._parse(line, raise_if_invalid_or_disabled=True)[2]
494 self._remove_valid_source(source)
495
496
497 class UbuntuSourcesList(SourcesList):
498
499 # prefer api.launchpad.net over launchpad.net/api
500 # see: https://github.com/ansible/ansible/pull/81978#issuecomment-1767062178
501 LP_API = 'https://api.launchpad.net/1.0/~%s/+archive/%s'
502 PPA_URI = 'https://ppa.launchpadcontent.net'
503
504 def __init__(self, module):
505 self.module = module
506 self.codename = module.params['codename'] or distro.codename
507 super(UbuntuSourcesList, self).__init__(module)
508
509 self.apt_key_bin = self.module.get_bin_path('apt-key', required=False)
510 self.gpg_bin = self.module.get_bin_path('gpg', required=False)
511 if not self.apt_key_bin and not self.gpg_bin:
512 msg = 'Either apt-key or gpg binary is required, but neither could be found.' \
513 'The apt-key CLI has been deprecated and removed in modern Debian and derivatives, ' \
514 'you might want to use "deb822_repository" instead.'
515 self.module.fail_json(msg)
516
517 def __deepcopy__(self, memo=None):
518 return UbuntuSourcesList(self.module)
519
520 def _get_ppa_info(self, owner_name, ppa_name):
521 lp_api = self.LP_API % (owner_name, ppa_name)
522
523 headers = dict(Accept='application/json')
524 response, info = fetch_url(self.module, lp_api, headers=headers)
525 if not is_fetch_success(info):
526 self.module.fail_json(msg="failed to fetch PPA information, error was: %s" % info['msg'])
527 return json.loads(to_native(response.read()))
528
529 def _expand_ppa(self, path):
530 ppa = path.split(':')[1]
531 ppa_owner = ppa.split('/')[0]
532 try:
533 ppa_name = ppa.split('/')[1]
534 except IndexError:
535 ppa_name = 'ppa'
536
537 line = 'deb %s/%s/%s/ubuntu %s main' % (self.PPA_URI, ppa_owner, ppa_name, self.codename)
538 return line, ppa_owner, ppa_name
539
540 def _key_already_exists(self, key_fingerprint):
541
542 if self.apt_key_bin:
543 locale = get_best_parsable_locale(self.module)
544 APT_ENV = dict(LANG=locale, LC_ALL=locale, LC_MESSAGES=locale, LC_CTYPE=locale, LANGUAGE=locale)
545 self.module.run_command_environ_update = APT_ENV
546 rc, out, err = self.module.run_command([self.apt_key_bin, 'export', key_fingerprint], check_rc=True)
547 found = bool(not err or 'nothing exported' not in err)
548 else:
549 found = self._gpg_key_exists(key_fingerprint)
550
551 return found
552
553 def _gpg_key_exists(self, key_fingerprint):
554
555 found = False
556 keyfiles = ['/etc/apt/trusted.gpg'] # main gpg repo for apt
557 for other_dir in APT_KEY_DIRS:
558 # add other known sources of gpg sigs for apt, skip hidden files
559 keyfiles.extend([os.path.join(other_dir, x) for x in os.listdir(other_dir) if not x.startswith('.')])
560
561 for key_file in keyfiles:
562
563 if os.path.exists(key_file):
564 try:
565 rc, out, err = self.module.run_command([self.gpg_bin, '--list-packets', key_file])
566 except OSError as ex:
567 self.module.debug(f"Could check key against file {key_file!r}: {ex}")
568 continue
569
570 if key_fingerprint in out:
571 found = True
572 break
573
574 return found
575
576 # https://www.linuxuprising.com/2021/01/apt-key-is-deprecated-how-to-add.html
577 def add_source(self, line, comment='', file=None):
578 if line.startswith('ppa:'):
579 source, ppa_owner, ppa_name = self._expand_ppa(line)
580
581 if source in self.repos_urls:
582 # repository already exists
583 return
584
585 info = self._get_ppa_info(ppa_owner, ppa_name)
586
587 # add gpg sig if needed
588 if not self._key_already_exists(info['signing_key_fingerprint']):
589
590 # TODO: report file that would have been added if not check_mode
591 keyfile = ''
592 if not self.module.check_mode:
593 if self.apt_key_bin:
594 command = [self.apt_key_bin, 'adv', '--recv-keys', '--no-tty', '--keyserver', 'hkp://keyserver.ubuntu.com:80',
595 info['signing_key_fingerprint']]
596 else:
597 # use first available key dir, in order of preference
598 for keydir in APT_KEY_DIRS:
599 if os.path.exists(keydir):
600 break
601 else:
602 self.module.fail_json("Unable to find any existing apt gpgp repo directories, tried the following: %s" % ', '.join(APT_KEY_DIRS))
603
604 keyfile = '%s/%s-%s-%s.gpg' % (keydir, os.path.basename(source).replace(' ', '-'), ppa_owner, ppa_name)
605 command = [self.gpg_bin, '--no-tty', '--keyserver', 'hkp://keyserver.ubuntu.com:80', '--export', info['signing_key_fingerprint']]
606
607 rc, stdout, stderr = self.module.run_command(command, check_rc=True, encoding=None)
608 if keyfile:
609 # using gpg we must write keyfile ourselves
610 if len(stdout) == 0:
611 self.module.fail_json(msg='Unable to get required signing key', rc=rc, stderr=stderr, command=command)
612 try:
613 with open(keyfile, 'wb') as f:
614 f.write(stdout)
615 self.module.log('Added repo key "%s" for apt to file "%s"' % (info['signing_key_fingerprint'], keyfile))
616 except OSError as ex:
617 self.module.fail_json(msg='Unable to add required signing key.', rc=rc, stderr=stderr, error=str(ex), exception=ex)
618
619 # apt source file
620 file = file or self._suggest_filename('%s_%s' % (line, self.codename))
621 else:
622 source = self._parse(line, raise_if_invalid_or_disabled=True)[2]
623 file = file or self._suggest_filename(source)
624
625 self._add_valid_source(source, comment, file)
626
627 def remove_source(self, line):
628 if line.startswith('ppa:'):
629 source = self._expand_ppa(line)[0]
630 else:
631 source = self._parse(line, raise_if_invalid_or_disabled=True)[2]
632 self._remove_valid_source(source)
633
634 @property
635 def repos_urls(self):
636 _repositories = []
637 for parsed_repos in self.files.values():
638 for parsed_repo in parsed_repos:
639 valid = parsed_repo[1]
640 enabled = parsed_repo[2]
641 source_line = parsed_repo[3]
642
643 if not valid or not enabled:
644 continue
645
646 if source_line.startswith('ppa:'):
647 source, ppa_owner, ppa_name = self._expand_ppa(source_line)
648 _repositories.append(source)
649 else:
650 _repositories.append(source_line)
651
652 return _repositories
653
654
655 def revert_sources_list(sources_before, sources_after, sourceslist_before):
656 """Revert the sourcelist files to their previous state."""
657
658 # First remove any new files that were created:
659 for filename in set(sources_after.keys()).difference(sources_before.keys()):
660 if os.path.exists(filename):
661 os.remove(filename)
662 # Now revert the existing files to their former state:
663 sourceslist_before.save()
664
665
666 def main():
667 module = AnsibleModule(
668 argument_spec=dict(
669 repo=dict(type='str', required=True),
670 state=dict(type='str', default='present', choices=['absent', 'present']),
671 mode=dict(type='raw'),
672 update_cache=dict(type='bool', default=True, aliases=['update-cache']),
673 update_cache_retries=dict(type='int', default=5),
674 update_cache_retry_max_delay=dict(type='int', default=12),
675 filename=dict(type='str'),
676 # This should not be needed, but exists as a failsafe
677 install_python_apt=dict(type='bool', default=True),
678 validate_certs=dict(type='bool', default=True),
679 codename=dict(type='str'),
680 ),
681 supports_check_mode=True,
682 )
683
684 params = module.params
685 repo = module.params['repo']
686 state = module.params['state']
687 update_cache = module.params['update_cache']
688 # Note: mode is referenced in SourcesList class via the passed in module (self here)
689
690 sourceslist = None
691
692 if not HAVE_PYTHON_APT:
693 # This interpreter can't see the apt Python library- we'll do the following to try and fix that:
694 # 1) look in common locations for system-owned interpreters that can see it; if we find one, respawn under it
695 # 2) finding none, try to install a matching python-apt package for the current interpreter version;
696 # we limit to the current interpreter version to try and avoid installing a whole other Python just
697 # for apt support
698 # 3) if we installed a support package, try to respawn under what we think is the right interpreter (could be
699 # the current interpreter again, but we'll let it respawn anyway for simplicity)
700 # 4) if still not working, return an error and give up (some corner cases not covered, but this shouldn't be
701 # made any more complex than it already is to try and cover more, eg, custom interpreters taking over
702 # system locations)
703
704 apt_pkg_name = 'python3-apt'
705
706 if has_respawned():
707 # this shouldn't be possible; short-circuit early if it happens...
708 module.fail_json(msg="{0} must be installed and visible from {1}.".format(apt_pkg_name, sys.executable))
709
710 interpreters = ['/usr/bin/python3', '/usr/bin/python']
711
712 interpreter = probe_interpreters_for_module(interpreters, 'apt')
713
714 if interpreter:
715 # found the Python bindings; respawn this module under the interpreter where we found them
716 respawn_module(interpreter)
717 # this is the end of the line for this process, it will exit here once the respawned module has completed
718
719 # don't make changes if we're in check_mode
720 if module.check_mode:
721 module.fail_json(msg="%s must be installed to use check mode. "
722 "If run normally this module can auto-install it." % apt_pkg_name)
723
724 if params['install_python_apt']:
725 install_python_apt(module, apt_pkg_name)
726 else:
727 module.fail_json(msg='%s is not installed, and install_python_apt is False' % apt_pkg_name)
728
729 # try again to find the bindings in common places
730 interpreter = probe_interpreters_for_module(interpreters, 'apt')
731
732 if interpreter:
733 # found the Python bindings; respawn this module under the interpreter where we found them
734 # NB: respawn is somewhat wasteful if it's this interpreter, but simplifies the code
735 respawn_module(interpreter)
736 # this is the end of the line for this process, it will exit here once the respawned module has completed
737 else:
738 # we've done all we can do; just tell the user it's busted and get out
739 module.fail_json(msg="{0} must be installed and visible from {1}.".format(apt_pkg_name, sys.executable))
740
741 if not repo:
742 module.fail_json(msg='Please set argument \'repo\' to a non-empty value')
743
744 if isinstance(distro, aptsources_distro.Distribution):
745 sourceslist = UbuntuSourcesList(module)
746 else:
747 module.fail_json(msg='Module apt_repository is not supported on target.')
748
749 sourceslist_before = copy.deepcopy(sourceslist)
750 sources_before = sourceslist.dump()
751
752 try:
753 if state == 'present':
754 sourceslist.add_source(repo)
755 elif state == 'absent':
756 sourceslist.remove_source(repo)
757 except InvalidSource as ex:
758 module.fail_json(msg='Invalid repository string: %s' % to_native(ex))
759
760 sources_after = sourceslist.dump()
761 changed = sources_before != sources_after
762
763 diff = []
764 sources_added = set()
765 sources_removed = set()
766 if changed:
767 sources_added = set(sources_after.keys()).difference(sources_before.keys())
768 sources_removed = set(sources_before.keys()).difference(sources_after.keys())
769 if module._diff:
770 for filename in set(sources_added.union(sources_removed)):
771 diff.append({'before': sources_before.get(filename, ''),
772 'after': sources_after.get(filename, ''),
773 'before_header': (filename, '/dev/null')[filename not in sources_before],
774 'after_header': (filename, '/dev/null')[filename not in sources_after]})
775
776 if changed and not module.check_mode:
777 try:
778 err = ''
779 sourceslist.save()
780 if update_cache:
781 update_cache_retries = module.params.get('update_cache_retries')
782 update_cache_retry_max_delay = module.params.get('update_cache_retry_max_delay')
783 randomize = secrets.randbelow(1000) / 1000.0
784
785 cache = apt.Cache()
786 for retry in range(update_cache_retries):
787 try:
788 cache.update()
789 break
790 except apt.cache.FetchFailedException as fetch_failed_exc:
791 err = fetch_failed_exc
792 module.warn(
793 f"Failed to update cache after {retry + 1} due "
794 f"to {to_native(fetch_failed_exc)} retry, retrying"
795 )
796
797 # Use exponential backoff with a max fail count, plus a little bit of randomness
798 delay = 2 ** retry + randomize
799 if delay > update_cache_retry_max_delay:
800 delay = update_cache_retry_max_delay + randomize
801 time.sleep(delay)
802 module.warn(f"Sleeping for {int(round(delay))} seconds, before attempting to update the cache again")
803 else:
804 revert_sources_list(sources_before, sources_after, sourceslist_before)
805 msg = (
806 f"Failed to update apt cache after {update_cache_retries} retries: "
807 f"{err if err else 'unknown reason'}"
808 )
809 module.fail_json(msg=msg)
810
811 except OSError as ex:
812 revert_sources_list(sources_before, sources_after, sourceslist_before)
813 raise
814
815 module.exit_json(changed=changed, repo=repo, sources_added=sources_added, sources_removed=sources_removed, state=state, diff=diff)
816
817
818 if __name__ == '__main__':
819 main()