k8s Secret
Secret 会以密文的形式存储数据,避免了直接在配置文件中保存敏感信息。Secret 会以Volume 的形式被mount到Pod,容器可通过文件的方式使用Secret中的敏感数据;此外容器也可以通过环境变量的方式使用这些数据。
Secret 可通过命令行或YAML 创建
1.创建Secret
(1) 通过 --from-literal
kubectl creata secret generic mysecret --from-literal=username=admin --from-literal=password=123456
(2) 通过 --from-file
echo -n admin > ./username echo -n 123456 > ./password kubectl create secret generic mysecret --from-file=./username --from-file=./password
(3) 通过 --from-env-file
cat << EOF > env.txt username=admin password=123456 EOF kubectl create secret generic mysecret --from-env-file=env.txt
(4) 通过YAML配置文件
文件中的敏感数据必须是通过base64编码后的结果。
echo -n admin | base64 echo -n 123456 | base64
myscrete.yaml
apiVersion:v1 kind: Secret metadat: name: mysecret data: username: YWRtaW4= password: MTIzNDU2
2.查看 Secret
kubectl get secret mysecret


通过 kubectl describe secret 查看 key

通过 kubectl edit secret mysecret 查看 Value

通过base 64将 Value 反编码

3.在Pod中使用Secret
Volume 方式
创建Pod 并在容器中读取secret
apiVersion: v1 kind: Pod metadata: name: mypod spec: containers: - name: mypod image: centos args: - /bin/sh - -c - sleep 10; touch /tmp/healthy;sleep 30000 volumeMounts: - name: foo mountPath: "/etc/foo" readOnly: true volumes: - name: foo secret: secretName: mysecret
kubectl apply -f mysecret.yml

Kubernetes 会在指定的路径下/etc/foo 下为每条敏感数据创建一个文件,文件名就是数据条目的key,这里是
/etc/foo/username 和 /etc/foo/password, Value 则是以明文存放在文件中。
自定义 存放数据的文件名
apiVersion: v1 kind: Pod metadata: name: mypod spec: containers: - name: mypod image: centos args: - /bin/sh - -c - sleep 10; touch /tmp/healthy;sleep 30000 volumeMounts: - name: foo mountPath: "/etc/foo" readOnly: true volumes: - name: foo secret: secretName: mysecret items: - key: username path: my-group/my-username - key: password path: my-group/my-password
这时数据将分别存放在 /etc/foo/my-group/my-username 和 /etc/foo/my-group/my-password 中
以Volume方式使用的Secret 支持动态更新: Secret 更新后,容器的数据也会更新。
更新 Secret
将password 更新为abcdef ,base64 编码为YWJjZGVm

kubectl apply -f mysecret.yml
几秒钟后,新的password 会同步到容器

环境变量的方式
apiVersion: v1 kind: Pod metadata: name: mypod spec: containers: - name: mypod image: centos args: - /bin/sh - -c - sleep 10; touch /tmp/healthy; sleep 30000 env: - name: SECRET_USERNAME valueFrom: secretKeyRef: name: mysecret key: username - name: SECRET_PASSWORD valueFrom: secretKeyRef: name: mysecret key: password
kubectl apply -f mypod-env.yml

通过环境变量的方式 SECRET_USERNAME 和 SECRET_PASSWORD 成功读取到Secreet 的数据
注意: 环境变量读取Secret 很方便,但是无法支撑Secret 动态更新

浙公网安备 33010602011771号