Error in setup of Kubernetes Secret for C# application in pod

214 Views Asked by At

I'm trying to save the database credentials in Kubernetes secret. This will be picked through yaml file of kubernetes depoloyment.yaml.

This is how i created the secret in kubernetes master node:

kubectl create secret generic moiz-db-credentials \
  --from-literal=DB_HOST=77.68.54.25 \
  --from-literal=DB_USER=sa \
  --from-literal=DB_PASSWORD='123456'

This is how i called them in the Kubernetes Deployment file:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: munib-testing-db
  labels:
    app: munib-testing-db
spec:
  replicas: 1
  selector:
    matchLabels:
      app: munib-testing-db
  template:
    metadata:
      labels:
        app: munib-testing-db
    spec:
      containers:
      - name: munib-testing-db
        image: selteq2/munib-testing-db:27
        ports:
        - containerPort: 80
        env:
          - name: DB_USER
            valueFrom:
              secretKeyRef:
                name: moiz-db-credentials
                key: DB_USER
          - name: DB_PASSWORD
            valueFrom:
              secretKeyRef:
                name: moiz-db-credentials
                key: DB_PASSWORD
          - name: DB_HOST
            valueFrom:
              secretKeyRef:
                name: moiz-db-credentials
                key: DB_HOST
      imagePullSecrets:
      - name: regcred

Now i have a confusion that how should i call them in C# application. this is the default way:

"ConnectionStrings": {
    "DefaultConnection": "Server=77.68.54.25;Database=expertCustomer_live_1;User ID=sa;Password=123456;MultipleActiveResultSets=true;TrustServerCertificate=True",
  }

I have changed them to the environment variable that i created but still i'm getting this error in swagger:

enter image description here

Any suggestion what im doing doing wrong?

1

There are 1 best solutions below

0
Cosmin Ioniță On

The deployment configuration takes the value of the k8s secret oiz-db-credentials at the key DB_PASSWORD, and exposes this value as an environment variable (inside your pod) which has the key DB_PASSWORD.

So if you run kubectl exec -it <your_pod> /bin/sh, and then run env, you'll see your env var DB_PASSWORD with the key being your actual password value (extracted from the secret).

So to get the value of this environment variable in your C# app, you need to do something like:

var password = Environment.GetEnvironmentVariable("DB_PASSWORD");