机密信息
Secret
Secret 会以密文的方式存储数据,避免了直接在配置文件中保存敏感信息。Secret 会以 Volume 的形式被 mount 到 Pod,容器可通过文件的方式使用 Secret 中的敏感数据;此外,容器也可以环境变量的方式使用这些数据。
创建Secret
- 1.通过 
--from-literal 
kubectl create secret generic mysecret --from-literal=username=admin --from-literal=passsword=123456
- 2.通过 
--from-file 
echo -n admin > ./username.txt
echo -n password > ./password.txt
kubectl create secret generic mysecret2 --from-file=./username.txt --from-file=./password.txt
- 3.通过 
--from-env-file 
cat > env.txt << EOF
username=admin
password=123456
EOF
kubectl create secret generic mysecret3 --from-env-file=env.txt
- 4.通过 YAML 配置
 
mysecrete.yaml
apiVersion: v1
kind: Secret
metadata:
  name: mysecret4
data:
  username: YWRtaW4=
  password: MTIzNDU2
创建Secret
kubectl apply -f mysecrete.yaml
- 查看创建的 Secret
 
kubectl get secret
- 查看Secret中的Key
 
kubectl describe secret mysecret
- 查看Secret中的Value
 
kubectl edit secret mysecret
- 对内容进行解码
 
echo -n YWRtaW4= | base64 --decode
使用Secret
- mypod.yaml
 
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
- 创建Pod并在容器中读取Secret
 
kubectl apply -f mypod.yaml
kubectl exec -it mypod cat /etc/foo/username
kubectl exec -it mypod cat /etc/foo/password
- 自定义存放数据文件名 mypod1.yaml
 
apiVersion: v1
kind: Pod
metadata:
  name: mypod1
spec:
  containers:
  - name: mypod1
    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
- 查看数据
 
kubectl apply -f mypod1.yaml
kubectl exec -it mypod1 cat /etc/foo/my-group/my-username
以 Volume 方式使用的 Secret 支持动态更新:Secret 更新后,容器中的数据也会更新。
环境变量方式使用Secret
- mypod-env.yaml
 
apiVersion: v1
kind: Pod
metadata:
  name: mypod2
spec:
  containers:
  - name: mypod2
    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
- 创建Pod并读取Secret
 
ubuntu2@root  k8s-learn kubectl apply -f mypod-env.yaml
pod/mypod2 unchanged
ubuntu2@root  k8s-learn kubectl exec -it mypod2 sh
/ # echo "$SECRET_USERNAME" && echo "$SECRET_PASSWORD"
admin
123456
/ #
环境变量读取 Secret 很方便,但无法支撑 Secret 动态更新。