<p>The Python <code>kubernetes</code> module provides two methods for listing secrets:</p>
<ul>
<li><code>list_namespaced_secret</code></li>
<li><code>list_secret_for_all_namespaces</code></li>
</ul>
<p>I want to list the secrets for the namespace in which a container is running.</p>
<p>The <code>list_secret_all_for_namespaces</code> 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.</p>
<p>The <code>list_namespaced_secret</code> method requires an explicit namespace name. I can provide that as an argument to my Python code...</p>
<pre><code>apiVersion: v1
kind: Pod
metadata:
  name: example
  namespace: my-sandbox
spec:
  containers:
  - command:
    - /path/to/my-python-code.py
    arguments:
    - my-sandbox
</code></pre>
<p>...but that's clumsy, because it means the pod manifest needs to be
modified every time it's deployed to a new namespace.</p>
<p>Is there a way to acquire the current namespace name via the API?</p>

<p>If you could use <code>fieldRef</code> in the pod's manifest to set the env variable.</p>
<pre><code>apiVersion: v1
kind: Pod
metadata:
  name: dapi-envars-fieldref
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ &quot;sh&quot;, &quot;-c&quot;]
      args:
      - while true; do
          echo -en '\n';
          printenv
          sleep 10;
        done;
      env:
        - name: MY_POD_NAMESPACE # &lt;----this
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
  restartPolicy: Never
</code></pre>
<p>You can read the env variable and consume it with <code>list_namespaced_secret</code>.</p>
<pre><code>from kubernetes import client, config
import os

config.load_kube_config()

v1 = client.CoreV1Api()

k = v1.list_namespaced_secret(str(os.environ.get(&quot;MY_POD_NAMESPACE&quot;)))
for i in k.items:
    print(i.metadata.name)
</code></pre>
