作为文件

和ConfigMap一样,可以在Pod的volumes中使用Secret:

  1. 首先创建一个Secret或者使用已有的Secret

    • 多个Pod可以引用同一个Secret

    • 一个Pod也可以引用多个Secret。

  2. spec.volumes下增加一个volume

    • spec.volumes.secret.secretName必须和Secret对象的名字相同,并且在同一个Namespace中

  3. spec.containers.volumeMounts加到需要用到该Secret的容器中,并且设置spec.containers.volumeMounts.readOnly = true

  4. 使用spec.containers.volumeMounts.mountPath指定Secret挂载目录。

例如,将名字为db-user-pass的Secret挂载到Pod中的/etc/foo

pod-secret-mount.yaml
apiVersion: v1
kind: Pod
metadata:
  name: pod-secret-mount
spec:
  containers:
  - name: pod-secret-mount
    image: nginx:1.25.3
    volumeMounts:
      - name: secret-mount
        mountPath: /etc/foo
        readOnly: true
    resources:
      limits:
        memory: "128Mi"
        cpu: "500m"
    ports:
      - containerPort: 80
  volumes: 
  - name: secret-mount
    secret:
      secretName: db-user-pass
$ kubectl create -f pod-secret-mount.yaml 
pod/pod-secret-mount created

$ kubectl exec -it pod-secret-mount -- ls -l /etc/foo
total 0
lrwxrwxrwx 1 root root 19 Nov 29 09:02 password.txt -> ..data/password.txt
lrwxrwxrwx 1 root root 19 Nov 29 09:02 username.txt -> ..data/username.txt

$ kubectl exec -it pod-secret-mount -- cat /etc/foo/password.txt
123456

注意:

  • 由于没有指定挂载文件的名称,因此会用Secret数据中的Key名作为文件。

  • Secret放入容器后,已经进行了解码,因此在容器内部是能够查看到明文的

自定义文件名挂载

挂载Secret时,可以使用spec.volumes.secret.items字段修改每个key的目标路径,即控制Secret Key在容器中的映射路径,和ConfigMap的用法一致:

最后更新于