Kubernetes YAML Secrets and ConfigMaps to ENV
Convert Kubernetes Secret and ConfigMap YAML manifests into .env file format. Learn how to handle base64-encoded values and manage configuration extraction.
Detailed Explanation
Kubernetes stores configuration in ConfigMaps and sensitive data in Secrets, both defined as YAML manifests. Converting these to .env format is common when developing locally or migrating between deployment platforms.
Kubernetes ConfigMap:
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
DATABASE_HOST: db.production.svc.cluster.local
DATABASE_PORT: "5432"
DATABASE_NAME: myapp
LOG_LEVEL: info
CACHE_TTL: "3600"
FEATURE_NEW_UI: "true"
Kubernetes Secret (values are base64-encoded):
apiVersion: v1
kind: Secret
metadata:
name: app-secrets
type: Opaque
data:
DATABASE_PASSWORD: cDRzc3cwcmQ=
JWT_SECRET: c3VwZXItc2VjcmV0LWtleS0xMjM=
API_KEY: YWJjZGVmZzEyMzQ1Ng==
Combined .env output:
# From ConfigMap: app-config
DATABASE_HOST=db.production.svc.cluster.local
DATABASE_PORT=5432
DATABASE_NAME=myapp
LOG_LEVEL=info
CACHE_TTL=3600
FEATURE_NEW_UI=true
# From Secret: app-secrets
DATABASE_PASSWORD=p4ssw0rd
JWT_SECRET=super-secret-key-123
API_KEY=abcdefg123456
Key conversion steps:
- ConfigMap
datasection contains plain-text key-value pairs. Conversion is direct -- just extract thedatamap and format asKEY=VALUE. - Secret
datasection contains base64-encoded values. Each value must be decoded (echo "cDRzc3cwcmQ=" | base64 -d) before writing to the .env file. - Secret
stringDatasection (if present) contains plain-text values that Kubernetes automatically base64-encodes. These can be converted directly without decoding.
Kubernetes-specific considerations:
- Namespaced data. ConfigMaps and Secrets are namespace-scoped. When extracting to .env, you lose the namespace context.
- Multiple ConfigMaps. A pod may mount multiple ConfigMaps. When combining them into one .env file, watch for key collisions.
- Binary data. Secrets can contain binary data (like TLS certificates). These need special handling -- typically Base64 encoding the entire value or writing to a separate file.
kubectl shortcut for extraction:
kubectl get configmap app-config -o jsonpath='{.data}' | \
jq -r 'to_entries[] | "\(.key)=\(.value)"'
This pipeline extracts the ConfigMap data and formats it as ENV directly from the cluster.
Use Case
Setting up a local development environment that mirrors the production Kubernetes cluster by extracting ConfigMap and Secret values into a .env file used by docker-compose or a dotenv-based development server.