What is a Secret?
A Secret is a Kubernetes object which is used to store and manage sensitive data in Kubernetes such as:
Passwords
API Keys
Database Credentials
Tokens
Certificates
Why Use Secrets?
Not Recommended:-
env:
- name: DB_PASSWORD
value: "admin123"
Anyone can see the password in the YAML file.
Recommended:- Store the password in a Kubernetes Secret and use it in the Deployment.
Step 1: Create a Secret
kubectl create secret generic mysql-secret --from-literal=username=admin --from-literal=password=admin123
kubectl get secrets
Step 2: Use Secret in Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-secret-demo
spec:
replicas: 2
selector:
matchLabels:
app: nginx-secret-demo
template:
metadata:
labels:
app: nginx-secret-demo
spec:
containers:
- name: nginx
image: nginx:latest
env:
- name: DB_USER
valueFrom:
secretKeyRef:
name: mysql-secret
key: username
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: mysql-secret
key: password
kubectl apply -f deployment.yaml
Step 3: Verify Inside the Container
kubectl get pods
kubectl exec -it <pod-name> -- bash
printenv DB_USER
Real-Life Example
Suppose your application connects to MySQL:
Database Host = mysql-service
Database User = admin
Database Password = admin123
Store the password in a Secret instead of hardcoding it in the Deployment YAML, This keeps sensitive data separate from application configuration.
No comments:
Post a Comment
testing