Debian Codegraph @

ansible_collections/community/general/plugins/modules/pulp_repo.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2016, Joe Adams <@sysadmind>
4 #
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import annotations
9
10 DOCUMENTATION = r"""
11 module: pulp_repo
12 author: "Joe Adams (@sysadmind)"
13 short_description: Add or remove Pulp repos from a remote host
14 description:
15 - Add or remove Pulp repos from a remote host.
16 - Note, this is for Pulp 2 only.
17 attributes:
18 check_mode:
19 support: full
20 diff_mode:
21 support: none
22 options:
23 add_export_distributor:
24 description:
25 - Whether or not to add the export distributor to new C(rpm) repositories.
26 type: bool
27 default: false
28 feed:
29 description:
30 - Upstream feed URL to receive updates from.
31 type: str
32 force_basic_auth:
33 description:
34 - C(httplib2), the library used by the M(ansible.builtin.uri) module only sends authentication information when a webservice
35 responds to an initial request with a 401 status. Since some basic auth services do not properly send a 401, logins
36 fail. This option forces the sending of the Basic authentication header upon initial request.
37 type: bool
38 default: false
39 generate_sqlite:
40 description:
41 - Boolean flag to indicate whether sqlite files should be generated during a repository publish.
42 type: bool
43 default: false
44 feed_ca_cert:
45 description:
46 - CA certificate string used to validate the feed source SSL certificate. This can be the file content or the path to
47 the file.
48 type: str
49 aliases: [importer_ssl_ca_cert]
50 feed_client_cert:
51 description:
52 - Certificate used as the client certificate when synchronizing the repository. This is used to communicate authentication
53 information to the feed source. The value to this option must be the full path to the certificate. The specified file
54 may be the certificate itself or a single file containing both the certificate and private key. This can be the file
55 content or the path to the file.
56 type: str
57 aliases: [importer_ssl_client_cert]
58 feed_client_key:
59 description:
60 - Private key to the certificate specified in O(feed_client_cert), assuming it is not included in the certificate file
61 itself. This can be the file content or the path to the file.
62 type: str
63 aliases: [importer_ssl_client_key]
64 name:
65 description:
66 - Name of the repo to add or remove. This correlates to repo-id in Pulp.
67 required: true
68 type: str
69 aliases: [repo]
70 proxy_host:
71 description:
72 - Proxy URL setting for the pulp repository importer. This is in the format V(scheme://host).
73 default:
74 type: str
75 proxy_port:
76 description:
77 - Proxy port setting for the pulp repository importer.
78 default:
79 type: str
80 proxy_username:
81 description:
82 - Proxy username for the pulp repository importer.
83 default:
84 type: str
85 proxy_password:
86 description:
87 - Proxy password for the pulp repository importer.
88 default:
89 type: str
90 publish_distributor:
91 description:
92 - Distributor to use when O(state=publish). The default is to publish all distributors.
93 type: str
94 pulp_host:
95 description:
96 - URL of the pulp server to connect to.
97 default: https://127.0.0.1
98 type: str
99 relative_url:
100 description:
101 - Relative URL for the local repository. It's required when state=present.
102 type: str
103 repo_type:
104 description:
105 - Repo plugin type to use (that is, V(rpm), V(docker)).
106 default: rpm
107 type: str
108 repoview:
109 description:
110 - Whether to generate repoview files for a published repository. Setting this to V(true) automatically activates O(generate_sqlite).
111 type: bool
112 default: false
113 serve_http:
114 description:
115 - Make the repo available over HTTP.
116 type: bool
117 default: false
118 serve_https:
119 description:
120 - Make the repo available over HTTPS.
121 type: bool
122 default: true
123 state:
124 description:
125 - The repo state. A state of V(sync) queues a sync of the repo. This is asynchronous but not delayed like a scheduled
126 sync. A state of V(publish) uses the repository's distributor to publish the content.
127 default: present
128 choices: ["present", "absent", "sync", "publish"]
129 type: str
130 url_password:
131 description:
132 - The password for use in HTTP basic authentication to the pulp API. If the O(url_username) parameter is not specified,
133 the O(url_password) parameter is not used.
134 url_username:
135 description:
136 - The username for use in HTTP basic authentication to the pulp API.
137 validate_certs:
138 description:
139 - If V(false), SSL certificates are not validated. This should only be used on personally controlled sites using self-signed
140 certificates.
141 type: bool
142 default: true
143 wait_for_completion:
144 description:
145 - Wait for asynchronous tasks to complete before returning.
146 type: bool
147 default: false
148 notes:
149 - This module can currently only create distributors and importers on rpm repositories. Contributions to support other repo
150 types are welcome.
151 extends_documentation_fragment:
152 - ansible.builtin.url
153 - community.general._attributes
154 """
155
156 EXAMPLES = r"""
157 - name: Create a new repo with name 'my_repo'
158 community.general.pulp_repo:
159 name: my_repo
160 relative_url: my/repo
161 state: present
162
163 - name: Create a repo with a feed and a relative URL
164 community.general.pulp_repo:
165 name: my_centos_updates
166 repo_type: rpm
167 feed: http://mirror.centos.org/centos/6/updates/x86_64/
168 relative_url: centos/6/updates
169 url_username: admin
170 url_password: admin
171 force_basic_auth: true
172 state: present
173
174 - name: Remove a repo from the pulp server
175 community.general.pulp_repo:
176 name: my_old_repo
177 repo_type: rpm
178 state: absent
179 """
180
181 RETURN = r"""
182 repo:
183 description: Name of the repo that the action was performed on.
184 returned: success
185 type: str
186 sample: my_repo
187 """
188
189 import json
190 import os
191 from time import sleep
192
193 # import module snippets
194 from ansible.module_utils.basic import AnsibleModule
195 from ansible.module_utils.urls import fetch_url, url_argument_spec
196
197
198 class pulp_server:
199 """
200 Class to interact with a Pulp server
201 """
202
203 def __init__(self, module, pulp_host, repo_type, wait_for_completion=False):
204 self.module = module
205 self.host = pulp_host
206 self.repo_type = repo_type
207 self.repo_cache = dict()
208 self.wait_for_completion = wait_for_completion
209
210 def check_repo_exists(self, repo_id):
211 try:
212 self.get_repo_config_by_id(repo_id)
213 except IndexError:
214 return False
215 else:
216 return True
217
218 def compare_repo_distributor_config(self, repo_id, **kwargs):
219 repo_config = self.get_repo_config_by_id(repo_id)
220
221 for distributor in repo_config["distributors"]:
222 for key, value in kwargs.items():
223 if key not in distributor["config"].keys():
224 return False
225
226 if distributor["config"][key] != value:
227 return False
228
229 return True
230
231 def compare_repo_importer_config(self, repo_id, **kwargs):
232 repo_config = self.get_repo_config_by_id(repo_id)
233
234 for importer in repo_config["importers"]:
235 for key, value in kwargs.items():
236 if value is not None:
237 if key not in importer["config"].keys():
238 return False
239
240 if importer["config"][key] != value:
241 return False
242
243 return True
244
245 def create_repo(
246 self,
247 repo_id,
248 relative_url,
249 feed=None,
250 generate_sqlite=False,
251 serve_http=False,
252 serve_https=True,
253 proxy_host=None,
254 proxy_port=None,
255 proxy_username=None,
256 proxy_password=None,
257 repoview=False,
258 ssl_ca_cert=None,
259 ssl_client_cert=None,
260 ssl_client_key=None,
261 add_export_distributor=False,
262 ):
263 url = f"{self.host}/pulp/api/v2/repositories/"
264 data = dict()
265 data["id"] = repo_id
266 data["distributors"] = []
267
268 if self.repo_type == "rpm":
269 yum_distributor = dict()
270 yum_distributor["distributor_id"] = "yum_distributor"
271 yum_distributor["distributor_type_id"] = "yum_distributor"
272 yum_distributor["auto_publish"] = True
273 yum_distributor["distributor_config"] = dict()
274 yum_distributor["distributor_config"]["http"] = serve_http
275 yum_distributor["distributor_config"]["https"] = serve_https
276 yum_distributor["distributor_config"]["relative_url"] = relative_url
277 yum_distributor["distributor_config"]["repoview"] = repoview
278 yum_distributor["distributor_config"]["generate_sqlite"] = generate_sqlite or repoview
279 data["distributors"].append(yum_distributor)
280
281 if add_export_distributor:
282 export_distributor = dict()
283 export_distributor["distributor_id"] = "export_distributor"
284 export_distributor["distributor_type_id"] = "export_distributor"
285 export_distributor["auto_publish"] = False
286 export_distributor["distributor_config"] = dict()
287 export_distributor["distributor_config"]["http"] = serve_http
288 export_distributor["distributor_config"]["https"] = serve_https
289 export_distributor["distributor_config"]["relative_url"] = relative_url
290 export_distributor["distributor_config"]["repoview"] = repoview
291 export_distributor["distributor_config"]["generate_sqlite"] = generate_sqlite or repoview
292 data["distributors"].append(export_distributor)
293
294 data["importer_type_id"] = "yum_importer"
295 data["importer_config"] = dict()
296
297 if feed:
298 data["importer_config"]["feed"] = feed
299
300 if proxy_host:
301 data["importer_config"]["proxy_host"] = proxy_host
302
303 if proxy_port:
304 data["importer_config"]["proxy_port"] = proxy_port
305
306 if proxy_username:
307 data["importer_config"]["proxy_username"] = proxy_username
308
309 if proxy_password:
310 data["importer_config"]["proxy_password"] = proxy_password
311
312 if ssl_ca_cert:
313 data["importer_config"]["ssl_ca_cert"] = ssl_ca_cert
314
315 if ssl_client_cert:
316 data["importer_config"]["ssl_client_cert"] = ssl_client_cert
317
318 if ssl_client_key:
319 data["importer_config"]["ssl_client_key"] = ssl_client_key
320
321 data["notes"] = {"_repo-type": "rpm-repo"}
322
323 response, info = fetch_url(self.module, url, data=json.dumps(data), method="POST")
324
325 if info["status"] != 201:
326 self.module.fail_json(
327 msg="Failed to create repo.", status_code=info["status"], response=info["msg"], url=url
328 )
329 else:
330 return True
331
332 def delete_repo(self, repo_id):
333 url = f"{self.host}/pulp/api/v2/repositories/{repo_id}/"
334 response, info = fetch_url(self.module, url, data="", method="DELETE")
335
336 if info["status"] != 202:
337 self.module.fail_json(
338 msg="Failed to delete repo.", status_code=info["status"], response=info["msg"], url=url
339 )
340
341 if self.wait_for_completion:
342 self.verify_tasks_completed(json.load(response))
343
344 return True
345
346 def get_repo_config_by_id(self, repo_id):
347 if repo_id not in self.repo_cache.keys():
348 repo_array = [x for x in self.repo_list if x["id"] == repo_id]
349 self.repo_cache[repo_id] = repo_array[0]
350
351 return self.repo_cache[repo_id]
352
353 def publish_repo(self, repo_id, publish_distributor):
354 url = f"{self.host}/pulp/api/v2/repositories/{repo_id}/actions/publish/"
355
356 # If there's no distributor specified, we will publish them all
357 if publish_distributor is None:
358 repo_config = self.get_repo_config_by_id(repo_id)
359
360 for distributor in repo_config["distributors"]:
361 data = dict()
362 data["id"] = distributor["id"]
363 response, info = fetch_url(self.module, url, data=json.dumps(data), method="POST")
364
365 if info["status"] != 202:
366 self.module.fail_json(
367 msg="Failed to publish the repo.",
368 status_code=info["status"],
369 response=info["msg"],
370 url=url,
371 distributor=distributor["id"],
372 )
373 else:
374 data = dict()
375 data["id"] = publish_distributor
376 response, info = fetch_url(self.module, url, data=json.dumps(data), method="POST")
377
378 if info["status"] != 202:
379 self.module.fail_json(
380 msg="Failed to publish the repo",
381 status_code=info["status"],
382 response=info["msg"],
383 url=url,
384 distributor=publish_distributor,
385 )
386
387 if self.wait_for_completion:
388 self.verify_tasks_completed(json.load(response))
389
390 return True
391
392 def sync_repo(self, repo_id):
393 url = f"{self.host}/pulp/api/v2/repositories/{repo_id}/actions/sync/"
394 response, info = fetch_url(self.module, url, data="", method="POST")
395
396 if info["status"] != 202:
397 self.module.fail_json(
398 msg="Failed to schedule a sync of the repo.", status_code=info["status"], response=info["msg"], url=url
399 )
400
401 if self.wait_for_completion:
402 self.verify_tasks_completed(json.load(response))
403
404 return True
405
406 def update_repo_distributor_config(self, repo_id, **kwargs):
407 url = f"{self.host}/pulp/api/v2/repositories/{repo_id}/distributors/"
408 repo_config = self.get_repo_config_by_id(repo_id)
409
410 for distributor in repo_config["distributors"]:
411 distributor_url = f"{url}{distributor['id']}/"
412 data = dict()
413 data["distributor_config"] = dict()
414
415 for key, value in kwargs.items():
416 data["distributor_config"][key] = value
417
418 response, info = fetch_url(self.module, distributor_url, data=json.dumps(data), method="PUT")
419
420 if info["status"] != 202:
421 self.module.fail_json(
422 msg="Failed to set the relative url for the repository.",
423 status_code=info["status"],
424 response=info["msg"],
425 url=url,
426 )
427
428 def update_repo_importer_config(self, repo_id, **kwargs):
429 url = f"{self.host}/pulp/api/v2/repositories/{repo_id}/importers/"
430 data = dict()
431 importer_config = dict()
432
433 for key, value in kwargs.items():
434 if value is not None:
435 importer_config[key] = value
436
437 data["importer_config"] = importer_config
438
439 if self.repo_type == "rpm":
440 data["importer_type_id"] = "yum_importer"
441
442 response, info = fetch_url(self.module, url, data=json.dumps(data), method="POST")
443
444 if info["status"] != 202:
445 self.module.fail_json(
446 msg="Failed to set the repo importer configuration",
447 status_code=info["status"],
448 response=info["msg"],
449 importer_config=importer_config,
450 url=url,
451 )
452
453 def set_repo_list(self):
454 url = f"{self.host}/pulp/api/v2/repositories/?details=true"
455 response, info = fetch_url(self.module, url, method="GET")
456
457 if info["status"] != 200:
458 self.module.fail_json(msg="Request failed", status_code=info["status"], response=info["msg"], url=url)
459
460 self.repo_list = json.load(response)
461
462 def verify_tasks_completed(self, response_dict):
463 for task in response_dict["spawned_tasks"]:
464 task_url = f"{self.host}{task['_href']}"
465
466 while True:
467 response, info = fetch_url(self.module, task_url, data="", method="GET")
468
469 if info["status"] != 200:
470 self.module.fail_json(
471 msg="Failed to check async task status.",
472 status_code=info["status"],
473 response=info["msg"],
474 url=task_url,
475 )
476
477 task_dict = json.load(response)
478
479 if task_dict["state"] == "finished":
480 return True
481
482 if task_dict["state"] == "error":
483 self.module.fail_json(msg="Asynchronous task failed to complete.", error=task_dict["error"])
484
485 sleep(2)
486
487
488 def main():
489 argument_spec = url_argument_spec()
490 argument_spec.update(
491 add_export_distributor=dict(default=False, type="bool"),
492 feed=dict(),
493 generate_sqlite=dict(default=False, type="bool"),
494 feed_ca_cert=dict(aliases=["importer_ssl_ca_cert"]),
495 feed_client_cert=dict(aliases=["importer_ssl_client_cert"]),
496 feed_client_key=dict(aliases=["importer_ssl_client_key"], no_log=True),
497 name=dict(required=True, aliases=["repo"]),
498 proxy_host=dict(),
499 proxy_port=dict(),
500 proxy_username=dict(),
501 proxy_password=dict(no_log=True),
502 publish_distributor=dict(),
503 pulp_host=dict(default="https://127.0.0.1"),
504 relative_url=dict(),
505 repo_type=dict(default="rpm"),
506 repoview=dict(default=False, type="bool"),
507 serve_http=dict(default=False, type="bool"),
508 serve_https=dict(default=True, type="bool"),
509 state=dict(default="present", choices=["absent", "present", "sync", "publish"]),
510 wait_for_completion=dict(default=False, type="bool"),
511 )
512 module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
513
514 add_export_distributor = module.params["add_export_distributor"]
515 feed = module.params["feed"]
516 generate_sqlite = module.params["generate_sqlite"]
517 importer_ssl_ca_cert = module.params["feed_ca_cert"]
518 importer_ssl_client_cert = module.params["feed_client_cert"]
519 importer_ssl_client_key = module.params["feed_client_key"]
520 proxy_host = module.params["proxy_host"]
521 proxy_port = module.params["proxy_port"]
522 proxy_username = module.params["proxy_username"]
523 proxy_password = module.params["proxy_password"]
524 publish_distributor = module.params["publish_distributor"]
525 pulp_host = module.params["pulp_host"]
526 relative_url = module.params["relative_url"]
527 repo = module.params["name"]
528 repo_type = module.params["repo_type"]
529 repoview = module.params["repoview"]
530 serve_http = module.params["serve_http"]
531 serve_https = module.params["serve_https"]
532 state = module.params["state"]
533 wait_for_completion = module.params["wait_for_completion"]
534
535 if (state == "present") and (not relative_url):
536 module.fail_json(msg="When state is present, relative_url is required.")
537
538 # Ensure that the importer_ssl_* is the content and not a file path
539 if importer_ssl_ca_cert is not None:
540 importer_ssl_ca_cert_file_path = os.path.abspath(importer_ssl_ca_cert)
541 if os.path.isfile(importer_ssl_ca_cert_file_path):
542 with open(importer_ssl_ca_cert_file_path) as importer_ssl_ca_cert_file_object:
543 importer_ssl_ca_cert = importer_ssl_ca_cert_file_object.read()
544
545 if importer_ssl_client_cert is not None:
546 importer_ssl_client_cert_file_path = os.path.abspath(importer_ssl_client_cert)
547 if os.path.isfile(importer_ssl_client_cert_file_path):
548 with open(importer_ssl_client_cert_file_path) as importer_ssl_client_cert_file_object:
549 importer_ssl_client_cert = importer_ssl_client_cert_file_object.read()
550
551 if importer_ssl_client_key is not None:
552 importer_ssl_client_key_file_path = os.path.abspath(importer_ssl_client_key)
553 if os.path.isfile(importer_ssl_client_key_file_path):
554 with open(importer_ssl_client_key_file_path) as importer_ssl_client_key_file_object:
555 importer_ssl_client_key = importer_ssl_client_key_file_object.read()
556
557 server = pulp_server(module, pulp_host, repo_type, wait_for_completion=wait_for_completion)
558 server.set_repo_list()
559 repo_exists = server.check_repo_exists(repo)
560
561 changed = False
562
563 if state == "absent" and repo_exists:
564 if not module.check_mode:
565 server.delete_repo(repo)
566
567 changed = True
568
569 if state == "sync":
570 if not repo_exists:
571 module.fail_json(msg="Repository was not found. The repository can not be synced.")
572
573 if not module.check_mode:
574 server.sync_repo(repo)
575
576 changed = True
577
578 if state == "publish":
579 if not repo_exists:
580 module.fail_json(msg="Repository was not found. The repository can not be published.")
581
582 if not module.check_mode:
583 server.publish_repo(repo, publish_distributor)
584
585 changed = True
586
587 if state == "present":
588 if not repo_exists:
589 if not module.check_mode:
590 server.create_repo(
591 repo_id=repo,
592 relative_url=relative_url,
593 feed=feed,
594 generate_sqlite=generate_sqlite,
595 serve_http=serve_http,
596 serve_https=serve_https,
597 proxy_host=proxy_host,
598 proxy_port=proxy_port,
599 proxy_username=proxy_username,
600 proxy_password=proxy_password,
601 repoview=repoview,
602 ssl_ca_cert=importer_ssl_ca_cert,
603 ssl_client_cert=importer_ssl_client_cert,
604 ssl_client_key=importer_ssl_client_key,
605 add_export_distributor=add_export_distributor,
606 )
607
608 changed = True
609
610 else:
611 # Check to make sure all the settings are correct
612 # The importer config gets overwritten on set and not updated, so
613 # we set the whole config at the same time.
614 if not server.compare_repo_importer_config(
615 repo,
616 feed=feed,
617 proxy_host=proxy_host,
618 proxy_port=proxy_port,
619 proxy_username=proxy_username,
620 proxy_password=proxy_password,
621 ssl_ca_cert=importer_ssl_ca_cert,
622 ssl_client_cert=importer_ssl_client_cert,
623 ssl_client_key=importer_ssl_client_key,
624 ):
625 if not module.check_mode:
626 server.update_repo_importer_config(
627 repo,
628 feed=feed,
629 proxy_host=proxy_host,
630 proxy_port=proxy_port,
631 proxy_username=proxy_username,
632 proxy_password=proxy_password,
633 ssl_ca_cert=importer_ssl_ca_cert,
634 ssl_client_cert=importer_ssl_client_cert,
635 ssl_client_key=importer_ssl_client_key,
636 )
637
638 changed = True
639
640 if relative_url is not None:
641 if not server.compare_repo_distributor_config(repo, relative_url=relative_url):
642 if not module.check_mode:
643 server.update_repo_distributor_config(repo, relative_url=relative_url)
644
645 changed = True
646
647 if not server.compare_repo_distributor_config(repo, generate_sqlite=generate_sqlite):
648 if not module.check_mode:
649 server.update_repo_distributor_config(repo, generate_sqlite=generate_sqlite)
650
651 changed = True
652
653 if not server.compare_repo_distributor_config(repo, repoview=repoview):
654 if not module.check_mode:
655 server.update_repo_distributor_config(repo, repoview=repoview)
656
657 changed = True
658
659 if not server.compare_repo_distributor_config(repo, http=serve_http):
660 if not module.check_mode:
661 server.update_repo_distributor_config(repo, http=serve_http)
662
663 changed = True
664
665 if not server.compare_repo_distributor_config(repo, https=serve_https):
666 if not module.check_mode:
667 server.update_repo_distributor_config(repo, https=serve_https)
668
669 changed = True
670
671 module.exit_json(changed=changed, repo=repo)
672
673
674 if __name__ == "__main__":
675 main()