应用启动过程中可能需要一些敏感信息,比如访问数据库的用户名密码或者秘钥。将这些信息直接保存在容器镜像中显然不妥,Kubernetes 提供的解决方案是 Secret。
Secret 会以密文的方式存储数据,避免了直接在配置文件中保存敏感信息。Secret 会以 Volume 的形式被 mount 到 Pod,容器可通过文件的方式使用 Secret 中的敏感数据;此外,容器也可以环境变量的方式使用这些数据。
Secret 可通过命令行或 YAML 创建。比如希望 Secret 中包含如下信息:
-
用户名
admin
-
密码
123456
1.创建 Secret方式
有四种方法创建 Secret:
1.1 通过 --from-literal
:
kubectl create secret generic mysecret --from-literal=username=admin --from-literal=password=123456
每个 --from-literal
对应一个信息条目。
1.2 通过 --from-file
:
echo -n admin > ./username echo -n 123456 > ./password kubectl create secret generic mysecret --from-file=./username --from-file=./password
每个文件内容对应一个信息条目。
1.3通过 --from-env-file
:
cat << EOF > env.txt username=admin password=123456 EOF kubectl create secret generic mysecret --from-env-file=env.txt
文件 env.txt
中每行 Key=Value 对应一个信息条目。
1.4通过 YAML 配置文件:
文件中的敏感数据必须是通过 base64 编码后的结果。
执行 kubectl apply
创建 Secret:
2.查看secret
2.1通过 kubectl get secret
查看存在的 secret
显示有两个数据条目
2.2通过kubectl describe secret
查看条目的 Key
2.3通过kubectl edit secret mysecret 查看vlaue