每天5分钟玩转Kubernetes | 在Pod中使用Secret

书籍来源:cloudman《每天5分钟玩转Kubernetes》

一边学习一边整理老师的课程内容及试验笔记,并与大家分享,侵权即删,谢谢支持!

附上汇总贴:每天5分钟玩转Kubernetes | 汇总_COCOgsta的博客-CSDN博客


Pod可以通过Volume或者环境变量的方式使用Secret。

10.3.1 Volume方式

Pod的配置文件如下所示。

[root@k8s-master ~]# cat mypod.yml 
apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
  - name: mypod
    image: busybox
    args:
      - /bin/sh
      - -c
      - sleep 10; touch /tmp/healthy; sleep 30000
    volumeMounts:
    - name: foo
      mountPath: "/etc/foo"
      readOnly: true
  volumes:
  - name: foo
    secret:
      secretName: mysecret
[root@k8s-master ~]# 

① 定义volume foo,来源为secret mysecret。

② 将foo mount到容器路径/etc/foo,可指定读写权限为readOnly。

创建Pod并在容器中读取Secret,如图所示。

可以看到,Kubernetes会在指定的路径/etc/foo下为每条敏感数据创建一个文件,文件名就是数据条目的Key,这里是/etc/foo/username和/etc/foo/password,Value则以明文存放在文件中。

我们也可以自定义存放数据的文件名,比如将配置文件改为如下所示那样。

[root@k8s-master ~]# cat mypod.yml 
apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
  - name: mypod
    image: busybox
    args:
      - /bin/sh
      - -c
      - sleep 10; touch /tmp/healthy; sleep 30000
    volumeMounts:
    - name: foo
      mountPath: "/etc/foo"
      readOnly: true
  volumes:
  - name: foo
    secret:
      secretName: mysecret
      items:
      - key: username
        path: my-group/my-username
      - key: password
        path: my-group/my-password
[root@k8s-master ~]# 

这时数据将分别存放在
/etc/foo/my-group/my-username和/etc/foo/my-group/my-password中。

以Volume方式使用的Secret支持动态更新:Secret更新后,容器中的数据也会更新。

将password更新为abcdef,base64编码为YWJjZGVm,如图所示。

更新Secret,如图所示。

几秒钟后,新的password会同步到容器,如图所示。

10.3.2 环境变量方式

通过Volume使用Secret,容器必须从文件读取数据,稍显麻烦,Kubernetes还支持通过环境变量使用Secret。

Pod配置文件示例如下所示。

[root@k8s-master ~]# cat mypod.yml 
apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
  - name: mypod
    image: busybox
    args:
      - /bin/sh
      - -c
      - sleep 10; touch /tmp/healthy; sleep 30000
    env:
      - name: SECRET_USERNAME
        valueFrom:
          secretKeyRef:
            name: mysecret
            key: username
      - name: SECRET_PASSWORD
        valueFrom:
          secretKeyRef:
            name: mysecret
            key: password
[root@k8s-master ~]# 

创建Pod并读取Secret,如图所示。

通过环境变量SECRET_USERNAME和SECRET_PASSWORD成功读取到Secret的数据。

需要注意的是,环境变量读取Secret很方便,但无法支撑Secret动态更新。

猜你喜欢

转载自blog.csdn.net/guolianggsta/article/details/125168729