创建Secret
使用Kubectl命令行创建Secret
假设有些Pod需要访问数据库,可以将账户、密码存储在username.txt和password.txt文件中,然后以文件的形式创建Secret供Pod使用。
首先创建账户信息文件:
echo -n "admin" > username.txt
echo -n "123456" > password.txt
然后以文件username.txt和password.txt创建Secret,创建方式和ConfigMap一致:
$ kubectl create secret generic db-user-pass --from-file=password.txt --from-file=username.txt
secret/db-user-pass created
查看Secret:
$ kubectl get secret db-user-pass -o yaml
apiVersion: v1
data:
password.txt: MTIzNDU2
username.txt: YWRtaW4=
kind: Secret
metadata:
creationTimestamp: "2023-11-29T08:17:54Z"
name: db-user-pass
namespace: default
resourceVersion: "163805"
uid: 889c6503-86d4-417c-8452-a809a3a44ff9
type: Opaque
默认情况下,get和describe命令都不会显示文件的内容,这是为了防止Secret中的内容被意外暴露。
通过YAML文件创建Secret
手动创建Secret时,每一项内容必须是base64编码的,所以要先对明文内容进行编码:
$ echo -n 'admin' | base64
YWRtaW4=
$ echo -n '123456' | base64
MTIzNDU2
然后创建一个YAML文件,格式如下:
$ kubectl get secret db-user-pass-yaml -o yaml
apiVersion: v1
data:
password: MTIzNDU2
username: YWRtaW4=
kind: Secret
metadata:
creationTimestamp: "2023-11-29T08:24:34Z"
name: db-user-pass-yaml
namespace: default
resourceVersion: "164645"
uid: ce6fa2fc-b05a-4b2f-9a4f-9879702d2b7f
type: Opaque
解码Secret
Secret被创建后,会以加密的方式存储于Kubernetes集群中,可以对其进行解码并查看内容:
首先以YAML的形式获取刚才创建的Secret:
$ kubectl get secret db-user-pass-yaml -o yaml
apiVersion: v1
data:
password: MTIzNDU2
username: YWRtaW4=
kind: Secret
metadata:
creationTimestamp: "2023-11-29T08:24:34Z"
name: db-user-pass-yaml
namespace: default
resourceVersion: "164645"
uid: ce6fa2fc-b05a-4b2f-9a4f-9879702d2b7f
type: Opaque
然后通过base64的--decode参数或-d参数解码即可:
$ echo "MTIzNDU2" | base64 --decode
123456
最后更新于
这有帮助吗?