Debian Codegraph @

lib/ansible/modules/deb822_repository.py

raw
1 # -*- coding: utf-8 -*-
2 # Copyright: Contributors to the Ansible project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 from __future__ import annotations
6
7 DOCUMENTATION = """
8 author: 'Ansible Core Team (@ansible)'
9 short_description: 'Add and remove deb822 formatted repositories'
10 description:
11 - 'Add and remove deb822 formatted repositories in Debian based distributions.'
12 module: deb822_repository
13 notes:
14 - This module will not automatically update caches, call the M(ansible.builtin.apt) module based
15 on the changed state.
16 options:
17 allow_downgrade_to_insecure:
18 description:
19 - Allow downgrading a package that was previously authenticated but
20 is no longer authenticated.
21 type: bool
22 allow_insecure:
23 description:
24 - Allow insecure repositories.
25 type: bool
26 allow_weak:
27 description:
28 - Allow repositories signed with a key using a weak digest algorithm.
29 type: bool
30 architectures:
31 description:
32 - Architectures to search within repository.
33 type: list
34 elements: str
35 by_hash:
36 description:
37 - Controls if APT should try to acquire indexes via a URI constructed
38 from a hashsum of the expected file instead of using the well-known
39 stable filename of the index.
40 type: bool
41 check_date:
42 description:
43 - Controls if APT should consider the machine's time correct and hence
44 perform time related checks, such as verifying that a Release file
45 is not from the future.
46 type: bool
47 check_valid_until:
48 description:
49 - Controls if APT should try to detect replay attacks.
50 type: bool
51 components:
52 description:
53 - Components specify different sections of one distribution version
54 present in a C(Suite).
55 type: list
56 elements: str
57 date_max_future:
58 description:
59 - Controls how far from the future a repository may be.
60 type: int
61 enabled:
62 description:
63 - Tells APT whether the source is enabled or not.
64 type: bool
65 exclude:
66 description:
67 - Controls which packages C(APT) should exclude from the repository.
68 - Mutually exclusive with O(include).
69 - This option is supported by apt>=3.1.0.
70 type: list
71 elements: str
72 version_added: '2.21'
73 include:
74 description:
75 - Controls which packages C(APT) should use from the repository.
76 - Mutually exclusive with O(exclude).
77 - This option is supported by apt>=3.1.0.
78 type: list
79 elements: str
80 version_added: '2.21'
81 inrelease_path:
82 description:
83 - Determines the path to the C(InRelease) file, relative to the normal
84 position of an C(InRelease) file.
85 type: str
86 install_python_debian:
87 description:
88 - Whether to automatically try to install the Python C(debian) library or not, if it is not already installed.
89 Without this library, the module does not work.
90 - Runs C(apt install python3-debian).
91 - Only works with the system Python. If you are using a Python on the remote that is not
92 the system Python, set O(install_python_debian=false) and ensure that the Python C(debian) library
93 for your Python version is installed some other way.
94 type: bool
95 default: false
96 version_added: '2.20'
97 languages:
98 description:
99 - Defines which languages information such as translated
100 package descriptions should be downloaded.
101 type: list
102 elements: str
103 name:
104 description:
105 - Name of the repo. Specifically used for C(X-Repolib-Name) and in
106 naming the repository and signing key files.
107 required: true
108 type: str
109 pdiffs:
110 description:
111 - Controls if APT should try to use C(PDiffs) to update old indexes
112 instead of downloading the new indexes entirely.
113 type: bool
114 signed_by:
115 description:
116 - Either a URL to a GPG key, absolute path to a keyring file, one or
117 more fingerprints of keys either in the C(trusted.gpg) keyring or in
118 the keyrings in the C(trusted.gpg.d/) directory, or an ASCII armored
119 GPG public key block.
120 type: str
121 suites:
122 description:
123 - >-
124 Suite can specify an exact path in relation to the URI(s) provided,
125 in which case the Components: must be omitted and suite must end
126 with a slash (C(/)). Alternatively, it may take the form of a
127 distribution version (for example a version codename like C(disco) or C(artful)).
128 If the suite does not specify a path, at least one component must
129 be present.
130 type: list
131 elements: str
132 targets:
133 description:
134 - Defines which download targets apt will try to acquire from this source.
135 type: list
136 elements: str
137 trusted:
138 description:
139 - Decides if a source is considered trusted or if warnings should be
140 raised before, for example packages are installed from this source.
141 type: bool
142 types:
143 choices:
144 - deb
145 - deb-src
146 default:
147 - deb
148 type: list
149 elements: str
150 description:
151 - Which types of packages to look for from a given source; either
152 binary V(deb) or source code V(deb-src).
153 uris:
154 description:
155 - The URIs must specify the base of the Debian distribution archive,
156 from which APT finds the information it needs.
157 type: list
158 elements: str
159 mode:
160 description:
161 - The octal mode for newly created files in C(sources.list.d).
162 type: raw
163 default: '0644'
164 state:
165 description:
166 - A source string state.
167 type: str
168 choices:
169 - absent
170 - present
171 default: present
172 requirements:
173 - python3-debian / python-debian
174 version_added: '2.15'
175 """
176
177 EXAMPLES = """
178 - name: Add debian repo
179 deb822_repository:
180 name: debian
181 types: deb
182 uris: http://deb.debian.org/debian
183 suites: stretch
184 components:
185 - main
186 - contrib
187 - non-free
188
189 - name: Add debian repo with key
190 deb822_repository:
191 name: debian
192 types: deb
193 uris: https://deb.debian.org
194 suites: stable
195 components:
196 - main
197 - contrib
198 - non-free
199 signed_by: |-
200 -----BEGIN PGP PUBLIC KEY BLOCK-----
201
202 mDMEYCQjIxYJKwYBBAHaRw8BAQdAD/P5Nvvnvk66SxBBHDbhRml9ORg1WV5CvzKY
203 CuMfoIS0BmFiY2RlZoiQBBMWCgA4FiEErCIG1VhKWMWo2yfAREZd5NfO31cFAmAk
204 IyMCGyMFCwkIBwMFFQoJCAsFFgIDAQACHgECF4AACgkQREZd5NfO31fbOwD6ArzS
205 dM0Dkd5h2Ujy1b6KcAaVW9FOa5UNfJ9FFBtjLQEBAJ7UyWD3dZzhvlaAwunsk7DG
206 3bHcln8DMpIJVXht78sL
207 =IE0r
208 -----END PGP PUBLIC KEY BLOCK-----
209
210 - name: Add repo using key from URL
211 deb822_repository:
212 name: example
213 types: deb
214 uris: https://download.example.com/linux/ubuntu
215 suites: '{{ ansible_distribution_release }}'
216 components: stable
217 architectures: amd64
218 signed_by: https://download.example.com/linux/ubuntu/gpg
219 """
220
221 RETURN = """
222 repo:
223 description: A source string for the repository
224 returned: always
225 type: str
226 sample: |
227 X-Repolib-Name: debian
228 Types: deb
229 URIs: https://deb.debian.org
230 Suites: stable
231 Components: main contrib non-free
232 Signed-By:
233 -----BEGIN PGP PUBLIC KEY BLOCK-----
234 .
235 mDMEYCQjIxYJKwYBBAHaRw8BAQdAD/P5Nvvnvk66SxBBHDbhRml9ORg1WV5CvzKY
236 CuMfoIS0BmFiY2RlZoiQBBMWCgA4FiEErCIG1VhKWMWo2yfAREZd5NfO31cFAmAk
237 IyMCGyMFCwkIBwMFFQoJCAsFFgIDAQACHgECF4AACgkQREZd5NfO31fbOwD6ArzS
238 dM0Dkd5h2Ujy1b6KcAaVW9FOa5UNfJ9FFBtjLQEBAJ7UyWD3dZzhvlaAwunsk7DG
239 3bHcln8DMpIJVXht78sL
240 =IE0r
241 -----END PGP PUBLIC KEY BLOCK-----
242
243 dest:
244 description: Path to the repository file
245 returned: always
246 type: str
247 sample: /etc/apt/sources.list.d/focal-archive.sources
248
249 key_filename:
250 description: Path to the signed_by key file
251 returned: always
252 type: str
253 sample: /etc/apt/keyrings/debian.gpg
254 """
255
256 import os
257 import re
258 import sys
259 import tempfile
260 import textwrap
261
262 from ansible.module_utils.basic import AnsibleModule
263 from ansible.module_utils.basic import missing_required_lib
264 from ansible.module_utils.common.collections import is_sequence
265 from ansible.module_utils.common.file import S_IRWXU_RXG_RXO, S_IRWU_RG_RO
266 from ansible.module_utils.common.respawn import has_respawned, probe_interpreters_for_module, respawn_module
267 from ansible.module_utils.common.text.converters import to_bytes
268 from ansible.module_utils.common.text.converters import to_native
269 from ansible.module_utils.urls import generic_urlparse
270 from ansible.module_utils.urls import open_url
271 from ansible.module_utils.urls import get_user_agent
272 from ansible.module_utils.urls import urlparse
273
274 HAS_DEBIAN = True
275 DEBIAN_IMP_ERR = None
276 try:
277 from debian.deb822 import Deb822 # type: ignore[import]
278 except ImportError as ex:
279 HAS_DEBIAN = False
280 DEBIAN_IMP_ERR = ex
281
282 KEYRINGS_DIR = '/etc/apt/keyrings'
283
284
285 def ensure_keyrings_dir(module):
286 changed = False
287 if not os.path.isdir(KEYRINGS_DIR):
288 if not module.check_mode:
289 os.mkdir(KEYRINGS_DIR, S_IRWXU_RXG_RXO)
290 changed |= True
291
292 changed |= module.set_fs_attributes_if_different(
293 {
294 'path': KEYRINGS_DIR,
295 'secontext': [None, None, None],
296 'owner': 'root',
297 'group': 'root',
298 'mode': '0755',
299 'attributes': None,
300 },
301 changed,
302 )
303
304 return changed
305
306
307 def make_signed_by_filename(slug, ext):
308 return os.path.join(KEYRINGS_DIR, '%s.%s' % (slug, ext))
309
310
311 def make_sources_filename(slug):
312 return os.path.join(
313 '/etc/apt/sources.list.d',
314 '%s.sources' % slug
315 )
316
317
318 def format_bool(v):
319 return 'yes' if v else 'no'
320
321
322 def format_list(v):
323 return ' '.join(v)
324
325
326 def format_multiline(v):
327 return '\n' + textwrap.indent(
328 '\n'.join(line.strip() or '.' for line in v.strip().splitlines()),
329 ' '
330 )
331
332
333 def format_field_name(v):
334 if v == 'name':
335 return 'X-Repolib-Name'
336 elif v == 'uris':
337 return 'URIs'
338 return v.replace('_', '-').title()
339
340
341 def is_armored(b_data):
342 return b'-----BEGIN PGP PUBLIC KEY BLOCK-----' in b_data
343
344
345 def write_signed_by_key(module, v, slug):
346 changed = False
347 if os.path.isfile(v):
348 return changed, v, None
349
350 b_data = None
351
352 parts = generic_urlparse(urlparse(v))
353 if parts.scheme:
354 try:
355 r = open_url(v, http_agent=get_user_agent())
356 except Exception as exc:
357 raise RuntimeError('Could not fetch signed_by key.') from exc
358 else:
359 b_data = r.read()
360 else:
361 # Not a file, nor a URL, just pass it through
362 return changed, None, v
363
364 if not b_data:
365 return changed, v, None
366
367 tmpfd, tmpfile = tempfile.mkstemp(dir=module.tmpdir)
368 with os.fdopen(tmpfd, 'wb') as f:
369 f.write(b_data)
370
371 ext = 'asc' if is_armored(b_data) else 'gpg'
372 filename = make_signed_by_filename(slug, ext)
373
374 src_chksum = module.sha256(tmpfile)
375 dest_chksum = module.sha256(filename)
376
377 if src_chksum != dest_chksum:
378 changed |= ensure_keyrings_dir(module)
379 if not module.check_mode:
380 module.atomic_move(tmpfile, filename)
381 changed |= True
382
383 changed |= module.set_mode_if_different(filename, S_IRWU_RG_RO, False)
384
385 return changed, filename, None
386
387
388 def install_python_debian(module, deb_pkg_name):
389
390 if not module.check_mode:
391 apt_path = module.get_bin_path('apt', required=True)
392 if apt_path:
393 rc, so, se = module.run_command([apt_path, 'update'])
394 if rc != 0:
395 module.fail_json(msg=f"Failed update while auto installing {deb_pkg_name} due to '{se.strip()}'")
396 rc, so, se = module.run_command([apt_path, 'install', deb_pkg_name, '-y', '-q'])
397 if rc != 0:
398 module.fail_json(msg=f"Failed to auto-install {deb_pkg_name} due to : '{se.strip()}'")
399 else:
400 module.fail_json(msg=f"{deb_pkg_name} must be installed to use check mode")
401
402
403 def main():
404 module = AnsibleModule(
405 argument_spec={
406 'allow_downgrade_to_insecure': {
407 'type': 'bool',
408 },
409 'allow_insecure': {
410 'type': 'bool',
411 },
412 'allow_weak': {
413 'type': 'bool',
414 },
415 'architectures': {
416 'elements': 'str',
417 'type': 'list',
418 },
419 'by_hash': {
420 'type': 'bool',
421 },
422 'check_date': {
423 'type': 'bool',
424 },
425 'check_valid_until': {
426 'type': 'bool',
427 },
428 'components': {
429 'elements': 'str',
430 'type': 'list',
431 },
432 'date_max_future': {
433 'type': 'int',
434 },
435 'enabled': {
436 'type': 'bool',
437 },
438 'exclude': {
439 'elements': 'str',
440 'type': 'list',
441 },
442 'include': {
443 'elements': 'str',
444 'type': 'list',
445 },
446 'inrelease_path': {
447 'type': 'str',
448 },
449 'install_python_debian': {
450 'type': 'bool',
451 'default': False,
452 },
453 'languages': {
454 'elements': 'str',
455 'type': 'list',
456 },
457 'name': {
458 'type': 'str',
459 'required': True,
460 },
461 'pdiffs': {
462 'type': 'bool',
463 },
464 'signed_by': {
465 'type': 'str',
466 },
467 'suites': {
468 'elements': 'str',
469 'type': 'list',
470 },
471 'targets': {
472 'elements': 'str',
473 'type': 'list',
474 },
475 'trusted': {
476 'type': 'bool',
477 },
478 'types': {
479 'choices': [
480 'deb',
481 'deb-src',
482 ],
483 'elements': 'str',
484 'type': 'list',
485 'default': [
486 'deb',
487 ]
488 },
489 'uris': {
490 'elements': 'str',
491 'type': 'list',
492 },
493 # non-deb822 args
494 'mode': {
495 'type': 'raw',
496 'default': '0644',
497 },
498 'state': {
499 'type': 'str',
500 'choices': [
501 'present',
502 'absent',
503 ],
504 'default': 'present',
505 },
506 },
507 mutually_exclusive=[
508 ['exclude', 'include']
509 ],
510 supports_check_mode=True,
511 )
512
513 if not HAS_DEBIAN:
514 deb_pkg_name = 'python3-debian'
515 # This interpreter can't see the debian Python library- we'll do the following to try and fix that as per
516 # the apt_repository module:
517 # 1) look in common locations for system-owned interpreters that can see it; if we find one, respawn under it
518 # 2) finding none, try to install a matching python-debian package for the current interpreter version;
519 # we limit to the current interpreter version to try and avoid installing a whole other Python just
520 # for deb support
521 # 3) if we installed a support package, try to respawn under what we think is the right interpreter (could be
522 # the current interpreter again, but we'll let it respawn anyway for simplicity)
523 # 4) if still not working, return an error and give up (some corner cases not covered, but this shouldn't be
524 # made any more complex than it already is to try and cover more, eg, custom interpreters taking over
525 # system locations)
526
527 if has_respawned():
528 # this shouldn't be possible; short-circuit early if it happens...
529 module.fail_json(msg=f"{deb_pkg_name} must be installed and visible from {sys.executable}.")
530
531 interpreters = ['/usr/bin/python3', '/usr/bin/python']
532
533 interpreter = probe_interpreters_for_module(interpreters, 'debian')
534
535 if interpreter:
536 # found the Python bindings; respawn this module under the interpreter where we found them
537 respawn_module(interpreter)
538 # this is the end of the line for this process, it will exit here once the respawned module has completed
539
540 # don't make changes if we're in check_mode
541 if module.check_mode:
542 module.fail_json(msg=f"{deb_pkg_name} must be installed to use check mode. If run with install_python_debian, this module can auto-install it.")
543
544 if module.params['install_python_debian']:
545 install_python_debian(module, deb_pkg_name)
546 else:
547 module.fail_json(msg=f'{deb_pkg_name} is not installed, and install_python_debian is False')
548
549 # try again to find the bindings in common places
550 interpreter = probe_interpreters_for_module(interpreters, 'debian')
551
552 if interpreter:
553 # found the Python bindings; respawn this module under the interpreter where we found them
554 # NB: respawn is somewhat wasteful if it's this interpreter, but simplifies the code
555 respawn_module(interpreter)
556 # this is the end of the line for this process, it will exit here once the respawned module has completed
557 else:
558 # we've done all we can do; just tell the user it's busted and get out
559 module.fail_json(msg=missing_required_lib(deb_pkg_name),
560 exception=DEBIAN_IMP_ERR)
561
562 check_mode = module.check_mode
563
564 changed = False
565
566 # Make a copy, so we don't mutate module.params to avoid future issues
567 params = module.params.copy()
568
569 # popped non-deb822 args
570 mode = params.pop('mode')
571 state = params.pop('state')
572 params.pop('install_python_debian')
573
574 name = params['name']
575 # Generate legacy-normalized slug for backward compatibility check
576 legacy_slug = re.sub(
577 r'[^a-z0-9-]+',
578 '',
579 re.sub(r'[_\s]+', '-', name.lower()),
580 )
581 legacy_sources = make_sources_filename(legacy_slug)
582
583 if os.path.exists(legacy_sources):
584 # Legacy file exists, reuse the old naming to maintain consistency
585 slug = legacy_slug
586 else:
587 # No legacy file, use the new naming convention
588 slug = name.replace(' ', '-')
589 sources_filename = make_sources_filename(slug)
590
591 if state == 'absent':
592 if os.path.exists(sources_filename):
593 if not check_mode:
594 os.unlink(sources_filename)
595 changed |= True
596 for ext in ('asc', 'gpg'):
597 signed_by_filename = make_signed_by_filename(slug, ext)
598 if os.path.exists(signed_by_filename):
599 if not check_mode:
600 os.unlink(signed_by_filename)
601 changed = True
602 module.exit_json(
603 repo=None,
604 changed=changed,
605 dest=sources_filename,
606 key_filename=signed_by_filename,
607 )
608
609 deb822 = Deb822()
610 signed_by_filename = None
611 for key, value in sorted(params.items()):
612 if value is None:
613 continue
614
615 if isinstance(value, bool):
616 value = format_bool(value)
617 elif isinstance(value, int):
618 value = to_native(value)
619 elif is_sequence(value):
620 value = format_list(value)
621 elif key == 'signed_by':
622 key_changed, signed_by_filename, signed_by_data = write_signed_by_key(module, value, slug)
623 value = signed_by_filename or signed_by_data
624 changed |= key_changed
625
626 if value.count('\n') > 0:
627 value = format_multiline(value)
628
629 deb822[format_field_name(key)] = value
630
631 repo = deb822.dump()
632 tmpfd, tmpfile = tempfile.mkstemp(dir=module.tmpdir)
633 with os.fdopen(tmpfd, 'wb') as f:
634 f.write(to_bytes(repo))
635
636 sources_filename = make_sources_filename(slug)
637
638 src_chksum = module.sha256(tmpfile)
639 dest_chksum = module.sha256(sources_filename)
640
641 if src_chksum != dest_chksum:
642 if not check_mode:
643 module.atomic_move(tmpfile, sources_filename)
644 changed |= True
645
646 changed |= module.set_mode_if_different(sources_filename, mode, False)
647
648 module.exit_json(
649 repo=repo,
650 changed=changed,
651 dest=sources_filename,
652 key_filename=signed_by_filename,
653 )
654
655
656 if __name__ == '__main__':
657 main()