-1

Iam trying to use Kubernetes secrets in my code in FastAPI webapp . I only have secret name and name space of the cluster. Is there any documentation on how to access the secret so I could set by db credentials accoring to values present in the secret rather than hardcoding it ?

Any help is aprreciated. Thanks!

Mat
  • 1,345
  • 9
  • 15
Sanket Wagh
  • 156
  • 1
  • 14
  • 1
    Mount the secrets as a volume in your pod spec. K8s will inject them as files when your pod launches. Read the secrets from those files. – rdas Oct 10 '22 at 14:02

1 Answers1

2

You can set the secrets as environment variable and then read them using os.environ["VAR_NAME"] or os.getenv("VAR_NAME")

Note: This solution has nothing to do with FastAPI and is purely K8s + Python. Therefore it might make more sense to rename the topic How to read values of secrets from K8 cluster using python? (or similar).

---
apiVersion: v1
kind: Secret
metadata:
  name: mysecret
type: Opaque
data:
  username: dXNlcm5hbWU=
  password: cGFzc3dvcmQ=
---
apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
  - name: mycontainer
    image: myimage
    env:
      - name: USERNAME
        valueFrom:
          secretKeyRef:
            name: mysecret
            key: username
      - name: PASSWORD
        valueFrom:
          secretKeyRef:
            name: mysecret
            key: password
  restartPolicy: Never
Mat
  • 1,345
  • 9
  • 15