secret-as-env-var

Learn how to securely inject Kubernetes secrets as environment variables using SecretKeyRef. This guide provides a practical example and explains the process step-by-step.

Kubernetes Secret as Env Var

This document demonstrates how to inject Kubernetes secrets as environment variables.

Creating a Kubernetes Secret

---
apiVersion: v1
kind: Secret
metadata:
  name: app-secret
type: Opaque
data:
  username: YWRtaW4= # base64 encoded value of "admin"
  password: YWRtaW4= # base64 encoded value of "admin"
---

Using the Secret in a Pod

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
  - name: container
    image: busybox:latest
    env:
    - name: AUTHENTICATION_ENABLED
      value: "true"
    - name: AUTHENTICATION_PASSWORD
      valueFrom:
        secretKeyRef:
          key: password
          name: app-secret

Explanation

The secretKeyRef field allows you to reference a specific key within a secret. This is a secure way to provide sensitive information to your applications without hardcoding it into your deployment manifests.

Further Reading

For more information on Kubernetes secrets, refer to the official documentation: Kubernetes Secrets Documentation