Debian Codegraph @

lib/ansible/modules/yum_repository.py

raw
1 # encoding: utf-8
2
3 # (c) 2015-2016, Jiri Tyr <[email protected]>
4 #
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import annotations
8
9 DOCUMENTATION = """
10 ---
11 module: yum_repository
12 author: Jiri Tyr (@jtyr)
13 version_added: '2.1'
14 short_description: Add or remove YUM repositories
15 description:
16 - Add or remove YUM repositories in RPM-based Linux distributions.
17 - If you wish to update an existing repository definition use M(community.general.ini_file) instead.
18
19 options:
20 bandwidth:
21 description:
22 - Maximum available network bandwidth in bytes/second. Used with the
23 O(throttle) option.
24 - If O(throttle) is a percentage and bandwidth is V(0) then bandwidth
25 throttling will be disabled. If O(throttle) is expressed as a data rate
26 (bytes/sec) then this option is ignored. Default is V(0) (no bandwidth
27 throttling).
28 type: str
29 baseurl:
30 description:
31 - URL to the directory where the yum repository's 'repodata' directory
32 lives.
33 - It can also be a list of multiple URLs.
34 - This, the O(metalink) or O(mirrorlist) parameters are required if O(state) is set to
35 V(present).
36 type: list
37 elements: str
38 cost:
39 description:
40 - Relative cost of accessing this repository. Useful for weighing one
41 repo's packages as greater/less than any other.
42 type: str
43 countme:
44 description:
45 - Whether a special flag should be added to a randomly chosen metalink/mirrorlist query each week.
46 This allows the repository owner to estimate the number of systems consuming it.
47 default: ~
48 type: bool
49 version_added: '2.18'
50 deltarpm_percentage:
51 description:
52 - When the relative size of delta vs pkg is larger than this, delta is
53 not used. Use V(0) to turn off delta rpm processing. Local repositories
54 (with file://O(baseurl)) have delta rpms turned off by default.
55 type: str
56 description:
57 description:
58 - A human-readable string describing the repository. This option corresponds to the C(name) property in the repo file.
59 - This parameter is only required if O(state=present).
60 type: str
61 enabled:
62 description:
63 - This tells yum whether or not use this repository.
64 - Yum default value is V(true).
65 type: bool
66 enablegroups:
67 description:
68 - Determines whether yum will allow the use of package groups for this
69 repository.
70 - Yum default value is V(true).
71 type: bool
72 exclude:
73 description:
74 - List of packages to exclude from updates or installs. This should be a
75 space separated list. Shell globs using wildcards (for example V(*) and V(?))
76 are allowed.
77 - The list can also be a regular YAML array.
78 - O(excludepkgs) alias was added in ansible-core 2.18.
79 type: list
80 elements: str
81 aliases:
82 - excludepkgs
83 failovermethod:
84 choices: [roundrobin, priority]
85 description:
86 - V(roundrobin) randomly selects a URL out of the list of URLs to start
87 with and proceeds through each of them as it encounters a failure
88 contacting the host.
89 - V(priority) starts from the first O(baseurl) listed and reads through
90 them sequentially.
91 type: str
92 file:
93 description:
94 - File name without the C(.repo) extension to save the repo in. Defaults
95 to the value of O(name).
96 type: str
97 gpgcheck:
98 description:
99 - Tells yum whether or not it should perform a GPG signature check on
100 packages.
101 - No default setting. If the value is not set, the system setting from
102 C(/etc/yum.conf) or system default of V(false) will be used.
103 type: bool
104 gpgkey:
105 description:
106 - A URL pointing to the ASCII-armored GPG key file for the repository.
107 - It can also be a list of multiple URLs.
108 type: list
109 elements: str
110 module_hotfixes:
111 description:
112 - Disable module RPM filtering and make all RPMs from the repository
113 available. The default is V(null).
114 version_added: '2.11'
115 type: bool
116 include:
117 description:
118 - Include external configuration file. Both, local path and URL is
119 supported. Configuration file will be inserted at the position of the
120 C(include=) line. Included files may contain further include lines.
121 Yum will abort with an error if an inclusion loop is detected.
122 type: str
123 includepkgs:
124 description:
125 - List of packages you want to only use from a repository. This should be
126 a space separated list. Shell globs using wildcards (for example V(*) and V(?))
127 are allowed. Substitution variables (for example V($releasever)) are honored
128 here.
129 - The list can also be a regular YAML array.
130 type: list
131 elements: str
132 ip_resolve:
133 description:
134 - Determines how yum resolves host names.
135 - V(4) or V(IPv4) - resolve to IPv4 addresses only.
136 - V(6) or V(IPv6) - resolve to IPv6 addresses only.
137 choices: ['4', '6', IPv4, IPv6, whatever]
138 type: str
139 metadata_expire:
140 description:
141 - Time (in seconds) after which the metadata will expire.
142 - Default value is 6 hours.
143 type: str
144 metalink:
145 description:
146 - Specifies a URL to a metalink file for the repomd.xml, a list of
147 mirrors for the entire repository are generated by converting the
148 mirrors for the repomd.xml file to a O(baseurl).
149 - This, the O(baseurl) or O(mirrorlist) parameters are required if O(state) is set to
150 V(present).
151 type: str
152 mirrorlist:
153 description:
154 - Specifies a URL to a file containing a list of baseurls.
155 - This, the O(baseurl) or O(metalink) parameters are required if O(state) is set to
156 V(present).
157 type: str
158 name:
159 description:
160 - Unique repository ID. This option builds the section name of the repository in the repo file.
161 - This parameter is only required if O(state) is set to V(present) or
162 V(absent).
163 type: str
164 required: true
165 password:
166 description:
167 - Password to use with the username for basic authentication.
168 type: str
169 priority:
170 description:
171 - Enforce ordered protection of repositories. The value is an integer
172 from 1 to 99.
173 - This option only works if the YUM Priorities plugin is installed.
174 type: str
175 proxy:
176 description:
177 - URL to the proxy server that yum should use. Set to V(_none_) to
178 disable the global proxy setting.
179 type: str
180 proxy_password:
181 description:
182 - Password for this proxy.
183 type: str
184 proxy_username:
185 description:
186 - Username to use for proxy.
187 type: str
188 repo_gpgcheck:
189 description:
190 - This tells yum whether or not it should perform a GPG signature check
191 on the repodata from this repository.
192 type: bool
193 reposdir:
194 description:
195 - Directory where the C(.repo) files will be stored.
196 type: path
197 default: /etc/yum.repos.d
198 retries:
199 description:
200 - Set the number of times any attempt to retrieve a file should retry
201 before returning an error. Setting this to V(0) makes yum try forever.
202 type: str
203 s3_enabled:
204 description:
205 - Enables support for S3 repositories.
206 - This option only works if the YUM S3 plugin is installed.
207 type: bool
208 skip_if_unavailable:
209 description:
210 - If set to V(true) yum will continue running if this repository cannot be
211 contacted for any reason. This should be set carefully as all repos are
212 consulted for any given command.
213 type: bool
214 sslcacert:
215 description:
216 - Path to the directory containing the databases of the certificate
217 authorities yum should use to verify SSL certificates.
218 type: str
219 aliases: [ ca_cert ]
220 sslclientcert:
221 description:
222 - Path to the SSL client certificate yum should use to connect to
223 repos/remote sites.
224 type: str
225 aliases: [ client_cert ]
226 sslclientkey:
227 description:
228 - Path to the SSL client key yum should use to connect to repos/remote
229 sites.
230 type: str
231 aliases: [ client_key ]
232 sslverify:
233 description:
234 - Defines whether yum should verify SSL certificates/hosts at all.
235 type: bool
236 aliases: [ validate_certs ]
237 state:
238 description:
239 - State of the repo file.
240 choices: [absent, present]
241 type: str
242 default: present
243 throttle:
244 description:
245 - Enable bandwidth throttling for downloads.
246 - This option can be expressed as a absolute data rate in bytes/sec. An
247 SI prefix (k, M or G) may be appended to the bandwidth value.
248 type: str
249 timeout:
250 description:
251 - Number of seconds to wait for a connection before timing out.
252 type: str
253 username:
254 description:
255 - Username to use for basic authentication to a repo or really any url.
256 type: str
257
258 extends_documentation_fragment:
259 - action_common_attributes
260 - files
261 attributes:
262 check_mode:
263 support: full
264 diff_mode:
265 support: full
266 platform:
267 platforms: rhel
268 notes:
269 - All comments will be removed if modifying an existing repo file.
270 - Section order is preserved in an existing repo file.
271 - Parameters in a section are ordered alphabetically in an existing repo
272 file.
273 - The repo file will be automatically deleted if it contains no repository.
274 - When removing a repository, beware that the metadata cache may still remain
275 on disk until you run C(yum clean all). Use a notification handler for this.
276 - "The O(ignore:params) parameter was removed in Ansible 2.5 due to circumventing Ansible's parameter
277 handling"
278 """
279
280 EXAMPLES = """
281 - name: Add repository
282 ansible.builtin.yum_repository:
283 name: epel
284 description: EPEL YUM repo
285 baseurl: https://download.fedoraproject.org/pub/epel/$releasever/$basearch/
286
287 - name: Add multiple repositories into the same file (1/2)
288 ansible.builtin.yum_repository:
289 name: epel
290 description: EPEL YUM repo
291 file: external_repos
292 baseurl: https://download.fedoraproject.org/pub/epel/$releasever/$basearch/
293 gpgcheck: no
294
295 - name: Add multiple repositories into the same file (2/2)
296 ansible.builtin.yum_repository:
297 name: rpmforge
298 description: RPMforge YUM repo
299 file: external_repos
300 baseurl: http://apt.sw.be/redhat/el7/en/$basearch/rpmforge
301 mirrorlist: http://mirrorlist.repoforge.org/el7/mirrors-rpmforge
302 enabled: no
303
304 # Handler showing how to clean yum metadata cache
305 - name: yum-clean-metadata
306 ansible.builtin.command: yum clean metadata
307
308 # Example removing a repository and cleaning up metadata cache
309 - name: Remove repository (and clean up left-over metadata)
310 ansible.builtin.yum_repository:
311 name: epel
312 state: absent
313 notify: yum-clean-metadata
314
315 - name: Remove repository from a specific repo file
316 ansible.builtin.yum_repository:
317 name: epel
318 file: external_repos
319 state: absent
320 """
321
322 RETURN = """
323 repo:
324 description: repository name
325 returned: success
326 type: str
327 sample: "epel"
328 state:
329 description: state of the target, after execution
330 returned: success
331 type: str
332 sample: "present"
333 """
334
335 import configparser
336 import os
337
338 from ansible.module_utils.basic import AnsibleModule, FILE_COMMON_ARGUMENTS
339 from ansible.module_utils.common.text.converters import to_native
340
341
342 class YumRepo:
343 def __init__(self, module, params, repoid, dest):
344 self.module = module
345 self.params = params
346 self.section = repoid
347 self.repofile = configparser.RawConfigParser()
348 self.dest = dest
349 if os.path.isfile(dest):
350 self.repofile.read(dest)
351
352 def add(self):
353 self.remove()
354 self.repofile.add_section(self.section)
355
356 for key, value in sorted(self.params.items()):
357 if value is None:
358 continue
359 if isinstance(value, bool):
360 value = str(int(value))
361 self.repofile.set(self.section, key, value)
362
363 def save(self):
364 if self.repofile.sections():
365 try:
366 with open(self.dest, 'w') as fd:
367 self.repofile.write(fd)
368 except OSError as ex:
369 self.module.fail_json(
370 msg=f"Problems handling file {self.dest!r}.",
371 details=str(ex),
372 exception=ex,
373 )
374 else:
375 try:
376 os.remove(self.dest)
377 except OSError as e:
378 self.module.fail_json(
379 msg=f"Cannot remove empty repo file {self.dest}.",
380 details=to_native(e),
381 )
382
383 def remove(self):
384 self.repofile.remove_section(self.section)
385
386 def dump(self):
387 repo_string = ""
388
389 for section in sorted(self.repofile.sections()):
390 repo_string += "[%s]\n" % section
391
392 for key, value in sorted(self.repofile.items(section)):
393 repo_string += "%s = %s\n" % (key, value)
394
395 repo_string += "\n"
396
397 return repo_string
398
399
400 def main():
401 argument_spec = dict(
402 bandwidth=dict(),
403 baseurl=dict(type='list', elements='str'),
404 cost=dict(),
405 countme=dict(type='bool'),
406 deltarpm_percentage=dict(),
407 description=dict(),
408 enabled=dict(type='bool'),
409 enablegroups=dict(type='bool'),
410 exclude=dict(type='list', elements='str', aliases=['excludepkgs']),
411 failovermethod=dict(choices=['roundrobin', 'priority']),
412 file=dict(),
413 gpgcheck=dict(type='bool'),
414 gpgkey=dict(type='list', elements='str', no_log=False),
415 module_hotfixes=dict(type='bool'),
416 include=dict(),
417 includepkgs=dict(type='list', elements='str'),
418 ip_resolve=dict(choices=['4', '6', 'IPv4', 'IPv6', 'whatever']),
419 metadata_expire=dict(),
420 metalink=dict(),
421 mirrorlist=dict(),
422 name=dict(required=True),
423 password=dict(no_log=True),
424 priority=dict(),
425 proxy=dict(),
426 proxy_password=dict(no_log=True),
427 proxy_username=dict(),
428 repo_gpgcheck=dict(type='bool'),
429 reposdir=dict(default='/etc/yum.repos.d', type='path'),
430 retries=dict(),
431 s3_enabled=dict(type='bool'),
432 skip_if_unavailable=dict(type='bool'),
433 sslcacert=dict(aliases=['ca_cert']),
434 sslclientcert=dict(aliases=['client_cert']),
435 sslclientkey=dict(aliases=['client_key'], no_log=False),
436 sslverify=dict(type='bool', aliases=['validate_certs']),
437 state=dict(choices=['present', 'absent'], default='present'),
438 throttle=dict(),
439 timeout=dict(),
440 username=dict(),
441 )
442
443 module = AnsibleModule(
444 required_if=[
445 ["state", "present", ["baseurl", "mirrorlist", "metalink"], True],
446 ["state", "present", ["description"]],
447 ],
448 argument_spec=argument_spec,
449 add_file_common_args=True,
450 supports_check_mode=True,
451 )
452
453 # make copy of params as we need to split them into yum repo only and file params
454 yum_repo_params = module.params.copy()
455 for alias in module.aliases:
456 yum_repo_params.pop(alias, None)
457
458 file_common_params = {}
459 for param in FILE_COMMON_ARGUMENTS:
460 file_common_params[param] = yum_repo_params.pop(param)
461
462 state = yum_repo_params.pop("state")
463 name = yum_repo_params['name']
464 yum_repo_params['name'] = yum_repo_params.pop('description')
465
466 for list_param in ('baseurl', 'gpgkey'):
467 v = yum_repo_params[list_param]
468 if v is not None:
469 yum_repo_params[list_param] = '\n'.join(v)
470
471 for list_param in ('exclude', 'includepkgs'):
472 v = yum_repo_params[list_param]
473 if v is not None:
474 yum_repo_params[list_param] = ' '.join(v)
475
476 repos_dir = yum_repo_params.pop("reposdir")
477 if not os.path.isdir(repos_dir):
478 module.fail_json(
479 msg="Repo directory '%s' does not exist." % repos_dir
480 )
481
482 if (file := yum_repo_params.pop("file")) is None:
483 file = name
484 file_common_params["dest"] = os.path.join(repos_dir, f"{file}.repo")
485
486 yumrepo = YumRepo(module, yum_repo_params, name, file_common_params["dest"])
487
488 diff = {
489 'before_header': file_common_params["dest"],
490 'before': yumrepo.dump(),
491 'after_header': file_common_params["dest"],
492 'after': ''
493 }
494
495 if state == 'present':
496 yumrepo.add()
497 elif state == 'absent':
498 yumrepo.remove()
499
500 diff['after'] = yumrepo.dump()
501
502 changed = diff['before'] != diff['after']
503
504 if not module.check_mode and changed:
505 yumrepo.save()
506
507 if os.path.isfile(file_common_params["dest"]):
508 file_args = module.load_file_common_arguments(file_common_params)
509 changed = module.set_fs_attributes_if_different(file_args, changed)
510
511 module.exit_json(changed=changed, repo=name, state=state, diff=diff)
512
513
514 if __name__ == '__main__':
515 main()