在容器组中使用保密字典
更新时间 2025-05-27 17:19:19
最近更新时间: 2025-05-27 17:19:19
本文介绍如何在容器组中使用保密字典。
如果需要在 Kubernetes 集群中使用密码、令牌、密钥、证书等敏感信息时,推荐使用保密字典。本文将介绍如何在控制台中创建保密字典(Secret),并使用保密字典配置Pod数据卷及环境变量。
前提条件
- 在容器组(Pod)中使用保密字典时,确保两者处于同一个集群和Namespace中。
- 已经连接到集群中的Master节点,具体操作请参阅通过kubectl连接。
创建保密字典
- 登录云容器引擎控制台。
- 在控制台的左侧导航栏中点击“集群” 。
- 在集群列表页面中,点击目标集群的名称进入集群详情页面。
- 点击左侧导航栏中的“配置管理” ,并选择保密字典 。
- 在保密字典页面中,单击左上角的“新增YAML” 。
- 在弹窗中自定义保密字典的YAML配置内容。
具体的YAML示例模板如下所示:
apiVersion: v1
kind: Secret
metadata:
name: secret-demo
namespace: default
type: Opaque
data:
username: dXNlcm5hbWU= # base64 编码的用户名
password: cGFzc3dvcmQ= # base64 编码的密码
使用保密字典配置Pod数据卷
- 创建example.yaml配置文件,具体示例内容如下:
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
namespace: default
labels:
app: nginx
spec:
replicas: 1
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
volumes:
- name: secret-volume
secret:
secretName: secret-demo
containers:
- name: nginx
image: registry-huadong1.crs-internal.ctyun.cn/open-source/nginx:1.26-alpine-slim
volumeMounts:
- name: secret-volume
mountPath: /mnt/secret
- 执行以下命令,配置保密字典。
kubectl apply -f example.yaml
在上述示例中,我们定义了一个Pod,并在其中添加了一个名为secret-volume的Volume,其类型为Secret,并将其挂载到名为nginx的容器中。在容器中,我们将Volume 挂载到了/mnt/secret路径下。此时,我们就可以在容器中使用 /mnt/secret/username和 /mnt/secret/password两个文件,来获取Secret 中的用户名和密码信息。
使用保密字典设置Pod的环境变量
- 通过命令行进行配置。
创建example.yaml配置文件,具体示例内容如下:
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: nginx
spec:
replicas: 1
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: registry-huadong1.crs-internal.ctyun.cn/open-source/nginx:1.26-alpine-slim
ports:
- containerPort: 80
env:
- name: username
valueFrom:
secretKeyRef:
name: secret-demo
key: username
- name: password
valueFrom:
secretKeyRef:
name: secret-demo
key: password
执行以下命令,配置保密字典。
kubectl apply -f example.yaml
在上述示例中,我们定义了一个Pod,并在其中添加了一个名为my-container 容器,接着为其定义了两个环境变量username和password,并使用valueFrom和secretKeyRef来引用Secret中的值。secretKeyRef的name属性用于指定Secret 的名称,key属性用于指定需要使用的Secret 中对应的键名。通过上述方式,在容器中就可以使用username和paasword环境变量,来获取Secret 中的用户名和密码信息。
- 通过控制台进行配置。
- 登录云容器引擎控制台。
- 在控制台的左侧导航栏中点击“集群” 。
- 在集群列表页面中,点击目标集群的名称进入集群详情页面。
- 点击左侧导航栏中的“工作负载” ,并选择“无状态” 。
- 在无状态页面中,单击左上角的“创建deployment” 。详细操作步骤请参阅Serverless 容器引擎使用快速入门 。
- 在“数据卷(选填)”中添加目标保密字典的数据卷。
- 在实例内容器中的环境变量区域单击“新增变量” ,类型选择“秘钥键值导入”,变量/变量引用选择在创建保密字典中新建的Secret,再分别选择Secret的Key以及填写它们对应的变量名。
本次示例配置如下所示: