Sobes.tech
Middle+

How do you inject secrets from Vault into an application? For example, to connect to a database at pod startup.

sobes.tech AI

Answer from AI

To inject secrets from HashiCorp Vault into an application running in Kubernetes, several approaches are often used:

  1. Vault Agent with Sidecar container

    • A sidecar container with Vault Agent is added to the pod, which authenticates with Vault and retrieves secrets.
    • Secrets are mounted into a shared volume (e.g., tmpfs) as files.
    • The main application reads secrets from these files at startup.
  2. Using CSI driver for Vault

    • Vault CSI Driver allows mounting secrets as a volume in the pod.
    • When the pod starts, secrets are automatically fetched and available in the filesystem.
  3. Initialization via init container

    • Init container fetches secrets from Vault and places them into a shared volume.
    • The main application reads them from the volume.
  4. Integration via environment variables

    • Vault Agent or init container can export secrets into environment variables.

Example with Vault Agent sidecar:

apiVersion: v1
kind: Pod
metadata:
  name: myapp
spec:
  serviceAccountName: vault-auth
  containers:
  - name: app
    image: myapp:latest
    volumeMounts:
    - name: vault-secrets
      mountPath: /etc/secrets
  - name: vault-agent
    image: vault:latest
    args: ["agent", "-config=/etc/vault/config.hcl"]
    volumeMounts:
    - name: vault-config
      mountPath: /etc/vault
    - name: vault-secrets
      mountPath: /etc/secrets
  volumes:
  - name: vault-config
    configMap:
      name: vault-agent-config
  - name: vault-secrets
    emptyDir: {}

As a result, the application reads secrets from /etc/secrets at startup and uses them to connect to the database.

It is important to ensure secure authentication (e.g., via Kubernetes Auth Method) and secret rotation.