Skip to content

Instantly share code, notes, and snippets.

@ahmetkotan
Last active November 1, 2020 11:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ahmetkotan/b592bf9919cfac7daa2e2e6c2e95772d to your computer and use it in GitHub Desktop.
Save ahmetkotan/b592bf9919cfac7daa2e2e6c2e95772d to your computer and use it in GitHub Desktop.
Run command on container from another container on same pod with kubernetes api
from kubernetes import client
from kubernetes.stream import stream
import os
import sys
if len(sys.argv) < 4:
print(f"Usage: {sys.argv[0]} <pod_name> <container_name> <command>")
sys.exit(1);
pod_name = sys.argv[1]
container = sys.argv[2]
k8s_secret_directory = "/var/run/secrets/kubernetes.io/serviceaccount"
with open(os.path.join(k8s_secret_directory, "token")) as f:
k8s_token = f.read()
k8s_ca_cert_file = os.path.join(k8s_secret_directory, "ca.crt")
with open(os.path.join(k8s_secret_directory, "namespace")) as f:
k8s_namespace = f.read()
k8s_host = os.getenv("KUBERNETES_SERVICE_HOST")
k8s_host_port = os.getenv("KUBERNETES_SERVICE_PORT")
configuration = client.configuration.Configuration()
configuration.api_key["authorization"] = k8s_token # K8s Authentication Token
configuration.api_key_prefix["authorization"] = "Bearer" # K8s Authentication Header Prefix
configuration.ssl_ca_cert = k8s_ca_cert_file # K8s SSL Certificate File
configuration.host = f"https://{k8s_host}:{k8s_host_port}" # Kubernetes API URL
k8s_client = client.CoreV1Api(client.ApiClient(configuration))
std = {"stderr": True, "stdin": False, "stdout": True, "tty": False}
command = sys.argv[3:]
response = stream(k8s_client.connect_get_namespaced_pod_exec, name=pod_name, container=container, namespace=k8s_namespace, command=command, **std)
print(response.strip())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment