Search code examples
postgresqlkubernetesyamlkubernetes-secrets

How to use dynamic connection string to POD in kubernetes secret file


I'm new in k8s. So I'll be appreciate for any suggestion. We have a multiple k8s namespaces in AKS.

I'm working under creating a cronjob that will run a script on multiple PostgreSQL pods in multiple namespaces. I created a secrets file to securely execute a cronjob to single target POD in default namespace. Here is my secrets file:

apiVersion: v1
kind: Secret
metadata:
    name: db-secrets
type: Opaque
data:
  "POSTGRES_PASSWORD": <encoded_password>
  "POSTGRES_USER": <encoded_username>
stringData:
  "DATABASE_HOST": postgres-db-postgresql-0.postgres-db-postgresql-headless.default.svc.cluster.local

Can anyone please suggest me in:

  1. How to use the dynamic string of target PostgreSQL POD DNS in my secrets file DATABASE_HOST section, so after deploying in k8s cluster, each cronjob will dynamically obtain target POD DNS, and connect to the POD in it's own namespace?
  2. Is it possible to use things like variables to dynamically obtain POD DNS?

I read somewhere that I can use HELM, however, I have not had time to work with Helm yet.


Solution

  • You can use Downward API in combination with interdependent environment variables to construct namespace-specific database hostname:

    apiVersion: v1
    kind: Pod
    metadata:
      name: test
    spec:
      containers:
        - name: test
          command:
            - sh
            - -c
            - sleep 1000
          image: busybox
          env:
          - name: POD_NAMESPACE
            valueFrom:
              fieldRef:
                fieldPath: metadata.namespace
          - name: DATABASE_HOST
            value: "postgres-db-postgresql-0.postgres-db-postgresql-headless.$(POD_NAMESPACE).svc.cluster.local"