Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 310 of 8025. Advanced Kubernetes ConfigurationFree lesson

Injecting Secrets into Pods as Environment Variables

Configure Pod manifests to map Secret keys directly into container environment variables for immediate application access at runtime.

Injecting Secrets into Pods as Environment Variables

In this lesson, you will learn how to securely map sensitive data stored in Kubernetes Secrets directly into your container's environment variables.

When building applications, you often need sensitive information like API keys, database credentials, or tokens. While we previously explored using ConfigMaps for non-sensitive data, Kubernetes Secrets are designed specifically for this private information. Injecting them as environment variables allows your application code to read these values just like any standard system configuration, making the transition from local development to a cluster seamless.

How it Works

Instead of hardcoding credentials in your container image—which is a major security risk—you define a Secret object in the cluster. You then reference that secret in your Pod manifest under the env section. Kubernetes handles the decryption and injection automatically when the container starts.

Here is a practical example of how to reference a secret key in a Pod:

apiVersion: v1
kind: Pod
metadata:
  name: secure-app
spec:
  containers:
  - name: web-server
    image: nginx
    env:
      - name: DB_PASSWORD
        valueFrom:
          secretKeyRef:
            name: database-secret
            key: password

In this manifest, we instruct Kubernetes to look for a secret named database-secret. It retrieves the value associated with the password key and injects it into the container as an environment variable named DB_PASSWORD.

By using valueFrom and secretKeyRef, you ensure that the sensitive value is not stored in your manifest file itself, but is instead pulled from the cluster's internal storage at runtime. This keeps your Pod configuration clean and your sensitive credentials safely managed by Kubernetes.

Remember, once the Pod is running, any process inside that container can access these variables by reading the environment. Ensure that your application is configured to handle these variables securely and that you have appropriate Role-Based Access Control (RBAC) in place to restrict who can view or modify the underlying Secret objects.

Key Takeaway: Injecting Secrets as environment variables via secretKeyRef allows your applications to access sensitive configuration at runtime without exposing those credentials in your code or source control.