how to connect kubernetes pods (terminal) interactively through api or other?

Viewed 320

How to connect the Kubernetes pods (terminal) interactively through API or other?

We can expose the pods using services but we need how to connect the pods interactively using API or others.

3 Answers

You can use exec --stdin as described here.

Something like this:

kubectl exec --stdin --tty [POD ID] -- /bin/bash

If you want to achieve it through API calls, the easiest way is to use one of the api client libraries e.g. kubernetes python client.

In python client it can be done using api_instance.connect_get_namespaced_pod_exec method. It's documentation gives you even a ready working example:

from __future__ import print_function
import time
import kubernetes.client
from kubernetes.client.rest import ApiException
from pprint import pprint
configuration = kubernetes.client.Configuration()
# Configure API key authorization: BearerToken
configuration.api_key['authorization'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['authorization'] = 'Bearer'

# Defining host is optional and default to http://localhost
configuration.host = "http://localhost"

# Enter a context with an instance of the API kubernetes.client
with kubernetes.client.ApiClient(configuration) as api_client:
    # Create an instance of the API class
    api_instance = kubernetes.client.CoreV1Api(api_client)
    name = 'name_example' # str | name of the PodExecOptions
namespace = 'namespace_example' # str | object name and auth scope, such as for teams and projects
command = 'command_example' # str | Command is the remote command to execute. argv array. Not executed within a shell. (optional)
container = 'container_example' # str | Container in which to execute the command. Defaults to only container if there is only one container in the pod. (optional)
stderr = True # bool | Redirect the standard error stream of the pod for this call. Defaults to true. (optional)
stdin = True # bool | Redirect the standard input stream of the pod for this call. Defaults to false. (optional)
stdout = True # bool | Redirect the standard output stream of the pod for this call. Defaults to true. (optional)
tty = True # bool | TTY if true indicates that a tty will be allocated for the exec call. Defaults to false. (optional)

    try:
        api_response = api_instance.connect_get_namespaced_pod_exec(name, namespace, command=command, container=container, stderr=stderr, stdin=stdin, stdout=stdout, tty=tty)
        pprint(api_response)
    except ApiException as e:
        print("Exception when calling CoreV1Api->connect_get_namespaced_pod_exec: %s\n" % e)

As a command you need to use bash, /bin/bash, sh or /bin/sh (it depends on what shell is available in your pod).

Compare it also with this answer.

Related