k8s/python: How do I read a secret using the Kubernetes Python client?
I want to do the opposite of this question:
How to create secrets using Kubernetes Python client?
i.e.:
How do I read an existing secret from a kubernetes cluster via the kubernetes-python API?
The use case is: I want to authenticate to mongodb (running in my cluster) from a jupyter notebook (also running in my cluster) without, for obvious reasons, saving the mongodb auth password inside the jupyter notebook.
Thanks!
Answers
You can read an existing Secret from a Kubernetes cluster using the Kubernetes Python client (kubernetes
library). Here's how you can do it:
from kubernetes import client, config
# Load Kubernetes configuration from default location
config.load_kube_config()
# Create a Kubernetes API client
v1 = client.CoreV1Api()
# Specify the namespace and secret name
namespace = "your-namespace"
secret_name = "your-secret-name"
try:
# Get the Secret object
secret = v1.read_namespaced_secret(name=secret_name, namespace=namespace)
# Extract the data from the Secret
secret_data = secret.data
# Decode the base64-encoded data
decoded_data = {key: value.decode("utf-8") for key, value in secret_data.items()}
# Access the decoded data
mongodb_username = decoded_data.get("username")
mongodb_password = decoded_data.get("password")
# Now you can use the MongoDB username and password
# for authentication in your Jupyter notebook
print(f"MongoDB username: {mongodb_username}")
print(f"MongoDB password: {mongodb_password}")
except client.rest.ApiException as e:
print(f"Exception when calling CoreV1Api->read_namespaced_secret: {e}")
Make sure to replace "your-namespace"
and "your-secret-name"
with the appropriate namespace and secret name where your Secret is located.
In this code:
- We first load the Kubernetes configuration using
config.load_kube_config()
to load the configuration from the default location (usually~/.kube/config
). - We then create a
CoreV1Api
client to interact with the Kubernetes API. - We specify the namespace and secret name of the Secret we want to read.
- We use the
read_namespaced_secret
method to retrieve the Secret object from the specified namespace. - We decode the base64-encoded data from the Secret.
- Finally, we access the decoded data, such as username and password, and use it for authentication in your Jupyter notebook.
Make sure your Jupyter notebook has the necessary permissions to read Secrets from the Kubernetes cluster.