主要用来保存用户名和密码,要求储存的为base64格式
1、生成base64类型的用户名密码
#用户名 [root@k8s-master01-etcd01 ~]# echo -n "root"|base64 cm9vdA== #密码 [root@k8s-master01-etcd01 ~]# echo -n "123456"|base64 MTIzNDU2
2、用上面的base64类型的用户名密码创建一个secret
[root@k8s-master01-etcd01 yaml]# kubectl apply -f mysecret.yaml
secret/mysqllogininfo created
[root@k8s-master01-etcd01 yaml]# cat mysecret.yaml
apiVersion: v1
kind: Secret
metadata:
name: mysqllogininfo
type: Opaque
data:
username: cm9vdA==
password: MTIzNDU2
[root@k8s-master01-etcd01 yaml]# kubectl get secret NAME TYPE DATA AGE default-token-6wrdx kubernetes.io/service-account-token 3 12d mysqllogininfo Opaque 2 25s registry-pull-secret kubernetes.io/dockerconfigjson 1 8d [root@k8s-master01-etcd01 yaml]# kubectl describe secret mysqllogininfo Name: mysqllogininfo Namespace: default Labels: <none> Annotations: Type: Opaque Data ==== password: 6 bytes username: 4 bytes
3、将secret导入到环境变量中
[root@k8s-master01-etcd01 yaml]# cat secret.pod.yaml apiVersion: apps/v1 kind: Deployment metadata: name: secret-busybox spec: replicas: 1 selector: matchLabels: app: secret-busybox template: metadata: labels: app: secret-busybox spec: containers: - name: secret-busybox image: busybox:1.28.4 command: ["/bin/sh","-c","env"] env: - name: MYSQL_USERNAME valueFrom: secretKeyRef: name: mysqllogininfo key: username - name: MYSQL_PASSWORD valueFrom: secretKeyRef: name: mysqllogininfo key: password
[root@k8s-master01-etcd01 yaml]# kubectl apply -f secret.pod.yaml deployment.apps/secret-busybox created [root@k8s-master01-etcd01 yaml]# kubectl get pod |grep busybox secret-busybox-5b48459787-7fns4 0/1 CrashLoopBackOff 2 38s [root@k8s-master01-etcd01 yaml]# kubectl logs secret-busybox-5b48459787-7fns4 |grep MYSQL MYSQL_USERNAME=root MYSQL_PASSWORD=123456
可以看到在环境变量中,容器会自动把base64类型的字符串进行解码
4、将secret挂载到volume中
[root@k8s-master01-etcd01 yaml]# cat secret-volume.yaml apiVersion: apps/v1 kind: Deployment metadata: name: secret-volume spec: replicas: 1 selector: matchLabels: app: secret-volume template: metadata: labels: app: secret-volume spec: volumes: - name: secrets secret: secretName: mysqllogininfo containers: - name: secret-volume image: busybox:1.28.4 command: ["/bin/sh","-c","sleep 3600"] volumeMounts: - name: secrets mountPath: "/etc/secrets" readOnly: true
[root@k8s-master01-etcd01 yaml]# kubectl apply -f secret-volume.yaml deployment.apps/secret-volume configured [root@k8s-master01-etcd01 yaml]# kubectl get pod|grep secret-volume secret-volume-7f8b49fb7b-tmhp6 1/1 Running 0 61s [root@k8s-master01-etcd01 yaml]# kubectl exec -it secret-volume-7f8b49fb7b-tmhp6 -- cat /etc/secrets/username root [root@k8s-master01-etcd01 yaml]# kubectl exec -it secret-volume-7f8b49fb7b-tmhp6 -- cat /etc/secrets/password 123456