A Secret is an object that contains a small amount of sensitive data such as a password, a token, or a key. In this notebook, we would learn how to create a Secret and how to use Secrets as files from a Pod as seen in https://kubernetes.io/docs/concepts/configuration/secret/#using-secrets
In [ ]:
from kubernetes import client, config
In [ ]:
config.load_kube_config()
client.configuration.assert_hostname = False
In [ ]:
api_instance = client.CoreV1Api()
sec = client.V1Secret()
In [ ]:
sec.metadata = client.V1ObjectMeta(name="mysecret")
sec.type = "Opaque"
sec.data = {"username": "bXl1c2VybmFtZQ==", "password": "bXlwYXNzd29yZA=="}
In [ ]:
api_instance.create_namespaced_secret(namespace="default", body=sec)
In [ ]:
pod = client.V1Pod()
spec = client.V1PodSpec()
pod.metadata = client.V1ObjectMeta(name="mypod")
container = client.V1Container()
container.name = "mypod"
container.image = "redis"
In [ ]:
volume_mounts = [client.V1VolumeMount()]
volume_mounts[0].mount_path = "/data/redis"
volume_mounts[0].name = "foo"
container.volume_mounts = volume_mounts
In [ ]:
spec.volumes = [client.V1Volume(name="foo")]
spec.volumes[0].secret = client.V1SecretVolumeSource(secret_name="mysecret")
In [ ]:
spec.containers = [container]
pod.spec = spec
In [ ]:
api_instance.create_namespaced_pod(namespace="default",body=pod)
In [ ]:
user = api_instance.connect_get_namespaced_pod_exec(name="mypod", namespace="default", command=[ "/bin/sh", "-c", "cat /data/redis/username" ], stderr=True, stdin=False, stdout=True, tty=False)
print(user)
passwd = api_instance.connect_get_namespaced_pod_exec(name="mypod", namespace="default", command=[ "/bin/sh", "-c", "cat /data/redis/password" ], stderr=True, stdin=False, stdout=True, tty=False)
print(passwd)
In [ ]:
api_instance.delete_namespaced_pod(name="mypod", namespace="default", body=client.V1DeleteOptions())
In [ ]:
api_instance.delete_namespaced_secret(name="mysecret", namespace="default", body=sec)
In [ ]: