Last active
November 1, 2020 11:55
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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