Secret 的意义
secret 解决了密码、token、密钥等敏感数据的配置问题,而不需要把这些敏感数据暴露到镜像或者 Pod Spec 中。Secret 可以以 Volume 或者环境变量的方式使用。
Secret 有三种类型:
- ServiceAccount:用来访问 Kubernetes API,由 Kubernetes 自动创建,并且会自动挂载到 Pod 的 /run/secrets/kubernetes.io/serviceaccount 目录中
- Opaque: base64 编码格式的 Secret, 用来存储密码、密钥等
- kubernetes.io/dockerconfigjson: 来存储私有 docker registry 的认证信息
ServiceAccount
Service Account 用来访问 Kubernetes API, 由 Kubernetes 自动创建,并且会自动挂载到 Pod 的 /run/secrets/kubernetes.io/serviceaccount 目录中。
kubectl get pod -n kube-system
kubectl exec kube-proxy-gh9k7 -n kube-system -it -- /bin/sh
cd /run/secrets/kubernetes.io/serviceaccount
ls
ca.crt namespace token
Opaque Secret
创建说明
Opaque 类型的数据是一个 map 类型,要求 value 是 base64 编码格式:
echo -n "admin"|base64
YWRtaW4=
echo -n "1f2d1e2e67df" | base64
MWYyZDFlMmU2N2Rm
mkdir Secret && cd Secret/
# 创建 Secret
vi mysecret.yaml
apiVersion: v1
kind: Secret
metadata:
name: mysecret
type: Opaque
data:
password: MWYyZDFlMmU2N2Rm
username: YWRtaW4=
kubectl apply -f mysecret.yaml
# 在 pod 中使用 Secret
vi pod1.yaml
apiVersion: v1
kind: Pod
metadata:
labels:
name: seret-test
name: seret-test
spec:
volumes:
- name: secrets
secret:
secretName: mysecret
containers:
- image: wangyanglinux/myapp:v1
name: db
volumeMounts:
- name: secrets
mountPath: "/etc/secrets"
readOnly: true
kubectl apply -f pod1.yaml
kubectl exec -it seret-test -- /bin/sh
cd /etc/secrets
cat password
1f2d1e2e67df
cat username
admin
kubectl delete -f pod1.yaml
将 Secret 导出到环境变量中
vi pod2.yaml
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: pod-deployment
spec:
replicas: 2
template:
metadata:
labels:
app: pod-deployment
spec:
containers:
- name: pod-1
image: wangyanglinux/myapp:v1
ports:
- containerPort: 80
env:
- name: TEST_USER
valueFrom:
secretKeyRef:
name: mysecret
key: username
- name: TEST_PASSWORD
valueFrom:
secretKeyRef:
name: mysecret
key: password
kubectl get pod
kubectl exec -it pod-deployment-747f78bc67-722f6 -- /bin/sh
/ # echo $TEST_USER
admin
/ # echo $TEST_PASSWORD
1f2d1e2e67df
kubectl delete -f pod2.yaml
kubernetes.io/dockerconfigjson
使用 kuberctl 创建 docker registry 认证的 secret
kubectl create secret docker-registry myregistrykey --docker-server=hub.atguigu.com --docker-username=admin --docker-password=Harbor12345 --docker-email=wangyanglinux@163.com
vi pod3.yaml
apiVersion: v1
kind: Pod
metadata:
name: foo
spec:
containers:
- name: foo
image: wangyanglinux/myapp:v1
imagePullSecrets:
- name: myregistrykey
kubectl apply -f pod3.yaml
kubectl delete -f pod3.yaml
kubectl delete -f mysecret.yaml
kubectl delete secret myregistrykey