Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: 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
14
15 short_description: Manages Kubernetes packages with the Helm package manager
16
17 version_added: 0.11.0
18
19 author:
20 - Lucas Boisserie (@LucasBoisserie)
21 - Matthieu Diehr (@d-matt)
22
23 requirements:
24 - "helm >= 3.0.0 (https://github.com/helm/helm/releases)"
25 - "yaml (https://pypi.org/project/PyYAML/)"
26
27 description:
28 - Install, upgrade, delete packages with the Helm package manager.
29
30 notes:
31 - The default idempotency check can fail to report changes when C(release_state) is set to C(present)
32 and C(chart_repo_url) is defined. Install helm diff >= 3.4.1 for better results.
33
34 options:
35 chart_ref:
36 description:
37 - chart_reference on chart repository.
38 - path to a packaged chart.
39 - path to an unpacked chart directory.
40 - absolute URL.
41 - Required when I(release_state) is set to C(present).
42 required: false
43 type: path
44 chart_repo_url:
45 description:
46 - Chart repository URL where to locate the requested chart.
47 required: false
48 type: str
49 chart_version:
50 description:
51 - Chart version to install. If this is not specified, the latest version is installed.
52 required: false
53 type: str
54 dependency_update:
55 description:
56 - Run standalone C(helm dependency update CHART) before the operation.
57 - Run inline C(--dependency-update) with C(helm install) command. This feature is not supported yet with the C(helm upgrade) command.
58 - So we should consider to use I(dependency_update) options with I(replace) option enabled when specifying I(chart_repo_url).
59 - The I(dependency_update) option require the add of C(dependencies) block in C(Chart.yaml/requirements.yaml) file.
60 - For more information please visit U(https://helm.sh/docs/helm/helm_dependency/)
61 default: false
62 type: bool
63 aliases: [ dep_up ]
64 version_added: 2.4.0
65 release_name:
66 description:
67 - Release name to manage.
68 required: true
69 type: str
70 aliases: [ name ]
71 release_namespace:
72 description:
73 - Kubernetes namespace where the chart should be installed.
74 required: true
75 type: str
76 aliases: [ namespace ]
77 release_state:
78 choices: ['present', 'absent']
79 description:
80 - Desirated state of release.
81 required: false
82 default: present
83 aliases: [ state ]
84 type: str
85 release_values:
86 description:
87 - Value to pass to chart.
88 required: false
89 default: {}
90 aliases: [ values ]
91 type: dict
92 values_files:
93 description:
94 - Value files to pass to chart.
95 - Paths will be read from the target host's filesystem, not the host running ansible.
96 - values_files option is evaluated before values option if both are used.
97 - Paths are evaluated in the order the paths are specified.
98 required: false
99 default: []
100 type: list
101 elements: str
102 version_added: 1.1.0
103 update_repo_cache:
104 description:
105 - Run C(helm repo update) before the operation. Can be run as part of the package installation or as a separate step (see Examples).
106 default: false
107 type: bool
108 set_values:
109 description:
110 - Values to pass to chart configuration
111 required: false
112 type: list
113 elements: dict
114 suboptions:
115 value:
116 description:
117 - Value to pass to chart configuration (e.g phase=prod).
118 type: str
119 required: true
120 value_type:
121 description:
122 - Use C(raw) set individual value.
123 - Use C(string) to force a string for an individual value.
124 - Use C(file) to set individual values from a file when the value itself is too long for the command line or is dynamically generated.
125 - Use C(json) to set json values (scalars/objects/arrays). This feature requires helm>=3.10.0.
126 default: raw
127 choices:
128 - raw
129 - string
130 - json
131 - file
132 version_added: 2.4.0
133 reuse_values:
134 description:
135 - When upgrading package, specifies wether to reuse the last release's values and merge in any overrides from parameters I(release_values),
136 I(values_files) or I(set_values).
137 - If I(reset_values) is set to C(True), this is ignored.
138 type: bool
139 required: false
140 version_added: 3.0.0
141 reset_values:
142 description:
143 - When upgrading package, reset the values to the ones built into the chart.
144 type: bool
145 required: false
146 default: True
147 version_added: 3.0.0
148 reset_then_reuse_values:
149 description:
150 - When upgrading package, reset the values to the ones built into the chart, apply the last release's values and merge in any overrides from
151 parameters O(release_values), O(values_files) or O(set_values).
152 - If O(reset_values) or O(reuse_values) is set to V(True), this is ignored.
153 - This feature requires helm diff >= 3.9.12.
154 type: bool
155 required: false
156 default: False
157 version_added: 6.0.0
158
159 #Helm options
160 disable_hook:
161 description:
162 - Helm option to disable hook on install/upgrade/delete.
163 default: False
164 type: bool
165 force:
166 description:
167 - Helm option to force reinstall, ignore on new install.
168 default: False
169 type: bool
170 purge:
171 description:
172 - Remove the release from the store and make its name free for later use.
173 default: True
174 type: bool
175 wait:
176 description:
177 - When I(release_state) is set to C(present), wait until all Pods, PVCs, Services,
178 and minimum number of Pods of a Deployment are in a ready state before marking the release as successful.
179 - When I(release_state) is set to C(absent), will wait until all the resources are deleted before returning.
180 It will wait for as long as I(wait_timeout). This feature requires helm>=3.7.0. Added in version 2.3.0.
181 default: False
182 type: bool
183 wait_timeout:
184 description:
185 - Timeout when wait option is enabled (helm2 is a number of seconds, helm3 is a duration).
186 - The use of I(wait_timeout) to wait for kubernetes commands to complete has been deprecated and will be removed after 2022-12-01.
187 type: str
188 timeout:
189 description:
190 - A Go duration (described here I(https://pkg.go.dev/time#ParseDuration)) value to wait for Kubernetes commands to complete. This defaults to 5m0s.
191 - similar to C(wait_timeout) but does not required C(wait) to be activated.
192 - Mutually exclusive with C(wait_timeout).
193 type: str
194 version_added: 2.3.0
195 atomic:
196 description:
197 - If set, the installation process deletes the installation on failure.
198 type: bool
199 default: False
200 create_namespace:
201 description:
202 - Create the release namespace if not present.
203 type: bool
204 default: False
205 version_added: 0.11.1
206 post_renderer:
207 description:
208 - Path to an executable to be used for post rendering.
209 type: str
210 version_added: 2.4.0
211 replace:
212 description:
213 - Reuse the given name, only if that name is a deleted release which remains in the history.
214 - This is unsafe in production environment.
215 - mutually exclusive with with C(history_max).
216 type: bool
217 default: False
218 version_added: 1.11.0
219 skip_crds:
220 description:
221 - Skip custom resource definitions when installing or upgrading.
222 type: bool
223 default: False
224 version_added: 1.2.0
225 history_max:
226 description:
227 - Limit the maximum number of revisions saved per release.
228 - mutually exclusive with with C(replace).
229 type: int
230 version_added: 2.2.0
231 insecure_skip_tls_verify:
232 description:
233 - Skip tls certificate checks for the chart download.
234 - Do not confuse with the C(validate_certs) option.
235 - This option is only available for helm >= 3.16.0.
236 type: bool
237 default: False
238 aliases: [ skip_tls_certs_check ]
239 version_added: 5.3.0
240 plain_http:
241 description:
242 - Use HTTP instead of HTTPS when working with OCI registries
243 - Requires Helm >= 3.13.0
244 type: bool
245 default: False
246 version_added: 6.1.0
247 take_ownership:
248 description:
249 - Helm will ignore the check for helm annotations and take ownership of the existing resources
250 - This feature requires helm >= 3.17.0
251 type: bool
252 default: False
253 version_added: 6.1.0
254 skip_schema_validation:
255 description:
256 - Disables JSON schema validation for Chart and values.
257 - This feature requires helm >= 3.16.0
258 type: bool
259 default: False
260 version_added: 6.2.0
261 extends_documentation_fragment:
262 - kubernetes.core.helm_common_options
263 """
264
265 EXAMPLES = r"""
266 - name: Deploy latest version of Prometheus chart inside monitoring namespace (and create it)
267 kubernetes.core.helm:
268 name: test
269 chart_ref: stable/prometheus
270 release_namespace: monitoring
271 create_namespace: true
272
273 # From repository
274 - name: Add stable chart repo
275 kubernetes.core.helm_repository:
276 name: stable
277 repo_url: "https://kubernetes.github.io/ingress-nginx"
278
279 - name: Deploy latest version of Grafana chart inside monitoring namespace with values
280 kubernetes.core.helm:
281 name: test
282 chart_ref: stable/grafana
283 release_namespace: monitoring
284 values:
285 replicas: 2
286
287 - name: Deploy Grafana chart on 5.0.12 with values loaded from template
288 kubernetes.core.helm:
289 name: test
290 chart_ref: stable/grafana
291 chart_version: 5.0.12
292 values: "{{ lookup('template', 'somefile.yaml') | from_yaml }}"
293
294 - name: Deploy Grafana chart using values files on target
295 kubernetes.core.helm:
296 name: test
297 chart_ref: stable/grafana
298 release_namespace: monitoring
299 values_files:
300 - /path/to/values.yaml
301
302 - name: Remove test release and waiting suppression ending
303 kubernetes.core.helm:
304 name: test
305 state: absent
306 wait: true
307
308 - name: Separately update the repository cache
309 kubernetes.core.helm:
310 name: dummy
311 namespace: kube-system
312 state: absent
313 update_repo_cache: true
314
315 - name: Deploy Grafana chart using set values on target
316 kubernetes.core.helm:
317 name: test
318 chart_ref: stable/grafana
319 release_namespace: monitoring
320 set_values:
321 - value: phase=prod
322 value_type: string
323
324 # From git
325 - name: Git clone stable repo on HEAD
326 ansible.builtin.git:
327 repo: "http://github.com/helm/charts.git"
328 dest: /tmp/helm_repo
329
330 - name: Deploy Grafana chart from local path
331 kubernetes.core.helm:
332 name: test
333 chart_ref: /tmp/helm_repo/stable/grafana
334 release_namespace: monitoring
335
336 # From url
337 - name: Deploy Grafana chart on 5.6.0 from url
338 kubernetes.core.helm:
339 name: test
340 chart_ref: "https://github.com/grafana/helm-charts/releases/download/grafana-5.6.0/grafana-5.6.0.tgz"
341 release_namespace: monitoring
342
343 - name: Deploy Bitnami's MongoDB latest chart from OCI registry
344 kubernetes.core.helm:
345 name: test
346 chart_ref: "oci://registry-1.docker.io/bitnamicharts/mongodb"
347 release_namespace: database
348
349 # Using complex Values
350 - name: Deploy new-relic client chart
351 kubernetes.core.helm:
352 name: newrelic-bundle
353 chart_ref: newrelic/nri-bundle
354 release_namespace: default
355 force: True
356 wait: True
357 replace: True
358 update_repo_cache: True
359 disable_hook: True
360 values:
361 global:
362 licenseKey: "{{ nr_license_key }}"
363 cluster: "{{ site_name }}"
364 newrelic-infrastructure:
365 privileged: True
366 ksm:
367 enabled: True
368 prometheus:
369 enabled: True
370 kubeEvents:
371 enabled: True
372 logging:
373 enabled: True
374
375 # Deploy latest version
376 - name: Deploy latest version of Grafana chart using reuse_values
377 kubernetes.core.helm:
378 name: test
379 chart_ref: stable/grafana
380 release_namespace: monitoring
381 reuse_values: true
382 values:
383 replicas: 2
384 version: 3e8ec0b2dffa40fb97d5342e4af887de95faa8c61a62480dd7f8aa03dffcf533
385 """
386
387 RETURN = r"""
388 status:
389 type: complex
390 description: A dictionary of status output
391 returned: on success Creation/Upgrade/Already deploy
392 contains:
393 appversion:
394 type: str
395 returned: always
396 description: Version of app deployed
397 chart:
398 type: str
399 returned: always
400 description: Chart name and chart version
401 name:
402 type: str
403 returned: always
404 description: Name of the release
405 namespace:
406 type: str
407 returned: always
408 description: Namespace where the release is deployed
409 revision:
410 type: str
411 returned: always
412 description: Number of time where the release has been updated
413 status:
414 type: str
415 returned: always
416 description: Status of release (can be DEPLOYED, FAILED, ...)
417 updated:
418 type: str
419 returned: always
420 description: The Date of last update
421 values:
422 type: dict
423 returned: always
424 description:
425 - Dict of Values used to deploy.
426 - This return value has been deprecated and will be removed in a release after
427 2027-01-08. Use RV(status.release_values) instead.
428 release_values:
429 type: dict
430 returned: always
431 description:
432 - Dict of Values used to deploy.
433 version_added: 6.3.0
434 stdout:
435 type: str
436 description: Full `helm` command stdout, in case you want to display it or examine the event log
437 returned: always
438 sample: ''
439 stderr:
440 type: str
441 description: Full `helm` command stderr, in case you want to display it or examine the event log
442 returned: always
443 sample: ''
444 command:
445 type: str
446 description: Full `helm` command built by this module, in case you want to re-run the command outside the module or debug a problem.
447 returned: always
448 sample: helm upgrade ...
449 """
450
451 import copy
452 import re
453 import tempfile
454 import traceback
455
456 from ansible_collections.kubernetes.core.plugins.module_utils.version import (
457 LooseVersion,
458 )
459
460 try:
461 import yaml
462
463 IMP_YAML = True
464 IMP_YAML_ERR = None
465 except ImportError:
466 IMP_YAML_ERR = traceback.format_exc()
467 IMP_YAML = False
468
469 from ansible.module_utils.basic import missing_required_lib
470 from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
471 AnsibleHelmModule,
472 parse_helm_plugin_list,
473 )
474 from ansible_collections.kubernetes.core.plugins.module_utils.helm_args_common import (
475 HELM_AUTH_ARG_SPEC,
476 )
477
478
479 def get_release(state, release_name):
480 """
481 Get Release from all deployed releases
482 """
483
484 if state is not None:
485 for release in state:
486 if release["name"] == release_name:
487 return release
488 return None
489
490
491 def get_release_status(module, release_name, all_status=False):
492 """
493 Get Release state from all release status (deployed, failed, pending-install, etc)
494 """
495
496 list_command = [
497 module.get_helm_binary(),
498 "list",
499 "--output=yaml",
500 "--filter",
501 release_name,
502 ]
503 if all_status and not module.is_helm_v4():
504 # --all has been removed from `helm list` command on helm v4
505 list_command.append("--all")
506 elif not all_status:
507 # The default behavior to display only deployed releases has been removed from
508 # Helm v4
509 list_command.append("--deployed")
510 rc, out, err = module.run_helm_command(list_command)
511
512 release = get_release(yaml.safe_load(out), release_name)
513
514 if release is None: # not install
515 return None
516
517 release["release_values"] = module.get_values(release_name)
518 release["values"] = release["release_values"]
519
520 return release
521
522
523 def run_repo_update(module):
524 """
525 Run Repo update
526 """
527 repo_update_command = module.get_helm_binary() + " repo update"
528 rc, out, err = module.run_helm_command(repo_update_command)
529
530
531 def run_dep_update(module, chart_ref):
532 """
533 Run dependency update
534 """
535 dep_update = module.get_helm_binary() + f" dependency update '{chart_ref}'"
536 rc, out, err = module.run_helm_command(dep_update)
537
538
539 def fetch_chart_info(
540 module, command, chart_ref, insecure_skip_tls_verify=False, plain_http=False
541 ):
542 """
543 Get chart info
544 """
545 inspect_command = command + f" show chart '{chart_ref}'"
546
547 if insecure_skip_tls_verify:
548 inspect_command += " --insecure-skip-tls-verify"
549
550 if plain_http:
551 helm_version = module.get_helm_version()
552 if LooseVersion(helm_version) < LooseVersion("3.13.0"):
553 module.fail_json(
554 msg="plain_http requires helm >= 3.13.0, current version is {0}".format(
555 helm_version
556 )
557 )
558 else:
559 inspect_command += " --plain-http"
560
561 rc, out, err = module.run_helm_command(inspect_command)
562
563 return yaml.safe_load(out)
564
565
566 def deploy(
567 module,
568 command,
569 release_name,
570 release_values,
571 chart_name,
572 wait,
573 wait_timeout,
574 disable_hook,
575 force,
576 values_files,
577 history_max,
578 atomic=False,
579 create_namespace=False,
580 replace=False,
581 post_renderer=None,
582 skip_crds=False,
583 timeout=None,
584 dependency_update=None,
585 set_value_args=None,
586 reuse_values=None,
587 reset_values=True,
588 reset_then_reuse_values=False,
589 insecure_skip_tls_verify=False,
590 plain_http=False,
591 take_ownership=False,
592 skip_schema_validation=False,
593 ):
594 """
595 Install/upgrade/rollback release chart
596 """
597 if replace:
598 # '--replace' is not supported by 'upgrade -i'
599 deploy_command = command + " install"
600 if dependency_update:
601 deploy_command += " --dependency-update"
602 else:
603 deploy_command = command + " upgrade -i" # install/upgrade
604 if reset_values:
605 deploy_command += " --reset-values"
606 if take_ownership:
607 deploy_command += " --take-ownership"
608
609 if reuse_values is not None:
610 deploy_command += " --reuse-values=" + str(reuse_values)
611
612 if reset_then_reuse_values:
613 helm_version = module.get_helm_version()
614 if LooseVersion(helm_version) < LooseVersion("3.14.0"):
615 module.fail_json(
616 msg="reset_then_reuse_values requires helm >= 3.14.0, current version is {0}".format(
617 helm_version
618 )
619 )
620 else:
621 deploy_command += " --reset-then-reuse-values"
622
623 if wait:
624 deploy_command += " --wait"
625 if wait_timeout is not None:
626 deploy_command += " --timeout " + wait_timeout
627
628 if atomic:
629 deploy_command += " --atomic"
630
631 if timeout:
632 deploy_command += " --timeout " + timeout
633
634 if force:
635 deploy_command += " --force"
636
637 if replace:
638 deploy_command += " --replace"
639
640 if disable_hook:
641 deploy_command += " --no-hooks"
642
643 if create_namespace:
644 deploy_command += " --create-namespace"
645
646 if insecure_skip_tls_verify:
647 helm_version = module.get_helm_version()
648 if LooseVersion(helm_version) < LooseVersion("3.16.0"):
649 module.fail_json(
650 msg="insecure_skip_tls_verify requires helm >= 3.16.0, current version is {0}".format(
651 helm_version
652 )
653 )
654 else:
655 deploy_command += " --insecure-skip-tls-verify"
656
657 if plain_http:
658 deploy_command += " --plain-http"
659
660 if values_files:
661 for value_file in values_files:
662 deploy_command += " --values=" + value_file
663
664 if release_values != {}:
665 fd, path = tempfile.mkstemp(suffix=".yml")
666 with open(path, "w") as yaml_file:
667 yaml.dump(release_values, yaml_file, default_flow_style=False)
668 deploy_command += " -f=" + path
669 module.add_cleanup_file(path)
670
671 if post_renderer:
672 deploy_command += " --post-renderer=" + post_renderer
673
674 if skip_crds:
675 deploy_command += " --skip-crds"
676
677 if history_max is not None:
678 deploy_command += " --history-max=%s" % str(history_max)
679
680 if set_value_args:
681 deploy_command += " " + set_value_args
682
683 if skip_schema_validation:
684 helm_version = module.get_helm_version()
685 if LooseVersion(helm_version) < LooseVersion("3.16.0"):
686 module.fail_json(
687 msg="skip_schema_validation requires helm >= 3.16.0, current version is {0}".format(
688 helm_version
689 )
690 )
691 else:
692 deploy_command += " --skip-schema-validation"
693
694 deploy_command += " " + release_name + f" '{chart_name}'"
695 return deploy_command
696
697
698 def delete(command, release_name, purge, disable_hook, wait, wait_timeout):
699 """
700 Delete release chart
701 """
702
703 delete_command = command + " uninstall "
704
705 if not purge:
706 delete_command += " --keep-history"
707
708 if disable_hook:
709 delete_command += " --no-hooks"
710
711 if wait:
712 delete_command += " --wait"
713
714 if wait_timeout is not None:
715 delete_command += " --timeout " + wait_timeout
716
717 delete_command += " " + release_name
718
719 return delete_command
720
721
722 def load_values_files(values_files):
723 values = {}
724 for values_file in values_files or []:
725 with open(values_file, "r") as fd:
726 content = yaml.safe_load(fd)
727 if not isinstance(content, dict):
728 continue
729 for k, v in content.items():
730 values[k] = v
731 return values
732
733
734 def get_plugin_version(plugin):
735 """
736 Check if helm plugin is installed and return corresponding version
737 """
738
739 rc, output, err, command = module.get_helm_plugin_list()
740 out = parse_helm_plugin_list(output=output.splitlines())
741
742 if not out:
743 return None
744
745 for line in out:
746 if line["name"] == plugin:
747 return line["version"]
748 return None
749
750
751 def helmdiff_check(
752 module,
753 release_name,
754 chart_ref,
755 release_values,
756 values_files=None,
757 chart_version=None,
758 replace=False,
759 chart_repo_url=None,
760 post_renderer=False,
761 set_value_args=None,
762 reuse_values=None,
763 reset_values=True,
764 reset_then_reuse_values=False,
765 insecure_skip_tls_verify=False,
766 plain_http=False,
767 skip_schema_validation=False,
768 ):
769 """
770 Use helm diff to determine if a release would change by upgrading a chart.
771 """
772 cmd = module.get_helm_binary() + " diff upgrade"
773 cmd += " " + release_name
774 cmd += " " + chart_ref
775
776 if chart_repo_url is not None:
777 cmd += " " + "--repo=" + chart_repo_url
778 if chart_version is not None:
779 cmd += " " + "--version=" + chart_version
780 if not replace:
781 cmd += " " + "--reset-values=" + str(reset_values)
782 if post_renderer:
783 cmd += " --post-renderer=" + post_renderer
784
785 if values_files:
786 for value_file in values_files:
787 cmd += " --values=" + value_file
788
789 if release_values != {}:
790 fd, path = tempfile.mkstemp(suffix=".yml")
791 with open(path, "w") as yaml_file:
792 yaml.dump(release_values, yaml_file, default_flow_style=False)
793 cmd += " -f=" + path
794 module.add_cleanup_file(path)
795
796 if set_value_args:
797 cmd += " " + set_value_args
798
799 if reuse_values:
800 cmd += " --reuse-values"
801
802 if reset_then_reuse_values:
803 helm_diff_version = get_plugin_version("diff")
804 helm_version = module.get_helm_version()
805 fail_msg = ""
806 if LooseVersion(helm_diff_version) < LooseVersion("3.9.12"):
807 fail_msg = "reset_then_reuse_values requires helm diff >= 3.9.12, current version is {0}\n".format(
808 helm_diff_version
809 )
810 if LooseVersion(helm_version) < LooseVersion("3.14.0"):
811 fail_msg += "reset_then_reuse_values requires helm >= 3.14.0, current version is {0}\n".format(
812 helm_version
813 )
814
815 if fail_msg:
816 module.fail_json(msg=fail_msg)
817 else:
818 cmd += " --reset-then-reuse-values"
819
820 if insecure_skip_tls_verify:
821 cmd += " --insecure-skip-tls-verify"
822
823 if skip_schema_validation:
824 helm_version = module.get_helm_version()
825 if LooseVersion(helm_version) < LooseVersion("3.16.0"):
826 module.fail_json(
827 msg="skip_schema_validation requires helm >= 3.16.0, current version is {0}".format(
828 helm_version
829 )
830 )
831 else:
832 cmd += " --skip-schema-validation"
833
834 if plain_http:
835 helm_version = module.get_helm_version()
836 if LooseVersion(helm_version) < LooseVersion("3.13.0"):
837 module.fail_json(
838 msg="plain_http requires helm >= 3.13.0, current version is {0}".format(
839 helm_version
840 )
841 )
842 else:
843 cmd += " --plain-http"
844
845 rc, out, err = module.run_helm_command(cmd)
846 return (len(out.strip()) > 0, out.strip())
847
848
849 def default_check(release_status, chart_info, values=None, values_files=None):
850 """
851 Use default check to determine if release would change by upgrading a chart.
852 """
853 # the 'appVersion' specification is optional in a chart
854 chart_app_version = chart_info.get("appVersion", None)
855 released_app_version = release_status.get("app_version", None)
856
857 # when deployed without an 'appVersion' chart value the 'helm list' command will return the entry `app_version: ""`
858 appversion_is_same = (chart_app_version == released_app_version) or (
859 chart_app_version is None and released_app_version == ""
860 )
861
862 if values_files:
863 values_match = release_status["values"] == load_values_files(values_files)
864 else:
865 values_match = release_status["values"] == values
866 return (
867 not values_match
868 or (chart_info["name"] + "-" + chart_info["version"]) != release_status["chart"]
869 or not appversion_is_same
870 )
871
872
873 def argument_spec():
874 arg_spec = copy.deepcopy(HELM_AUTH_ARG_SPEC)
875 arg_spec.update(
876 dict(
877 chart_ref=dict(type="path"),
878 chart_repo_url=dict(type="str"),
879 chart_version=dict(type="str"),
880 dependency_update=dict(type="bool", default=False, aliases=["dep_up"]),
881 release_name=dict(type="str", required=True, aliases=["name"]),
882 release_namespace=dict(type="str", required=True, aliases=["namespace"]),
883 release_state=dict(
884 default="present", choices=["present", "absent"], aliases=["state"]
885 ),
886 release_values=dict(type="dict", default={}, aliases=["values"]),
887 values_files=dict(type="list", default=[], elements="str"),
888 update_repo_cache=dict(type="bool", default=False),
889 disable_hook=dict(type="bool", default=False),
890 force=dict(type="bool", default=False),
891 purge=dict(type="bool", default=True),
892 wait=dict(type="bool", default=False),
893 wait_timeout=dict(type="str"),
894 timeout=dict(type="str"),
895 atomic=dict(type="bool", default=False),
896 create_namespace=dict(type="bool", default=False),
897 post_renderer=dict(type="str"),
898 replace=dict(type="bool", default=False),
899 skip_crds=dict(type="bool", default=False),
900 history_max=dict(type="int"),
901 set_values=dict(type="list", elements="dict"),
902 reuse_values=dict(type="bool"),
903 reset_values=dict(type="bool", default=True),
904 reset_then_reuse_values=dict(type="bool", default=False),
905 insecure_skip_tls_verify=dict(
906 type="bool", default=False, aliases=["skip_tls_certs_check"]
907 ),
908 plain_http=dict(type="bool", default=False),
909 take_ownership=dict(type="bool", default=False),
910 skip_schema_validation=dict(type="bool", default=False),
911 )
912 )
913 return arg_spec
914
915
916 def main():
917 global module
918 module = AnsibleHelmModule(
919 argument_spec=argument_spec(),
920 required_if=[
921 ("release_state", "present", ["release_name", "chart_ref"]),
922 ("release_state", "absent", ["release_name"]),
923 ],
924 mutually_exclusive=[
925 ("context", "ca_cert"),
926 ("replace", "history_max"),
927 ("wait_timeout", "timeout"),
928 ],
929 supports_check_mode=True,
930 )
931
932 if not IMP_YAML:
933 module.fail_json(msg=missing_required_lib("yaml"), exception=IMP_YAML_ERR)
934
935 # Validate Helm version >=3.0.0
936 module.validate_helm_version()
937
938 changed = False
939
940 chart_ref = module.params.get("chart_ref")
941 chart_repo_url = module.params.get("chart_repo_url")
942 chart_version = module.params.get("chart_version")
943 dependency_update = module.params.get("dependency_update")
944 release_name = module.params.get("release_name")
945 release_state = module.params.get("release_state")
946 release_values = module.params.get("release_values")
947 values_files = module.params.get("values_files")
948 update_repo_cache = module.params.get("update_repo_cache")
949
950 # Helm options
951 disable_hook = module.params.get("disable_hook")
952 force = module.params.get("force")
953 purge = module.params.get("purge")
954 wait = module.params.get("wait")
955 wait_timeout = module.params.get("wait_timeout")
956 atomic = module.params.get("atomic")
957 create_namespace = module.params.get("create_namespace")
958 post_renderer = module.params.get("post_renderer")
959 replace = module.params.get("replace")
960 skip_crds = module.params.get("skip_crds")
961 history_max = module.params.get("history_max")
962 timeout = module.params.get("timeout")
963 set_values = module.params.get("set_values")
964 reuse_values = module.params.get("reuse_values")
965 reset_values = module.params.get("reset_values")
966 reset_then_reuse_values = module.params.get("reset_then_reuse_values")
967 insecure_skip_tls_verify = module.params.get("insecure_skip_tls_verify")
968 plain_http = module.params.get("plain_http")
969 take_ownership = module.params.get("take_ownership")
970 skip_schema_validation = module.params.get("skip_schema_validation")
971
972 if update_repo_cache:
973 run_repo_update(module)
974
975 # Get real/deployed release status
976 all_status = release_state == "absent"
977 release_status = get_release_status(module, release_name, all_status=all_status)
978
979 helm_cmd = module.get_helm_binary()
980
981 if plain_http:
982 helm_version = module.get_helm_version()
983 if LooseVersion(helm_version) < LooseVersion("3.13.0"):
984 module.fail_json(
985 msg="plain_http requires helm >= 3.13.0, current version is {0}".format(
986 helm_version
987 )
988 )
989 if take_ownership:
990 helm_version = module.get_helm_version()
991 if LooseVersion(helm_version) < LooseVersion("3.17.0"):
992 module.fail_json(
993 msg="take_ownership requires helm >= 3.17.0, current version is {0}".format(
994 helm_version
995 )
996 )
997
998 if skip_schema_validation:
999 helm_version = module.get_helm_version()
1000 if LooseVersion(helm_version) < LooseVersion("3.16.0"):
1001 module.fail_json(
1002 msg="skip_schema_validation requires helm >= 3.16.0, current version is {0}".format(
1003 helm_version
1004 )
1005 )
1006
1007 opt_result = {}
1008 if release_state == "absent" and release_status is not None:
1009 # skip release statuses 'uninstalled' and 'uninstalling'
1010 if not release_status["status"].startswith("uninstall"):
1011 if replace:
1012 module.fail_json(msg="replace is not applicable when state is absent")
1013
1014 if wait:
1015 helm_version = module.get_helm_version()
1016 if LooseVersion(helm_version) < LooseVersion("3.7.0"):
1017 module.warn(
1018 "helm uninstall support option --wait for helm release >= 3.7.0"
1019 )
1020 wait = False
1021
1022 helm_cmd = delete(
1023 helm_cmd, release_name, purge, disable_hook, wait, wait_timeout
1024 )
1025 changed = True
1026 elif release_state == "present":
1027 if chart_version is not None:
1028 helm_cmd += " --version=" + chart_version
1029
1030 if chart_repo_url is not None:
1031 helm_cmd += " --repo=" + chart_repo_url
1032
1033 # Fetch chart info to have real version and real name for chart_ref from archive, folder or url
1034 chart_info = fetch_chart_info(
1035 module, helm_cmd, chart_ref, insecure_skip_tls_verify, plain_http
1036 )
1037
1038 if dependency_update:
1039 if chart_info.get("dependencies"):
1040 # Can't use '--dependency-update' with 'helm upgrade' that is the
1041 # default chart install method, so if chart_repo_url is defined
1042 # we can't use the dependency update command. But, in the near future
1043 # we can get rid of this method and use only '--dependency-update'
1044 # option. Please see https://github.com/helm/helm/pull/8810
1045 if not chart_repo_url and not re.fullmatch(
1046 r"^http[s]*://[\w.:/?&=-]+$", chart_ref
1047 ):
1048 run_dep_update(module, chart_ref)
1049
1050 # To not add --dependency-update option in the deploy function
1051 dependency_update = False
1052 else:
1053 module.warn(
1054 "This is a not stable feature with 'chart_repo_url'. Please consider to use dependency update with on-disk charts"
1055 )
1056 if not replace:
1057 msg_fail = (
1058 "'--dependency-update' hasn't been supported yet with 'helm upgrade'. "
1059 "Please use 'helm install' instead by adding 'replace' option"
1060 )
1061 module.fail_json(msg=msg_fail)
1062 else:
1063 module.warn(
1064 "There is no dependencies block defined in Chart.yaml. Dependency update will not be performed. "
1065 "Please consider add dependencies block or disable dependency_update to remove this warning."
1066 )
1067
1068 set_value_args = None
1069 if set_values:
1070 set_value_args = module.get_helm_set_values_args(set_values)
1071
1072 if release_status is None: # Not installed
1073 helm_cmd = deploy(
1074 module,
1075 helm_cmd,
1076 release_name,
1077 release_values,
1078 chart_ref,
1079 wait,
1080 wait_timeout,
1081 disable_hook,
1082 False,
1083 values_files=values_files,
1084 atomic=atomic,
1085 create_namespace=create_namespace,
1086 post_renderer=post_renderer,
1087 replace=replace,
1088 dependency_update=dependency_update,
1089 skip_crds=skip_crds,
1090 history_max=history_max,
1091 timeout=timeout,
1092 set_value_args=set_value_args,
1093 reuse_values=reuse_values,
1094 reset_values=reset_values,
1095 reset_then_reuse_values=reset_then_reuse_values,
1096 insecure_skip_tls_verify=insecure_skip_tls_verify,
1097 plain_http=plain_http,
1098 take_ownership=take_ownership,
1099 skip_schema_validation=skip_schema_validation,
1100 )
1101 changed = True
1102
1103 else:
1104 helm_diff_version = get_plugin_version("diff")
1105 helm_version_compatible = module.is_helm_version_compatible_with_helm_diff(
1106 helm_diff_version
1107 )
1108 if (
1109 helm_diff_version
1110 and helm_version_compatible
1111 and (
1112 not chart_repo_url
1113 or (
1114 chart_repo_url
1115 and LooseVersion(helm_diff_version) >= LooseVersion("3.4.1")
1116 )
1117 )
1118 ):
1119 would_change, prepared = helmdiff_check(
1120 module,
1121 release_name,
1122 chart_ref,
1123 release_values,
1124 values_files,
1125 chart_version,
1126 replace,
1127 chart_repo_url,
1128 post_renderer,
1129 set_value_args,
1130 reuse_values=reuse_values,
1131 reset_values=reset_values,
1132 reset_then_reuse_values=reset_then_reuse_values,
1133 insecure_skip_tls_verify=insecure_skip_tls_verify,
1134 plain_http=plain_http,
1135 skip_schema_validation=skip_schema_validation,
1136 )
1137 if would_change and module._diff:
1138 opt_result["diff"] = {"prepared": prepared}
1139 else:
1140 if helm_diff_version and not helm_version_compatible:
1141 module.warn(
1142 "Idempotency checks are currently disabled due to a version mismatch."
1143 f" Helm version {module.get_helm_version()} requires helm-diff >= 3.14.0,"
1144 f" but the environment is currently running {helm_diff_version}."
1145 " Please align the plugin versions to restore standard behavior."
1146 )
1147 else:
1148 module.warn(
1149 "The default idempotency check can fail to report changes in certain cases. "
1150 "Install helm diff >= 3.4.1 for better results."
1151 )
1152 would_change = default_check(
1153 release_status, chart_info, release_values, values_files
1154 )
1155
1156 if force or would_change:
1157 helm_cmd = deploy(
1158 module,
1159 helm_cmd,
1160 release_name,
1161 release_values,
1162 chart_ref,
1163 wait,
1164 wait_timeout,
1165 disable_hook,
1166 force,
1167 values_files=values_files,
1168 atomic=atomic,
1169 create_namespace=create_namespace,
1170 post_renderer=post_renderer,
1171 replace=replace,
1172 skip_crds=skip_crds,
1173 history_max=history_max,
1174 timeout=timeout,
1175 dependency_update=dependency_update,
1176 set_value_args=set_value_args,
1177 reuse_values=reuse_values,
1178 reset_values=reset_values,
1179 reset_then_reuse_values=reset_then_reuse_values,
1180 insecure_skip_tls_verify=insecure_skip_tls_verify,
1181 plain_http=plain_http,
1182 take_ownership=take_ownership,
1183 skip_schema_validation=skip_schema_validation,
1184 )
1185 changed = True
1186
1187 if module.check_mode:
1188 check_status = {
1189 "values": {"current": {}, "declared": {}},
1190 "release_values": {"current": {}, "declared": {}},
1191 }
1192 if release_status:
1193 check_status["values"]["current"] = release_status["release_values"]
1194 check_status["values"]["declared"] = release_status
1195 check_status["release_values"]["current"] = release_status["release_values"]
1196 check_status["release_values"]["declared"] = release_status
1197
1198 module.exit_json(
1199 changed=changed,
1200 command=helm_cmd,
1201 status=check_status,
1202 stdout="",
1203 stderr="",
1204 **opt_result,
1205 )
1206 elif not changed:
1207 module.exit_json(
1208 changed=False,
1209 status=release_status,
1210 stdout="",
1211 stderr="",
1212 command=helm_cmd,
1213 **opt_result,
1214 )
1215
1216 rc, out, err = module.run_helm_command(helm_cmd)
1217
1218 module.exit_json(
1219 changed=changed,
1220 stdout=out,
1221 stderr=err,
1222 status=get_release_status(module, release_name, all_status=True),
1223 command=helm_cmd,
1224 **opt_result,
1225 )
1226
1227
1228 if __name__ == "__main__":
1229 main()