Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2020, 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_repository
14
15 short_description: Manage Helm repositories.
16
17 version_added: 0.11.0
18
19 author:
20 - Lucas Boisserie (@LucasBoisserie)
21
22 requirements:
23 - "helm >= 3.0.0 (https://github.com/helm/helm/releases)"
24 - "yaml (https://pypi.org/project/PyYAML/)"
25
26 description:
27 - Manage Helm repositories.
28
29 options:
30 binary_path:
31 description:
32 - The path of a helm binary to use.
33 required: false
34 type: path
35 repo_name:
36 description:
37 - Chart repository name.
38 required: true
39 type: str
40 aliases: [ name ]
41 repo_url:
42 description:
43 - Chart repository url
44 type: str
45 aliases: [ url ]
46 repo_username:
47 description:
48 - Chart repository username for repository with basic auth.
49 - Required if chart_repo_password is specified.
50 required: false
51 type: str
52 aliases: [ username ]
53 repo_password:
54 description:
55 - Chart repository password for repository with basic auth.
56 - Required if chart_repo_username is specified.
57 required: false
58 type: str
59 aliases: [ password ]
60 repo_state:
61 choices: ['present', 'absent']
62 description:
63 - Desired state of repository.
64 required: false
65 default: present
66 aliases: [ state ]
67 type: str
68 pass_credentials:
69 description:
70 - Pass credentials to all domains.
71 required: false
72 default: false
73 type: bool
74 version_added: 2.3.0
75 host:
76 description:
77 - Provide a URL for accessing the API. Can also be specified via C(K8S_AUTH_HOST) environment variable.
78 type: str
79 version_added: 2.3.0
80 api_key:
81 description:
82 - Token used to authenticate with the API. Can also be specified via C(K8S_AUTH_API_KEY) environment variable.
83 type: str
84 version_added: 2.3.0
85 validate_certs:
86 description:
87 - Whether or not to verify the API server's SSL certificates. Can also be specified via C(K8S_AUTH_VERIFY_SSL)
88 environment variable.
89 type: bool
90 aliases: [ verify_ssl ]
91 default: True
92 version_added: 2.3.0
93 ca_cert:
94 description:
95 - Path to a CA certificate used to authenticate with the API. The full certificate chain must be provided to
96 avoid certificate validation errors. Can also be specified via C(K8S_AUTH_SSL_CA_CERT) environment variable.
97 type: path
98 aliases: [ ssl_ca_cert ]
99 version_added: 2.3.0
100 context:
101 description:
102 - Helm option to specify which kubeconfig context to use.
103 - If the value is not specified in the task, the value of environment variable C(K8S_AUTH_CONTEXT) will be used instead.
104 type: str
105 aliases: [ kube_context ]
106 version_added: 2.4.0
107 kubeconfig:
108 description:
109 - Helm option to specify kubeconfig path to use.
110 - If the value is not specified in the task, the value of environment variable C(K8S_AUTH_KUBECONFIG) will be used instead.
111 - The configuration can be provided as dictionary.
112 type: raw
113 aliases: [ kubeconfig_path ]
114 version_added: 2.4.0
115 force_update:
116 description:
117 - Whether or not to replace (overwrite) the repo if it already exists.
118 type: bool
119 aliases: [ force ]
120 default: False
121 version_added: 2.4.0
122 insecure_skip_tls_verify:
123 description:
124 - Skip tls certificate checks for the repository url.
125 type: bool
126 default: False
127 aliases: [ skip_tls_certs_check ]
128 version_added: "5.3.0"
129 """
130
131 EXAMPLES = r"""
132 - name: Add a repository
133 kubernetes.core.helm_repository:
134 name: stable
135 repo_url: https://kubernetes.github.io/ingress-nginx
136
137 - name: Add Red Hat Helm charts repository
138 kubernetes.core.helm_repository:
139 name: redhat-charts
140 repo_url: https://redhat-developer.github.com/redhat-helm-charts
141 """
142
143 RETURN = r"""
144 stdout:
145 type: str
146 description: Full `helm` command stdout, in case you want to display it or examine the event log
147 returned: always
148 sample: '"bitnami" has been added to your repositories'
149 stdout_lines:
150 type: list
151 description: Full `helm` command stdout in list, in case you want to display it or examine the event log
152 returned: always
153 sample: ["\"bitnami\" has been added to your repositories"]
154 stderr:
155 type: str
156 description: Full `helm` command stderr, in case you want to display it or examine the event log
157 returned: always
158 sample: ''
159 stderr_lines:
160 type: list
161 description: Full `helm` command stderr in list, in case you want to display it or examine the event log
162 returned: always
163 sample: [""]
164 command:
165 type: str
166 description: Full `helm` command built by this module, in case you want to re-run the command outside the module or debug a problem.
167 returned: always
168 sample: '/usr/local/bin/helm repo add bitnami https://charts.bitnami.com/bitnami'
169 msg:
170 type: str
171 description: Error message returned by `helm` command
172 returned: on failure
173 sample: 'Repository already have a repository named bitnami'
174 """
175
176 import copy
177 import traceback
178
179 try:
180 import yaml
181
182 IMP_YAML = True
183 IMP_YAML_ERR = None
184 except ImportError:
185 IMP_YAML_ERR = traceback.format_exc()
186 IMP_YAML = False
187
188 from ansible.module_utils.basic import missing_required_lib
189 from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
190 AnsibleHelmModule,
191 )
192 from ansible_collections.kubernetes.core.plugins.module_utils.helm_args_common import (
193 HELM_AUTH_ARG_SPEC,
194 HELM_AUTH_MUTUALLY_EXCLUSIVE,
195 )
196
197
198 # Get repository from all repositories added
199 def get_repository(state, repo_name):
200 if state is not None:
201 for repository in state:
202 if repository["name"] == repo_name:
203 return repository
204 return None
205
206
207 # Get repository status
208 def get_repository_status(module, repository_name):
209 list_command = module.get_helm_binary() + " repo list --output=yaml"
210
211 rc, out, err = module.run_helm_command(list_command, fails_on_error=False)
212
213 # no repo => rc=1 and 'no repositories to show' in output
214 if rc == 1 and "no repositories to show" in err:
215 return None
216 elif rc != 0:
217 module.fail_json(
218 msg="Failure when executing Helm command. Exited {0}.\nstdout: {1}\nstderr: {2}".format(
219 rc, out, err
220 ),
221 command=list_command,
222 )
223
224 return get_repository(yaml.safe_load(out), repository_name)
225
226
227 # Install repository
228 def install_repository(
229 command,
230 repository_name,
231 repository_url,
232 repository_username,
233 repository_password,
234 pass_credentials,
235 force_update,
236 insecure_skip_tls_verify,
237 ):
238 install_command = command + " repo add " + repository_name + " " + repository_url
239
240 if repository_username is not None and repository_password is not None:
241 install_command += " --username=" + repository_username
242 install_command += " --password=" + repository_password
243
244 if pass_credentials:
245 install_command += " --pass-credentials"
246
247 if force_update:
248 install_command += " --force-update"
249
250 if insecure_skip_tls_verify:
251 install_command += " --insecure-skip-tls-verify"
252
253 return install_command
254
255
256 # Delete repository
257 def delete_repository(command, repository_name):
258 remove_command = command + " repo rm " + repository_name
259
260 return remove_command
261
262
263 def argument_spec():
264 arg_spec = copy.deepcopy(HELM_AUTH_ARG_SPEC)
265 arg_spec.update(
266 dict(
267 repo_name=dict(type="str", aliases=["name"], required=True),
268 repo_url=dict(type="str", aliases=["url"]),
269 repo_username=dict(type="str", aliases=["username"]),
270 repo_password=dict(type="str", aliases=["password"], no_log=True),
271 repo_state=dict(
272 default="present", choices=["present", "absent"], aliases=["state"]
273 ),
274 pass_credentials=dict(type="bool", default=False, no_log=True),
275 force_update=dict(type="bool", default=False, aliases=["force"]),
276 insecure_skip_tls_verify=dict(
277 type="bool", default=False, aliases=["skip_tls_certs_check"]
278 ),
279 )
280 )
281 return arg_spec
282
283
284 def main():
285 global module
286
287 module = AnsibleHelmModule(
288 argument_spec=argument_spec(),
289 required_together=[["repo_username", "repo_password"]],
290 required_if=[("repo_state", "present", ["repo_url"])],
291 mutually_exclusive=HELM_AUTH_MUTUALLY_EXCLUSIVE,
292 supports_check_mode=True,
293 )
294
295 if not IMP_YAML:
296 module.fail_json(msg=missing_required_lib("yaml"), exception=IMP_YAML_ERR)
297
298 # Validate Helm version >= 3.0.0
299 module.validate_helm_version()
300
301 changed = False
302
303 repo_name = module.params.get("repo_name")
304 repo_url = module.params.get("repo_url")
305 repo_username = module.params.get("repo_username")
306 repo_password = module.params.get("repo_password")
307 repo_state = module.params.get("repo_state")
308 pass_credentials = module.params.get("pass_credentials")
309 force_update = module.params.get("force_update")
310 insecure_skip_tls_verify = module.params.get("insecure_skip_tls_verify")
311
312 helm_cmd = module.get_helm_binary()
313
314 repository_status = get_repository_status(module, repo_name)
315
316 if repo_state == "absent" and repository_status is not None:
317 helm_cmd = delete_repository(helm_cmd, repo_name)
318 changed = True
319 elif repo_state == "present":
320 if repository_status is None or force_update:
321 helm_cmd = install_repository(
322 helm_cmd,
323 repo_name,
324 repo_url,
325 repo_username,
326 repo_password,
327 pass_credentials,
328 force_update,
329 insecure_skip_tls_verify,
330 )
331 changed = True
332 elif repository_status["url"] != repo_url:
333 module.fail_json(
334 msg="Repository already have a repository named {0}".format(repo_name)
335 )
336
337 if module.check_mode:
338 module.exit_json(changed=changed)
339 elif not changed:
340 module.exit_json(changed=False, repo_name=repo_name, repo_url=repo_url)
341
342 rc, out, err = module.run_helm_command(helm_cmd)
343
344 if repo_password is not None:
345 helm_cmd = helm_cmd.replace(repo_password, "******")
346
347 if rc != 0:
348 module.fail_json(
349 msg="Failure when executing Helm command. Exited {0}.\nstdout: {1}\nstderr: {2}".format(
350 rc, out, err
351 ),
352 command=helm_cmd,
353 )
354
355 module.exit_json(changed=changed, stdout=out, stderr=err, command=helm_cmd)
356
357
358 if __name__ == "__main__":
359 main()