How to create and use a Secret

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

Load config from default location


In [ ]:
config.load_kube_config()
client.configuration.assert_hostname = False

Create API endpoint instance and API resource instances


In [ ]:
api_instance = client.CoreV1Api()
sec  = client.V1Secret()

Fill required Secret fields


In [ ]:
sec.metadata = client.V1ObjectMeta(name="mysecret")
sec.type = "Opaque"
sec.data = {"username": "bXl1c2VybmFtZQ==", "password": "bXlwYXNzd29yZA=="}

Create Secret


In [ ]:
api_instance.create_namespaced_secret(namespace="default", body=sec)

Create test Pod API resource instances


In [ ]:
pod = client.V1Pod()
spec = client.V1PodSpec()
pod.metadata = client.V1ObjectMeta(name="mypod")
container = client.V1Container()
container.name = "mypod"
container.image = "redis"

Add volumeMount which would be used to hold secret


In [ ]:
volume_mounts = [client.V1VolumeMount()]
volume_mounts[0].mount_path = "/data/redis"
volume_mounts[0].name = "foo"
container.volume_mounts = volume_mounts

Create volume required by secret


In [ ]:
spec.volumes = [client.V1Volume(name="foo")]
spec.volumes[0].secret = client.V1SecretVolumeSource(secret_name="mysecret")

In [ ]:
spec.containers = [container]
pod.spec = spec

Create the Pod


In [ ]:
api_instance.create_namespaced_pod(namespace="default",body=pod)

View secret being used within the pod

Wait for alteast 10 seconds to ensure pod is running before executing this section.


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)

Delete Pod


In [ ]:
api_instance.delete_namespaced_pod(name="mypod", namespace="default", body=client.V1DeleteOptions())

Delete Secret


In [ ]:
api_instance.delete_namespaced_secret(name="mysecret", namespace="default", body=sec)

In [ ]: