k8s-secret使用案例
1. secret 配置文件示例
2. 使用案例
2.1 将用户名和密码进行编码
root@configmap-demo-pod:/# echo -n admin | base64
YWRtaW4=
root@configmap-demo-pod:/# echo -n '1f2d1e2e67df' | base64
MWYyZDFlMmU2N2Rm
2.2 将编码后的值放到secret
[root@k8s-master secret]# vim secret.yaml
[root@k8s-master secret]# cat secret.yaml
apiVersion: v1
kind: Secret
metadata:
name: db-user-pass
type: Opaque
data:
username: YWRtaW4=
password: MWYyZDFlMmU2N2Rm
2.3 启动secret配置文件
[root@k8s-master secret]# kubectl apply -f secret.yaml
secret/db-user-pass created
2.4 编写secret的pod文件
[root@k8s-master secret]# vim secret-pod.yaml
[root@k8s-master secret]# cat secret-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: secret-demo-pod
spec:
containers:
- name: demo
image: nginx
env:
- name: USER
valueFrom:
secretKeyRef:
name: db-user-pass
key: username
- name: PASS
valueFrom:
secretKeyRef:
name: db-user-pass
key: password
volumeMounts:
- name: config
mountPath: "/config"
readOnly: true
volumes:
- name: config
secret:
secretName: db-user-pass
items:
- key: username
path: my-username
2.5 启动配置文件
[root@k8s-master secret]# kubectl apply -f secret-pod.yaml
pod/secret-demo-pod created
2.6 查看pod是否启动
[root@k8s-master secret]# kubectl get pod
NAME READY STATUS RESTARTS AGE
configmap-demo-pod 1/1 Running 0 6h52m
secret-demo-pod 1/1 Running 0 86s
2.7 进入容器验证
[root@k8s-master secret]# kubectl exec -it secret-demo-pod -- /bin/bash
root@secret-demo-pod:/# env
KUBERNETES_SERVICE_PORT_HTTPS=443
KUBERNETES_SERVICE_PORT=443
HOSTNAME=secret-demo-pod
PWD=/
PKG_RELEASE=1~buster
HOME=/root
KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443
NJS_VERSION=0.5.0
TERM=xterm
USER=admin
PASS=1f2d1e2e67df
SHLVL=1
KUBERNETES_PORT_443_TCP_PROTO=tcp
KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1
KUBERNETES_SERVICE_HOST=10.96.0.1
KUBERNETES_PORT=tcp://10.96.0.1:443
KUBERNETES_PORT_443_TCP_PORT=443
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
NGINX_VERSION=1.19.6
_=/usr/bin/env
root@secret-demo-pod:/# echo $USER
admin
root@secret-demo-pod:/# echo $PASS
1f2d1e2e67df
root@secret-demo-pod:/# cat /config/my-username
admin
root@secret-demo-pod:/#