k8s管理机密信息

Secret介绍:

应用启动过程中可能需要一些敏感信息,比如访问数据库的用户名密码或者秘钥。将这些信息直接保存在容器镜像中显然不妥,Kubernetes 提供的解决方案是 Secret。

Secret 会以密文的方式存储数据,避免了直接在配置文件中保存敏感信息。Secret 会以 Volume 的形式被 mount 到 Pod,容器可通过文件的方式使用 Secret 中的敏感数据;此外,容器也可以环境变量的方式使用这些数据。

Secret 可通过命令行或 YAML 创建。比如希望 Secret 中包含如下信息:

  1. 用户名 admin

  2. 密码 123456

创建 Secret

有四种方法创建 Secret:

1. 通过 --from-literal

#kubectl create secret generic mysecret --from-literal=username=admin --from-literal=password=123

 

2. 通过 --from-file

#echo -n admin > ./username

#echo -n 123456 > ./password

#kubectl create secret generic mysecret1 --from-file=./username --from-file=./password

3. 通过 --from-env-file

#cat << EOF > env.txt

username=admin

password=123456

EOF

#kubectl create secret generic mysecret2 --from-env-file=env.txt

4. 通过 YAML 配置文件:

文件中的敏感数据必须是通过 base64 编码后的结果。

执行 kubectl apply 创建 Secret:

如果还想查看 Value,可以用 kubectl edit secret mysecret

然后通过 base64 将 Value 反编码:

volume 方式使用 Secret

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

(1)Pod 的配置文件如下所示:

#vim mypod.yml

kind: Pod
apiVersion: v1
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

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

① 定义 volume foo,来源为 secret mysecret

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

(2)我们也可以自定义存放数据的文件名,比如将配置文件改为:

kind: Pod
apiVersion: v1
metadata:
  name: mypod2
spec:
  containers:
    - name: mypod2
      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: passwork
          path: my-group/my-password

 

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

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

将 password 更新为 abcdef,base64 编码为 YWJjZGVm

更新 Secret。

几秒钟或,新的 password 会同步到容器。

环境变量方式使用 Secret

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

Pod 配置文件示例如下:

创建 Pod 并读取 Secret。

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

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

Secret 可以为 Pod 提供密码、Token、私钥等敏感数据;

删除

#kubectl delete secret mysecret
或
#kubectl delete -f mysecret.yml

猜你喜欢

转载自blog.csdn.net/PpikachuP/article/details/89708787
k8s