The Python kubernetes
module provides two methods for listing secrets:
list_namespaced_secret
list_secret_for_all_namespaces
I want to list the secrets for the namespace in which a container is running.
The list_secret_all_for_namespaces
method isn't appropriate because it attempts to list secrets at the cluster scope, and I don't need or want that level of access.
The list_namespaced_secret
method requires an explicit namespace name. I can provide that as an argument to my Python code...
apiVersion: v1
kind: Pod
metadata:
name: example
namespace: my-sandbox
spec:
containers:
- command:
- /path/to/my-python-code.py
arguments:
- my-sandbox
...but that's clumsy, because it means the pod manifest needs to be modified every time it's deployed to a new namespace.
Is there a way to acquire the current namespace name via the API?
I appreciate the answers pointing at the dowward api, but I was hoping for something that would be independent from the pod manifest.
It looks like the namespace is exposed via the ServiceAccount
information injected into the container, in /run/secrets/kubernetes.io/serviceaccount/namespace
. This is available whether or not your pod has an explicit ServiceAccountName
.
If you could use fieldRef
in the pod's manifest to set the env variable.
apiVersion: v1
kind: Pod
metadata:
name: dapi-envars-fieldref
spec:
containers:
- name: test-container
image: k8s.gcr.io/busybox
command: [ "sh", "-c"]
args:
- while true; do
echo -en '\n';
printenv
sleep 10;
done;
env:
- name: MY_POD_NAMESPACE # <----this
valueFrom:
fieldRef:
fieldPath: metadata.namespace
restartPolicy: Never
You can read the env variable and consume it with list_namespaced_secret
.
from kubernetes import client, config
import os
config.load_kube_config()
v1 = client.CoreV1Api()
k = v1.list_namespaced_secret(str(os.environ.get("MY_POD_NAMESPACE")))
for i in k.items:
print(i.metadata.name)
You can set an environment variable in this manifest that will be auto-populated when your Pod is deployed. See this stackoverflow answer for how to do that:
https://stackoverflow.com/a/57809472/16894714
Then you can simply access the environment variable from within your python script and call list_namespaced_secret
.