Secret与ConfigMap在Pod中引用

Pod中使用配置好的Secret与ConfigMap

如前文所述,已经配置好了Cluster所需要的Secret与ConfigMap,接下来是需要考虑如何在Pod中使用配置好的信息。

在Pod中有两种引用方法

  • 以Env变量来使用。此方法只能一次性加载,不能够动态更新。即Secret或者ConfigMap的值发生改变时,不能够在Pod实现动态更新,需要重新加载Pod来引用新的值
apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
    - name: busybox
      image: busybox
      args:
        - bin/sh
        - -c
        - sleep 10 ; echo "${USERNAME} and ${PASSWORD}, login with ${LOGIN} and ${REQUIRED}" ; sleep 60
      env:
        - name: USERNAME
          valueFrom:
            secretKeyRef:
              key: username
              name: my-secret
        - name: PASSWORD
          valueFrom:
            secretKeyRef:
              key: password
              name: my-secret
        - name: LOGIN
          valueFrom:
            configMapKeyRef:
              key: login
              name: my-config
        - name: REQUIRED
          valueFrom:
            configMapKeyRef:
              key: required
              name: my-config
  • 以Volume形式来是引用,可以实现动态同步更新
apiVersion: v1
kind: Pod
metadata:
  name: my-pod-volume
spec:
  containers:
    - name: busybox
      image: busybox
      args:
        - bin/sh
        - -c
        - sleep 60
      volumeMounts:
        - mountPath: /etc/secret
          name: secret-config
        - mountPath: /etc/config-map
          name: configmap-config
  volumes:
    - name: secret-config
      secret:
        # value of username in /etc/secret/username
        # value of password in /etc/secret/username
        # key in secret as file name
        secretName: my-secret
    - name: configmap-config
      configMap:
        name: my-config
        items:
          - key: config
            # relative path to mount path, config file would be found in /etc/configMap/config in container
            path: config
          - key: login
            path: login
          - key: required
            path: required

可以通过运行命令来查询具体Secret和ConfigMap在container中存储位置

kubectl exec -it pod my-pod-volume /bin/sh

kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
/ # cat /etc/secret/username 
admin/ # 
/ # cat /etc/secret/password 
1234/ # 
/ # cat /etc/config-map/config 
username: admin
password: "1234"
/ # cat /etc/config-map/login 
/ # cat /etc/config-map/login 
username/ # 
/ # cat /etc/config-map/required 
password/ # 

 

上一篇:buu-[极客大挑战 2019]Secret File


下一篇:k8s学习记录,配置管理ConfigMap&Secret(十七)