Debian Codegraph @

ansible_collections/kubernetes/core/plugins/connection/kubectl.py

raw symbols SCIP
1 # Based on the docker connection plugin
2 #
3 # Connection plugin for configuring kubernetes containers with kubectl
4 # (c) 2017, XuXinkun <[email protected]>
5 #
6 # This file is part of Ansible
7 #
8 # Ansible is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Ansible is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
20 from __future__ import absolute_import, division, print_function
21
22 __metaclass__ = type
23
24 DOCUMENTATION = r"""
25 author:
26 - xuxinkun (@xuxinkun)
27
28 name: kubectl
29
30 short_description: Execute tasks in pods running on Kubernetes.
31
32 description:
33 - Use the kubectl exec command to run tasks in, or put/fetch files to, pods running on the Kubernetes
34 container platform.
35
36 requirements:
37 - kubectl (go binary)
38
39 options:
40 kubectl_pod:
41 description:
42 - Pod name.
43 - Required when the host name does not match pod name.
44 default: ''
45 vars:
46 - name: ansible_kubectl_pod
47 env:
48 - name: K8S_AUTH_POD
49 kubectl_container:
50 description:
51 - Container name.
52 - Required when a pod contains more than one container.
53 default: ''
54 vars:
55 - name: ansible_kubectl_container
56 env:
57 - name: K8S_AUTH_CONTAINER
58 kubectl_namespace:
59 description:
60 - The namespace of the pod
61 default: ''
62 vars:
63 - name: ansible_kubectl_namespace
64 env:
65 - name: K8S_AUTH_NAMESPACE
66 kubectl_extra_args:
67 description:
68 - Extra arguments to pass to the kubectl command line.
69 - Please be aware that this passes information directly on the command line and it could expose sensitive data.
70 default: ''
71 vars:
72 - name: ansible_kubectl_extra_args
73 env:
74 - name: K8S_AUTH_EXTRA_ARGS
75 kubectl_local_env_vars:
76 description:
77 - Local enviromantal variable to be passed locally to the kubectl command line.
78 - Please be aware that this passes information directly on the command line and it could expose sensitive data.
79 default: {}
80 type: dict
81 version_added: 3.1.0
82 vars:
83 - name: ansible_kubectl_local_env_vars
84 kubectl_kubeconfig:
85 description:
86 - Path to a kubectl config file. Defaults to I(~/.kube/config)
87 - The configuration can be provided as dictionary. Added in version 2.4.0.
88 default: ''
89 vars:
90 - name: ansible_kubectl_kubeconfig
91 - name: ansible_kubectl_config
92 env:
93 - name: K8S_AUTH_KUBECONFIG
94 kubectl_context:
95 description:
96 - The name of a context found in the K8s config file.
97 default: ''
98 vars:
99 - name: ansible_kubectl_context
100 env:
101 - name: K8S_AUTH_CONTEXT
102 kubectl_host:
103 description:
104 - URL for accessing the API.
105 default: ''
106 vars:
107 - name: ansible_kubectl_host
108 - name: ansible_kubectl_server
109 env:
110 - name: K8S_AUTH_HOST
111 - name: K8S_AUTH_SERVER
112 kubectl_username:
113 description:
114 - Provide a username for authenticating with the API.
115 default: ''
116 vars:
117 - name: ansible_kubectl_username
118 - name: ansible_kubectl_user
119 env:
120 - name: K8S_AUTH_USERNAME
121 kubectl_password:
122 description:
123 - Provide a password for authenticating with the API.
124 - Please be aware that this passes information directly on the command line and it could expose sensitive data.
125 We recommend using the file based authentication options instead.
126 default: ''
127 vars:
128 - name: ansible_kubectl_password
129 env:
130 - name: K8S_AUTH_PASSWORD
131 kubectl_token:
132 description:
133 - API authentication bearer token.
134 - Please be aware that this passes information directly on the command line and it could expose sensitive data.
135 We recommend using the file based authentication options instead.
136 vars:
137 - name: ansible_kubectl_token
138 - name: ansible_kubectl_api_key
139 env:
140 - name: K8S_AUTH_TOKEN
141 - name: K8S_AUTH_API_KEY
142 client_cert:
143 description:
144 - Path to a certificate used to authenticate with the API.
145 default: ''
146 vars:
147 - name: ansible_kubectl_cert_file
148 - name: ansible_kubectl_client_cert
149 env:
150 - name: K8S_AUTH_CERT_FILE
151 aliases: [ kubectl_cert_file ]
152 client_key:
153 description:
154 - Path to a key file used to authenticate with the API.
155 default: ''
156 vars:
157 - name: ansible_kubectl_key_file
158 - name: ansible_kubectl_client_key
159 env:
160 - name: K8S_AUTH_KEY_FILE
161 aliases: [ kubectl_key_file ]
162 ca_cert:
163 description:
164 - Path to a CA certificate used to authenticate with the API.
165 default: ''
166 vars:
167 - name: ansible_kubectl_ssl_ca_cert
168 - name: ansible_kubectl_ca_cert
169 env:
170 - name: K8S_AUTH_SSL_CA_CERT
171 aliases: [ kubectl_ssl_ca_cert ]
172 validate_certs:
173 description:
174 - Whether or not to verify the API server's SSL certificate. Defaults to I(true).
175 default: ''
176 vars:
177 - name: ansible_kubectl_verify_ssl
178 - name: ansible_kubectl_validate_certs
179 env:
180 - name: K8S_AUTH_VERIFY_SSL
181 aliases: [ kubectl_verify_ssl ]
182 """
183
184 EXAMPLES = r"""
185
186 - name: Run a command in a pod using local kubectl with kubeconfig file ~/.kube/config
187 hosts: localhost
188 gather_facts: no
189 vars:
190 ansible_connection: kubernetes.core.kubectl
191 ansible_kubectl_namespace: my-namespace
192 ansible_kubectl_pod: my-pod
193 ansible_kubectl_container: my-container
194 tasks:
195 # be aware that the command is executed as the user that started the container
196 # and requires python to be installed in the image
197 - name: Run a command in a pod
198 ansible.builtin.command: echo "Hello, World!"
199
200 - name: Run a command in a pod using local kubectl with inventory variables
201 # Example inventory:
202 # k8s:
203 # hosts:
204 # foo.example.com:
205 # ansible_connection: kubernetes.core.kubectl
206 # ansible_kubectl_kubeconfig: /root/.kube/foo.example.com.config
207 # ansible_kubectl_pod: my-foo-pod
208 # ansible_kubectl_container: my-foo-container
209 # ansible_kubectl_namespace: my-foo-namespace
210 # bar.example.com:
211 # ansible_connection: kubernetes.core.kubectl
212 # ansible_kubectl_kubeconfig: /root/.kube/bar.example.com.config
213 # ansible_kubectl_pod: my-bar-pod
214 # ansible_kubectl_container: my-bar-container
215 # ansible_kubectl_namespace: my-bar-namespace
216 hosts: k8s
217 gather_facts: no
218 tasks:
219 # be aware that the command is executed as the user that started the container
220 # and requires python to be installed in the image
221 - name: Run a command in a pod
222 ansible.builtin.command: echo "Hello, World!"
223
224 - name: Run a command in a pod using dynamic inventory
225 hosts: localhost
226 gather_facts: no
227 vars:
228 kubeconfig: /root/.kube/config
229 namespace: my-namespace
230 my_app: my-app
231 tasks:
232 - name: Get My App pod info based on label
233 kubernetes.core.k8s_info:
234 kubeconfig: "{{ kubeconfig }}"
235 namespace: "{{ namespace }}"
236 kind: Pod
237 label_selectors: app.kubernetes.io/name = "{{ my_app }}"
238 register: my_app_pod
239
240 - name: Get My App pod name
241 ansible.builtin.set_fact:
242 my_app_pod_name: "{{ my_app_pod.resources[0].metadata.name }}"
243
244 - name: Add My App pod to inventory
245 ansible.builtin.add_host:
246 name: "{{ my_app_pod_name }}"
247 ansible_connection: kubernetes.core.kubectl
248 ansible_kubectl_kubeconfig: "{{ kubeconfig }}"
249 ansible_kubectl_pod: "{{ my_app_pod_name }}"
250 ansible_kubectl_namespace: "{{ namespace }}"
251
252 - name: Run a command in My App pod
253 # be aware that the command is executed as the user that started the container
254 # and requires python to be installed in the image
255 ansible.builtin.command: echo "Hello, World!"
256 delegate_to: "{{ my_app_pod_name }}"
257 """
258
259 import json
260 import os
261 import os.path
262 import shutil
263 import subprocess
264 import tempfile
265
266 from ansible.errors import AnsibleError, AnsibleFileNotFound
267 from ansible.module_utils.common.text.converters import to_bytes
268 from ansible.module_utils.parsing.convert_bool import boolean
269 from ansible.module_utils.six.moves import shlex_quote
270 from ansible.parsing.yaml.loader import AnsibleLoader
271 from ansible.plugins.connection import BUFSIZE, ConnectionBase
272 from ansible.utils.display import Display
273
274 display = Display()
275
276
277 CONNECTION_TRANSPORT = "kubectl"
278
279 CONNECTION_OPTIONS = {
280 "kubectl_container": "-c",
281 "kubectl_namespace": "-n",
282 "kubectl_kubeconfig": "--kubeconfig",
283 "kubectl_context": "--context",
284 "kubectl_host": "--server",
285 "kubectl_username": "--username",
286 "kubectl_password": "--password",
287 "client_cert": "--client-certificate",
288 "client_key": "--client-key",
289 "ca_cert": "--certificate-authority",
290 "validate_certs": "--insecure-skip-tls-verify",
291 "kubectl_token": "--token",
292 }
293
294
295 class Connection(ConnectionBase):
296 """Local kubectl based connections"""
297
298 transport = CONNECTION_TRANSPORT
299 connection_options = CONNECTION_OPTIONS
300 documentation = DOCUMENTATION
301 has_pipelining = True
302 transport_cmd = None
303
304 def __init__(self, play_context, new_stdin, *args, **kwargs):
305 super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs)
306
307 # Note: kubectl runs commands as the user that started the container.
308 # It is impossible to set the remote user for a kubectl connection.
309 cmd_arg = "{0}_command".format(self.transport)
310 self.transport_cmd = kwargs.get(cmd_arg, shutil.which(self.transport))
311 if not self.transport_cmd:
312 raise AnsibleError("{0} command not found in PATH".format(self.transport))
313 self._file_to_delete = None
314
315 def delete_temporary_file(self):
316 if self._file_to_delete is not None:
317 os.remove(self._file_to_delete)
318 self._file_to_delete = None
319
320 def _build_exec_cmd(self, cmd):
321 """Build the local kubectl exec command to run cmd on remote_host"""
322 local_cmd = [self.transport_cmd]
323 censored_local_cmd = [self.transport_cmd]
324
325 # Build command options based on doc string
326 doc_yaml = AnsibleLoader(self.documentation).get_single_data()
327 for key in doc_yaml.get("options"):
328 if key == "validate_certs" and self.get_option(key) != "":
329 # Translate validate_certs to --insecure-skip-tls-verify flag
330 # validate_certs=True means verify certs (don't skip verification)
331 # validate_certs=False means don't verify certs (skip verification)
332 validate_certs_value = boolean(self.get_option(key), strict=False)
333 skip_verify_ssl = not validate_certs_value
334 local_cmd.append(
335 "{0}={1}".format(
336 self.connection_options[key], str(skip_verify_ssl).lower()
337 )
338 )
339 censored_local_cmd.append(
340 "{0}={1}".format(
341 self.connection_options[key], str(skip_verify_ssl).lower()
342 )
343 )
344 elif key.endswith("kubeconfig") and self.get_option(key) != "":
345 kubeconfig_path = self.get_option(key)
346 if isinstance(kubeconfig_path, dict):
347 fd, tmpfile = tempfile.mkstemp()
348 with os.fdopen(fd, "w") as fp:
349 json.dump(kubeconfig_path, fp)
350 kubeconfig_path = tmpfile
351 self._file_to_delete = tmpfile
352
353 cmd_arg = self.connection_options[key]
354 local_cmd += [cmd_arg, kubeconfig_path]
355 censored_local_cmd += [cmd_arg, kubeconfig_path]
356 elif (
357 not key.endswith("container")
358 and self.get_option(key)
359 and self.connection_options.get(key)
360 ):
361 cmd_arg = self.connection_options[key]
362 local_cmd += [cmd_arg, self.get_option(key)]
363 # Redact password and token from console log
364 if key.endswith(("_token", "_password")):
365 censored_local_cmd += [cmd_arg, "********"]
366 else:
367 censored_local_cmd += [cmd_arg, self.get_option(key)]
368
369 extra_args_name = "{0}_extra_args".format(self.transport)
370 if self.get_option(extra_args_name):
371 local_cmd += self.get_option(extra_args_name).split(" ")
372 censored_local_cmd += self.get_option(extra_args_name).split(" ")
373
374 pod = self.get_option("{0}_pod".format(self.transport))
375 if not pod:
376 pod = self._play_context.remote_addr
377 # -i is needed to keep stdin open which allows pipelining to work
378 local_cmd += ["exec", "-i", pod]
379 censored_local_cmd += ["exec", "-i", pod]
380
381 # if the pod has more than one container, then container is required
382 container_arg_name = "{0}_container".format(self.transport)
383 if self.get_option(container_arg_name):
384 local_cmd += ["-c", self.get_option(container_arg_name)]
385 censored_local_cmd += ["-c", self.get_option(container_arg_name)]
386
387 local_cmd += ["--"] + cmd
388 censored_local_cmd += ["--"] + cmd
389
390 return local_cmd, censored_local_cmd
391
392 def _local_env(self):
393 """Return a dict of local environment variables to pass to the kubectl command"""
394 local_env = {}
395 local_local_env_vars_name = "{0}_local_env_vars".format(self.transport)
396 local_env_vars = self.get_option(local_local_env_vars_name)
397 if local_env_vars:
398 if isinstance(local_env_vars, dict):
399 local_env_vars = json.dumps(local_env_vars)
400 local_env = os.environ.copy()
401 local_env.update(json.loads(local_env_vars))
402 return local_env
403 return None
404
405 def _connect(self, port=None):
406 """Connect to the container. Nothing to do"""
407 super(Connection, self)._connect()
408 if not self._connected:
409 display.vvv(
410 "ESTABLISH {0} CONNECTION".format(self.transport),
411 host=self._play_context.remote_addr,
412 )
413 self._connected = True
414
415 def exec_command(self, cmd, in_data=None, sudoable=False):
416 """Run a command in the container"""
417 super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
418
419 local_cmd, censored_local_cmd = self._build_exec_cmd(
420 [self._play_context.executable, "-c", cmd]
421 )
422
423 display.vvv(
424 "EXEC %s" % (censored_local_cmd,), host=self._play_context.remote_addr
425 )
426 local_cmd = [to_bytes(i, errors="surrogate_or_strict") for i in local_cmd]
427 p = subprocess.Popen(
428 local_cmd,
429 shell=False,
430 stdin=subprocess.PIPE,
431 stdout=subprocess.PIPE,
432 stderr=subprocess.PIPE,
433 env=self._local_env(),
434 )
435
436 stdout, stderr = p.communicate(in_data)
437 self.delete_temporary_file()
438 return (p.returncode, stdout, stderr)
439
440 def _prefix_login_path(self, remote_path):
441 """Make sure that we put files into a standard path
442
443 If a path is relative, then we need to choose where to put it.
444 ssh chooses $HOME but we aren't guaranteed that a home dir will
445 exist in any given chroot. So for now we're choosing "/" instead.
446 This also happens to be the former default.
447
448 Can revisit using $HOME instead if it's a problem
449 """
450 if not remote_path.startswith(os.path.sep):
451 remote_path = os.path.join(os.path.sep, remote_path)
452 return os.path.normpath(remote_path)
453
454 def put_file(self, in_path, out_path):
455 """Transfer a file from local to the container"""
456 super(Connection, self).put_file(in_path, out_path)
457 display.vvv(
458 "PUT %s TO %s" % (in_path, out_path), host=self._play_context.remote_addr
459 )
460
461 out_path = self._prefix_login_path(out_path)
462 if not os.path.exists(to_bytes(in_path, errors="surrogate_or_strict")):
463 raise AnsibleFileNotFound("file or module does not exist: %s" % in_path)
464
465 out_path = shlex_quote(out_path)
466 # kubectl doesn't have native support for copying files into
467 # running containers, so we use kubectl exec to implement this
468 with open(to_bytes(in_path, errors="surrogate_or_strict"), "rb") as in_file:
469 if not os.fstat(in_file.fileno()).st_size:
470 count = " count=0"
471 else:
472 count = ""
473 args, dummy = self._build_exec_cmd(
474 [
475 self._play_context.executable,
476 "-c",
477 "dd of=%s bs=%s%s && sleep 0" % (out_path, BUFSIZE, count),
478 ]
479 )
480 args = [to_bytes(i, errors="surrogate_or_strict") for i in args]
481 try:
482 p = subprocess.Popen(
483 args,
484 stdin=in_file,
485 stdout=subprocess.PIPE,
486 stderr=subprocess.PIPE,
487 env=self._local_env(),
488 )
489 except OSError:
490 raise AnsibleError(
491 "kubectl connection requires dd command in the container to put files"
492 )
493 stdout, stderr = p.communicate()
494 self.delete_temporary_file()
495
496 if p.returncode != 0:
497 raise AnsibleError(
498 "failed to transfer file %s to %s:\n%s\n%s"
499 % (in_path, out_path, stdout, stderr)
500 )
501
502 def fetch_file(self, in_path, out_path):
503 """Fetch a file from container to local."""
504 super(Connection, self).fetch_file(in_path, out_path)
505 display.vvv(
506 "FETCH %s TO %s" % (in_path, out_path), host=self._play_context.remote_addr
507 )
508
509 in_path = self._prefix_login_path(in_path)
510 out_dir = os.path.dirname(out_path)
511
512 # kubectl doesn't have native support for fetching files from
513 # running containers, so we use kubectl exec to implement this
514 args, dummy = self._build_exec_cmd(
515 [self._play_context.executable, "-c", "dd if=%s bs=%s" % (in_path, BUFSIZE)]
516 )
517 args = [to_bytes(i, errors="surrogate_or_strict") for i in args]
518 actual_out_path = os.path.join(out_dir, os.path.basename(in_path))
519 with open(
520 to_bytes(actual_out_path, errors="surrogate_or_strict"), "wb"
521 ) as out_file:
522 try:
523 p = subprocess.Popen(
524 args,
525 stdin=subprocess.PIPE,
526 stdout=out_file,
527 stderr=subprocess.PIPE,
528 env=self._local_env(),
529 )
530 except OSError:
531 raise AnsibleError(
532 "{0} connection requires dd command in the container to fetch files".format(
533 self.transport
534 )
535 )
536 stdout, stderr = p.communicate()
537 self.delete_temporary_file()
538
539 if p.returncode != 0:
540 raise AnsibleError(
541 "failed to fetch file %s to %s:\n%s\n%s"
542 % (in_path, out_path, stdout, stderr)
543 )
544
545 if actual_out_path != out_path:
546 os.rename(
547 to_bytes(actual_out_path, errors="strict"),
548 to_bytes(out_path, errors="strict"),
549 )
550
551 def close(self):
552 """Terminate the connection. Nothing to do for kubectl"""
553 super(Connection, self).close()
554 self._connected = False