Debian Codegraph @

ansible_collections/kubernetes/core/plugins/modules/helm_pull.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2022, Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6 from __future__ import absolute_import, division, print_function
7
8 __metaclass__ = type
9
10
11 DOCUMENTATION = r"""
12 ---
13 module: helm_pull
14 short_description: download a chart from a repository and (optionally) unpack it in local directory.
15 version_added: 2.4.0
16 author:
17 - Aubin Bikouo (@abikouo)
18 description:
19 - Retrieve a package from a package repository, and download it locally.
20 - It can also be used to perform cryptographic verification of a chart without installing the chart.
21 - There are options for unpacking the chart after download.
22
23 requirements:
24 - "helm >= 3.0.0 (https://github.com/helm/helm/releases)"
25
26 options:
27 chart_ref:
28 description:
29 - chart name on chart repository.
30 - absolute URL.
31 required: true
32 type: str
33 chart_version:
34 description:
35 - Specify a version constraint for the chart version to use.
36 - This constraint can be a specific tag (e.g. 1.1.1) or it may reference a valid range (e.g. ^2.0.0).
37 - Mutually exclusive with C(chart_devel).
38 type: str
39 verify_chart:
40 description:
41 - Verify the package before using it.
42 default: False
43 type: bool
44 verify_chart_keyring:
45 description:
46 - location of public keys used for verification.
47 type: path
48 provenance:
49 description:
50 - Fetch the provenance file, but don't perform verification.
51 type: bool
52 default: False
53 repo_url:
54 description:
55 - chart repository url where to locate the requested chart.
56 type: str
57 aliases: [ url, chart_repo_url ]
58 repo_username:
59 description:
60 - Chart repository username where to locate the requested chart.
61 - Required if C(repo_password) is specified.
62 type: str
63 aliases: [ username, chart_repo_username ]
64 repo_password:
65 description:
66 - Chart repository password where to locate the requested chart.
67 - Required if C(repo_username) is specified.
68 type: str
69 aliases: [ password, chart_repo_password ]
70 pass_credentials:
71 description:
72 - Pass credentials to all domains.
73 default: False
74 type: bool
75 skip_tls_certs_check:
76 description:
77 - Whether or not to check tls certificate for the chart download.
78 - Requires helm >= 3.3.0. Alias C(insecure_skip_tls_verify) added in 5.3.0.
79 type: bool
80 default: False
81 aliases: [ insecure_skip_tls_verify ]
82 chart_devel:
83 description:
84 - Use development versions, too. Equivalent to version '>0.0.0-0'.
85 - Mutually exclusive with C(chart_version).
86 type: bool
87 untar_chart:
88 description:
89 - if set to true, will untar the chart after downloading it.
90 type: bool
91 default: False
92 force:
93 description:
94 - Force download of the chart even if it already exists in the destination directory.
95 - By default, the module will skip downloading if the chart with the same version already exists for idempotency.
96 - When used with O(untar_chart=true), will remove any existing chart directory before extracting.
97 type: bool
98 default: False
99 version_added: 6.3.0
100 destination:
101 description:
102 - location to write the chart.
103 type: path
104 required: True
105 chart_ca_cert:
106 description:
107 - Verify certificates of HTTPS-enabled servers using this CA bundle.
108 - Requires helm >= 3.1.0.
109 type: path
110 chart_ssl_cert_file:
111 description:
112 - Identify HTTPS client using this SSL certificate file.
113 - Requires helm >= 3.1.0.
114 type: path
115 chart_ssl_key_file:
116 description:
117 - Identify HTTPS client using this SSL key file
118 - Requires helm >= 3.1.0.
119 type: path
120 binary_path:
121 description:
122 - The path of a helm binary to use.
123 required: false
124 type: path
125 plain_http:
126 description:
127 - Use HTTP instead of HTTPS when working with OCI registries
128 - Requires Helm >= 3.13.0
129 type: bool
130 default: False
131 version_added: 6.1.0
132 """
133
134 EXAMPLES = r"""
135 - name: Download chart using chart url
136 kubernetes.core.helm_pull:
137 chart_ref: https://github.com/grafana/helm-charts/releases/download/grafana-5.6.0/grafana-5.6.0.tgz
138 destination: /path/to/chart
139
140 - name: Download Chart using chart_name and repo_url
141 kubernetes.core.helm_pull:
142 chart_ref: redis
143 repo_url: https://charts.bitnami.com/bitnami
144 untar_chart: yes
145 destination: /path/to/chart
146
147 - name: Download Chart (skip tls certificate check)
148 kubernetes.core.helm_pull:
149 chart_ref: redis
150 repo_url: https://charts.bitnami.com/bitnami
151 untar_chart: yes
152 destination: /path/to/chart
153 skip_tls_certs_check: yes
154
155 - name: Download Chart using chart registry credentials
156 kubernetes.core.helm_pull:
157 chart_ref: redis
158 repo_url: https://charts.bitnami.com/bitnami
159 untar_chart: yes
160 destination: /path/to/chart
161 username: myuser
162 password: mypassword123
163
164 - name: Download Chart (force re-download even if exists)
165 kubernetes.core.helm_pull:
166 chart_ref: redis
167 repo_url: https://charts.bitnami.com/bitnami
168 chart_version: '17.0.0'
169 destination: /path/to/chart
170 force: yes
171
172 - name: Download and untar chart (force re-extraction even if directory exists)
173 kubernetes.core.helm_pull:
174 chart_ref: redis
175 repo_url: https://charts.bitnami.com/bitnami
176 chart_version: '17.0.0'
177 destination: /path/to/chart
178 untar_chart: yes
179 force: yes
180 """
181
182 RETURN = r"""
183 stdout:
184 type: str
185 description: Full `helm pull` command stdout, in case you want to display it or examine the event log
186 returned: always
187 sample: ''
188 stderr:
189 type: str
190 description: Full `helm pull` command stderr, in case you want to display it or examine the event log
191 returned: always
192 sample: ''
193 command:
194 type: str
195 description: Full `helm pull` command built by this module, in case you want to re-run the command outside the module or debug a problem.
196 returned: always
197 sample: helm pull --repo test ...
198 msg:
199 type: str
200 description: A message indicating the result of the operation.
201 returned: when chart already exists
202 sample: Chart redis version 17.0.0 already exists in destination directory
203 rc:
204 type: int
205 description: Helm pull command return code
206 returned: always
207 sample: 1
208 """
209
210 import os
211 import shutil
212 import tarfile
213 import uuid
214
215 try:
216 import yaml
217
218 HAS_YAML = True
219 except ImportError:
220 HAS_YAML = False
221
222 from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
223 AnsibleHelmModule,
224 )
225 from ansible_collections.kubernetes.core.plugins.module_utils.version import (
226 LooseVersion,
227 )
228
229
230 def extract_chart_name(chart_ref):
231 """
232 Extract chart name from chart reference.
233
234 Args:
235 chart_ref (str): Chart reference (name, URL, or OCI reference)
236
237 Returns:
238 str: Extracted chart name
239 """
240 chart_name = chart_ref.split("/")[-1]
241 # Remove any query parameters or fragments from URL-based refs
242 if "?" in chart_name:
243 chart_name = chart_name.split("?")[0]
244 if "#" in chart_name:
245 chart_name = chart_name.split("#")[0]
246 # Remove .tgz extension if present
247 if chart_name.endswith(".tgz"):
248 chart_name = chart_name[:-4]
249 return chart_name
250
251
252 def chart_exists(destination, chart_ref, chart_version, untar_chart):
253 """
254 Check if the chart already exists in the destination directory.
255
256 For untarred charts: check if directory exists with Chart.yaml matching version
257 For tarred charts: check if .tgz file exists and contains matching version
258
259 Args:
260 destination (str): Destination directory path
261 chart_ref (str): Chart reference (name or URL)
262 chart_version (str): Chart version to check for
263 untar_chart (bool): Whether to check for untarred or tarred chart
264
265 Returns:
266 bool: True if chart with matching version exists, False otherwise
267 """
268 # YAML is required for version checking
269 if not HAS_YAML:
270 return False
271
272 # Without version, we can't reliably check
273 if not chart_version:
274 return False
275
276 # Extract chart name from chart_ref using shared helper
277 chart_name = extract_chart_name(chart_ref)
278
279 if untar_chart:
280 # Check for extracted directory
281 chart_dir = os.path.join(destination, chart_name)
282 chart_yaml_path = os.path.join(chart_dir, "Chart.yaml")
283
284 if os.path.isdir(chart_dir) and os.path.isfile(chart_yaml_path):
285 try:
286 with open(chart_yaml_path, "r", encoding="utf-8") as chart_file:
287 chart_metadata = yaml.safe_load(chart_file)
288 # Ensure chart_metadata is a dict and has a version that matches
289 if (
290 chart_metadata
291 and isinstance(chart_metadata, dict)
292 and chart_metadata.get("version") == chart_version
293 and chart_metadata.get("name") == chart_name
294 ):
295 return True
296 except (yaml.YAMLError, IOError, OSError, TypeError):
297 # If we can't read or parse the file, treat as non-existent
298 pass
299 else:
300 # Check for .tgz file
301 chart_file = os.path.join(destination, f"{chart_name}-{chart_version}.tgz")
302
303 if os.path.isfile(chart_file):
304 try:
305 # Verify it's a valid tarball with matching version
306 with tarfile.open(chart_file, "r:gz") as tar:
307 # Try to extract Chart.yaml to verify version
308 # Look for Chart.yaml at the expected path: <chart-name>/Chart.yaml
309 expected_chart_yaml = f"{chart_name}/Chart.yaml"
310 try:
311 member = tar.getmember(expected_chart_yaml)
312 chart_yaml_file = tar.extractfile(member)
313 if chart_yaml_file:
314 try:
315 chart_metadata = yaml.safe_load(chart_yaml_file)
316 # Ensure chart_metadata is a dict and has a version that matches
317 if (
318 chart_metadata
319 and isinstance(chart_metadata, dict)
320 and chart_metadata.get("version") == chart_version
321 and chart_metadata.get("name") == chart_name
322 ):
323 return True
324 except (yaml.YAMLError, TypeError):
325 # If we can't parse the YAML, treat as non-existent
326 pass
327 finally:
328 chart_yaml_file.close()
329 except KeyError:
330 # Chart.yaml not found at expected path
331 pass
332 except (tarfile.TarError, yaml.YAMLError, IOError, OSError, TypeError):
333 # If we can't read or parse the tarball, treat as non-existent
334 pass
335
336 return False
337
338
339 def main():
340 argspec = dict(
341 chart_ref=dict(type="str", required=True),
342 chart_version=dict(type="str"),
343 verify_chart=dict(type="bool", default=False),
344 verify_chart_keyring=dict(type="path"),
345 provenance=dict(type="bool", default=False),
346 repo_url=dict(type="str", aliases=["url", "chart_repo_url"]),
347 repo_username=dict(type="str", aliases=["username", "chart_repo_username"]),
348 repo_password=dict(
349 type="str", no_log=True, aliases=["password", "chart_repo_password"]
350 ),
351 pass_credentials=dict(type="bool", default=False, no_log=False),
352 skip_tls_certs_check=dict(
353 type="bool", default=False, aliases=["insecure_skip_tls_verify"]
354 ),
355 chart_devel=dict(type="bool"),
356 untar_chart=dict(type="bool", default=False),
357 force=dict(type="bool", default=False),
358 destination=dict(type="path", required=True),
359 chart_ca_cert=dict(type="path"),
360 chart_ssl_cert_file=dict(type="path"),
361 chart_ssl_key_file=dict(type="path"),
362 binary_path=dict(type="path"),
363 plain_http=dict(type="bool", default=False),
364 )
365 module = AnsibleHelmModule(
366 argument_spec=argspec,
367 supports_check_mode=True,
368 required_by=dict(
369 repo_username=("repo_password"),
370 repo_password=("repo_username"),
371 ),
372 mutually_exclusive=[("chart_version", "chart_devel")],
373 )
374
375 # Validate Helm version >=3.0.0
376 module.validate_helm_version()
377
378 helm_version = module.get_helm_version()
379
380 helm_pull_opt_versionning = dict(
381 skip_tls_certs_check="3.3.0",
382 chart_ca_cert="3.1.0",
383 chart_ssl_cert_file="3.1.0",
384 chart_ssl_key_file="3.1.0",
385 plain_http="3.13.0",
386 )
387
388 def test_version_requirement(opt):
389 req_version = helm_pull_opt_versionning.get(opt)
390 if req_version and LooseVersion(helm_version) < LooseVersion(req_version):
391 module.fail_json(
392 msg="Parameter {0} requires helm >= {1}, current version is {2}".format(
393 opt, req_version, helm_version
394 )
395 )
396
397 # Set `helm pull` arguments requiring values
398 helm_pull_opts = []
399
400 helm_value_args = dict(
401 chart_version="version",
402 verify_chart_keyring="keyring",
403 repo_url="repo",
404 repo_username="username",
405 repo_password="password",
406 destination="destination",
407 chart_ca_cert="ca-file",
408 chart_ssl_cert_file="cert-file",
409 chart_ssl_key_file="key-file",
410 )
411
412 for opt, cmdkey in helm_value_args.items():
413 if module.params.get(opt):
414 test_version_requirement(opt)
415 helm_pull_opts.append("--{0} {1}".format(cmdkey, module.params.get(opt)))
416
417 # Set `helm pull` arguments flags
418 helm_flag_args = dict(
419 verify_chart=dict(key="verify"),
420 provenance=dict(key="prov"),
421 pass_credentials=dict(key="pass-credentials"),
422 skip_tls_certs_check=dict(key="insecure-skip-tls-verify"),
423 chart_devel=dict(key="devel"),
424 untar_chart=dict(key="untar"),
425 plain_http=dict(key="plain-http"),
426 )
427
428 for k, v in helm_flag_args.items():
429 if module.params.get(k):
430 test_version_requirement(k)
431 helm_pull_opts.append("--{0}".format(v["key"]))
432
433 helm_cmd_common = "{0} pull {1} {2}".format(
434 module.get_helm_binary(),
435 module.params.get("chart_ref"),
436 " ".join(helm_pull_opts),
437 )
438
439 # Check if chart already exists (idempotency)
440 if module.params.get("chart_version") and not module.params.get("force"):
441 chart_exists_locally = chart_exists(
442 module.params.get("destination"),
443 module.params.get("chart_ref"),
444 module.params.get("chart_version"),
445 module.params.get("untar_chart"),
446 )
447
448 if chart_exists_locally:
449 module.exit_json(
450 failed=False,
451 changed=False,
452 msg="Chart {0} version {1} already exists in destination directory".format(
453 module.params.get("chart_ref"), module.params.get("chart_version")
454 ),
455 command="",
456 stdout="",
457 stderr="",
458 rc=0,
459 )
460
461 # When both untar_chart and force are enabled, we need to remove the existing chart directory
462 # BEFORE running helm pull to prevent helm's "directory already exists" error.
463 # We do this by:
464 # 1. Renaming the existing directory to a temporary name (if it exists)
465 # 2. Running helm pull
466 # 3. On success: remove the temporary directory
467 # 4. On failure: restore the temporary directory and report the error
468 chart_dir_renamed = False
469 chart_dir = None
470 chart_dir_backup = None
471
472 if module.params.get("untar_chart") and module.params.get("force"):
473 chart_name = extract_chart_name(module.params.get("chart_ref"))
474 chart_dir = os.path.join(module.params.get("destination"), chart_name)
475
476 # Check if directory exists and contains a Chart.yaml (to be safe)
477 if os.path.isdir(chart_dir):
478 chart_yaml_path = os.path.join(chart_dir, "Chart.yaml")
479 # Only rename if it looks like a Helm chart directory (have Chart.yaml)
480 if os.path.isfile(chart_yaml_path):
481 if not module.check_mode:
482 # Rename to temporary backup name using uuid for uniqueness
483 backup_suffix = uuid.uuid4().hex[:8]
484 chart_dir_backup = os.path.join(
485 module.params.get("destination"),
486 f".{chart_name}_backup_{backup_suffix}",
487 )
488 os.rename(chart_dir, chart_dir_backup)
489 chart_dir_renamed = True
490
491 if not module.check_mode:
492 rc, out, err = module.run_helm_command(helm_cmd_common, fails_on_error=False)
493
494 # Handle cleanup/restore based on helm command result
495 if chart_dir_renamed:
496 if rc == 0:
497 # Success: remove the backup directory
498 if os.path.isdir(chart_dir_backup):
499 shutil.rmtree(chart_dir_backup)
500 else:
501 # Failure: restore the backup directory
502 if os.path.isdir(chart_dir_backup) and not os.path.exists(chart_dir):
503 os.rename(chart_dir_backup, chart_dir)
504 else:
505 rc, out, err = (0, "", "")
506
507 if rc == 0:
508 module.exit_json(
509 failed=False,
510 changed=True,
511 command=helm_cmd_common,
512 stdout=out,
513 stderr=err,
514 rc=rc,
515 )
516 else:
517 module.fail_json(
518 msg="Failure when executing Helm command.",
519 command=helm_cmd_common,
520 changed=False,
521 stdout=out,
522 stderr=err,
523 rc=rc,
524 )
525
526
527 if __name__ == "__main__":
528 main()