Kubernetes:Secret
lastmod 2024-06-11created 2024-06-111 edits
Applying an env file
Convert a .env file into a Secret:
Verify the Secret was created
Applying a Secret to a Pod
Inject the Secret into the Pod as environment variables. You can expose the Secret as environment variables using the envFrom field in the Pod or Deployment definition file.
Writing the Pod YAML file
The example below shows how to inject my-secret into the Pod as environment variables:
apiVersion: v1
kind: Pod
metadata:
name: my-app
spec:
containers:
- name: my-container
image: my-image
envFrom:
- secretRef:
name: my-secret
Writing the Deployment YAML file
The example below shows how to use a Secret in a Deployment:
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 1
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-container
image: my-image
envFrom:
- secretRef:
name: my-secret
Mounting a Secret as a file
Instead of injecting the Secret as environment variables, you can also mount it as a file.
Writing the Pod YAML file
The example below shows how to mount a Secret as a volume:
apiVersion: v1
kind: Pod
metadata:
name: my-app
spec:
containers:
- name: my-container
image: my-image
volumeMounts:
- name: secret-volume
mountPath: /etc/secrets
readOnly: true
volumes:
- name: secret-volume
secret:
secretName: my-secret
Updating and reapplying a Secret
To update a Secret, edit the .env file and then recreate or update the Secret. You can also delete the old Secret and create a new one.
If you are using a Deployment, you must restart the rollout after updating the Secret for the changes to take effect.
Best practices
- Access control: Properly control access permissions to Secrets. Set up RBAC policies to restrict access to sensitive information.
- Environment separation: Manage Secrets separately for development, staging, and production environments. Use different Secrets per environment to improve security.
- Encryption: In Kubernetes, Secrets are stored encrypted in etcd by default. You can further improve security by managing Secrets with an external system such as Vault.
- Periodic audits: Regularly audit Secrets and check how they are managed. Remove expired information and Secrets that are no longer used.