How to use secrets as environment variables

KubernetesKubernetesBeginner
Practice Now

Introduction

In modern Kubernetes deployments, managing sensitive configuration data securely is crucial. This tutorial explores how to effectively use Kubernetes secrets as environment variables, providing a robust method for handling confidential information like API keys, database credentials, and other sensitive configuration details within containerized applications.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL kubernetes(("`Kubernetes`")) -.-> kubernetes/TroubleshootingandDebuggingCommandsGroup(["`Troubleshooting and Debugging Commands`"]) kubernetes(("`Kubernetes`")) -.-> kubernetes/BasicCommandsGroup(["`Basic Commands`"]) kubernetes(("`Kubernetes`")) -.-> kubernetes/AdvancedCommandsGroup(["`Advanced Commands`"]) kubernetes(("`Kubernetes`")) -.-> kubernetes/ConfigurationandVersioningGroup(["`Configuration and Versioning`"]) kubernetes/TroubleshootingandDebuggingCommandsGroup -.-> kubernetes/describe("`Describe`") kubernetes/TroubleshootingandDebuggingCommandsGroup -.-> kubernetes/exec("`Exec`") kubernetes/BasicCommandsGroup -.-> kubernetes/create("`Create`") kubernetes/BasicCommandsGroup -.-> kubernetes/set("`Set`") kubernetes/AdvancedCommandsGroup -.-> kubernetes/apply("`Apply`") kubernetes/ConfigurationandVersioningGroup -.-> kubernetes/config("`Config`") subgraph Lab Skills kubernetes/describe -.-> lab-419038{{"`How to use secrets as environment variables`"}} kubernetes/exec -.-> lab-419038{{"`How to use secrets as environment variables`"}} kubernetes/create -.-> lab-419038{{"`How to use secrets as environment variables`"}} kubernetes/set -.-> lab-419038{{"`How to use secrets as environment variables`"}} kubernetes/apply -.-> lab-419038{{"`How to use secrets as environment variables`"}} kubernetes/config -.-> lab-419038{{"`How to use secrets as environment variables`"}} end

Secrets in Kubernetes

What are Kubernetes Secrets?

Kubernetes Secrets are objects that help you manage sensitive information such as passwords, OAuth tokens, SSH keys, and other confidential data. They provide a way to separate sensitive configuration data from container images and pod specifications, enhancing security and flexibility in your applications.

Why Use Secrets?

Secrets solve several critical challenges in container orchestration:

  1. Security: Prevent sensitive data from being exposed in plain text
  2. Flexibility: Easily update credentials without modifying container images
  3. Separation of Concerns: Decouple configuration from application code

Types of Kubernetes Secrets

graph TD A[Kubernetes Secrets] --> B[Opaque Secrets] A --> C[Service Account Tokens] A --> D[Docker Registry Secrets] A --> E[TLS Secrets] A --> F[Bootstrap Token Secrets]
Secret Type Description Use Case
Opaque Default secret type Generic key-value pairs
Service Account Automatically created tokens Authenticating with Kubernetes API
Docker Registry Container image pull credentials Private container registries
TLS SSL/TLS certificates Secure network communications

Creating Secrets in Kubernetes

There are multiple ways to create secrets:

1. Literal Secret Creation

kubectl create secret generic db-credentials \
    --from-literal=username=admin \
    --from-literal=password=mysecretpassword

2. File-based Secret Creation

## Create a file with credentials
echo "database_password" > ./password.txt

## Create secret from file
kubectl create secret generic db-secret \
    --from-file=./password.txt

Best Practices

  1. Avoid storing secrets in source code
  2. Use environment-specific secrets
  3. Rotate secrets regularly
  4. Limit secret access using RBAC

LabEx Tip

When learning Kubernetes secrets, LabEx provides hands-on labs that help you practice secret management in a safe, controlled environment.

Security Considerations

  • Secrets are base64 encoded, not encrypted
  • Enable encryption at rest in your Kubernetes cluster
  • Use external secret management systems for enhanced security

By understanding and properly implementing Kubernetes Secrets, you can significantly improve the security and manageability of your containerized applications.

Secret Configuration

Secret Manifest Structure

Kubernetes secrets are typically defined using YAML manifests with specific configuration parameters:

apiVersion: v1
kind: Secret
metadata:
  name: example-secret
type: Opaque
data:
  username: YWRtaW4=
  password: cGFzc3dvcmQ=

Secret Types

graph TD A[Secret Types] --> B[Opaque] A --> C[kubernetes.io/service-account-token] A --> D[kubernetes.io/dockercfg] A --> E[kubernetes.io/dockerconfigjson] A --> F[kubernetes.io/basic-auth] A --> G[kubernetes.io/ssh-auth] A --> H[kubernetes.io/tls]

Encoding Secrets

Base64 Encoding

Kubernetes requires secret values to be base64 encoded:

## Encoding
echo -n 'admin' | base64
## Output: YWRtaW4=

## Decoding
echo 'YWRtaW4=' | base64 --decode
## Output: admin

Creating Secrets Manually

1. Generic Secrets

## Create secret from literal values
kubectl create secret generic db-credentials \
    --from-literal=username=dbuser \
    --from-literal=password=securepass

## Create secret from files
kubectl create secret generic app-config \
    --from-file=./config.json

2. Docker Registry Secrets

kubectl create secret docker-registry regcred \
    --docker-server=https://index.docker.io/v1/ \
    --docker-username=youruser \
    --docker-password=yourpassword \
    [email protected]

Secret Configuration Options

Configuration Description Example
type Defines secret type Opaque, kubernetes.io/tls
data Base64 encoded key-value pairs username: YWRtaW4=
stringData Allows plain text input username: admin

Advanced Secret Management

Immutable Secrets

apiVersion: v1
kind: Secret
metadata:
  name: immutable-secret
type: Opaque
immutable: true
data:
  key: BASE64_ENCODED_VALUE

LabEx Recommendation

When practicing secret configurations, LabEx provides interactive environments to safely experiment with Kubernetes secret management.

Security Best Practices

  1. Use stringData for easier secret creation
  2. Implement secret rotation
  3. Limit secret access using RBAC
  4. Consider external secret management solutions

Common Pitfalls

  • Accidentally committing secrets to version control
  • Using weak or predictable secret values
  • Insufficient access controls
  • Not encrypting secrets at rest

By mastering secret configuration, you can enhance the security and flexibility of your Kubernetes deployments.

Environment Variable Injection

Introduction to Environment Variable Injection

Environment variable injection allows you to pass secret values directly into container environments, providing a secure method of configuration management in Kubernetes.

Injection Methods

graph TD A[Secret Injection Methods] --> B[envFrom] A --> C[env] A --> D[Volume Mount]

Method 1: Using env Directive

Simple Environment Variable Injection

apiVersion: v1
kind: Pod
metadata:
  name: secret-env-pod
spec:
  containers:
  - name: myapp
    image: nginx
    env:
    - name: DB_USERNAME
      valueFrom:
        secretKeyRef:
          name: db-credentials
          key: username
    - name: DB_PASSWORD
      valueFrom:
        secretKeyRef:
          name: db-credentials
          key: password

Method 2: Using envFrom

Injecting All Secret Keys

apiVersion: v1
kind: Pod
metadata:
  name: full-secret-env-pod
spec:
  containers:
  - name: myapp
    image: nginx
    envFrom:
    - secretRef:
        name: db-credentials

Method 3: Volume Mount Injection

apiVersion: v1
kind: Pod
metadata:
  name: secret-volume-pod
spec:
  containers:
  - name: myapp
    image: nginx
    volumeMounts:
    - name: secret-volume
      mountPath: /etc/secrets
      readOnly: true
  volumes:
  - name: secret-volume
    secret:
      secretName: db-credentials

Injection Strategies

Strategy Pros Cons
env Selective key injection Manual configuration
envFrom Easy full secret injection Less granular control
Volume Mount File-based access Slightly more complex

Practical Example

Python Application Configuration

import os

## Accessing injected environment variables
db_username = os.environ.get('DB_USERNAME')
db_password = os.environ.get('DB_PASSWORD')

def connect_to_database():
    ## Use injected credentials securely
    connection = database.connect(
        username=db_username,
        password=db_password
    )

LabEx Tip

LabEx provides comprehensive labs to practice different secret injection techniques in real Kubernetes environments.

Best Practices

  1. Use least-privilege principle
  2. Rotate secrets regularly
  3. Avoid hardcoding sensitive information
  4. Use environment-specific configurations

Security Considerations

  • Limit secret access using RBAC
  • Use encrypted communication channels
  • Implement secret rotation mechanisms
  • Monitor and audit secret usage

Common Patterns

  • Development vs. Production secrets
  • Dynamically generated credentials
  • External secret management integration

By mastering environment variable injection, you can create more secure and flexible Kubernetes deployments while maintaining clean, manageable configurations.

Summary

By understanding how to use secrets as environment variables in Kubernetes, developers can significantly improve their application's security and configuration management. This approach ensures sensitive data remains protected, easily configurable, and seamlessly integrated into container environments, enabling more secure and flexible deployment strategies.

Other Kubernetes Tutorials you may like