Kubernetes

Kubernetes Secrets 密钥管理

Posted on 2020-10-12,3 min read

Secrets是一个包含敏感数据的对象,例如我们常用的密码,令牌或密钥等, 我们编写yaml如果直接明文这些信息则会将我们的敏感信息暴漏在我们的脚本中; 所以将其放置在Secret对象中可以更好地控制它的使用方式,并降低意外暴露的风险。

Pod可以引用我们事先创建好的Secrets键值对到环境变量, 通过获取环境变量的键值对动态更新我们Pod的环境配置, 从而实现动态配置更新.

  1. 创建一个secret

# kubectl create secret generic secret-demo --from-literal='password=countonme'

  1. 查看创建好的secret

# kubectl get secret secret-demo

NAME          TYPE      DATA      AGE
secret-demo   Opaque    1         13s

3.创建一个Pod并引用这个secret

# vi secret-env-pod.yaml

apiVersion: v1
kind: Pod
metadata:
  name: httpd-pod
spec:
  containers:
  - image: httpd
    name: httpd
    imagePullPolicy: Always
    env:
    - name: PASSWORD
      valueFrom:
        secretKeyRef:
          name: secret-demo
          key: password

# kubectl create -f secret-env-pod.yaml

4.查看secret

# kubectl describe secret

5.查看变量是否引入Pod

# kubectl exec -ti httpd-pod env

PATH=/usr/local/apache2/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=httpd-pod
TERM=xterm
PASSWORD=countonme
KUBERNETES_SERVICE_PORT_HTTPS=443
KUBERNETES_PORT=tcp://10.96.0.1:443
KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443
KUBERNETES_PORT_443_TCP_PROTO=tcp
KUBERNETES_PORT_443_TCP_PORT=443
KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1
KUBERNETES_SERVICE_HOST=10.96.0.1
KUBERNETES_SERVICE_PORT=443
HTTPD_PREFIX=/usr/local/apache2
NGHTTP2_VERSION=1.18.1-1
OPENSSL_VERSION=1.0.2l-1~bpo8+1
HTTPD_VERSION=2.4.29
HTTPD_SHA256=777753a5a25568a2a27428b2214980564bc1c38c1abf9ccc7630b639991f7f00
HTTPD_PATCHES=
APACHE_DIST_URLS=https://www.apache.org/dyn/closer.cgi?action=download&filename=
HOME=/root

可以看到Pod的环境变量里已经引入一组键值对PASSWORD=countonme

6.向Pod挂载目录写入secret文件.

# vi secret-vol-pod.yaml

apiVersion: v1
kind: Pod
metadata:
  name: httpd-pod-secret-vol
spec:
  containers:
  - image: httpd
    name: httpd
    imagePullPolicy: Always
    volumeMounts:
    - name: secret
      mountPath: "/mnt"
      readOnly: true
  volumes:
  - name: secret
    secret:
      secretName: secret-demo

# kubectl create -f secret-vol-pod.yaml

# kubectl exec -it httpd-pod-secret-vol cat /mnt/password

countonme

可以看到该Pod下面有一个文件名为password, 内容为countonme的文本文件.

下一篇: Kubernetes之Pod, Replicaset, Deployment, Label, Service→