Kubernetes的Secret对象的使用

Secret可以想要访问的加密数据,存放到Etcd中,Pod可以通过的Volume的方式,访问到Secret保存的信息

一、创建方式

  1. 通过文件
    生成两个文件
echo "chenqionghe" > ./username.txt
echo "111111" > ./password.txt
知识兔

创建

kubectl create secret generic user --from-file=./username.txt
kubectl create secret generic pass --from-file=./password.txt
知识兔
  1. 通过yaml
    注意:值必须是base64转码
apiVersion: v1
kind: Secret
metadata:
  name: mysecret
type: Opaque
data:
  user:  Y2hlbnFpb25naGUK
  pass: MTExMTExCg==
知识兔

创建

kubectl apply -f mysecret.yaml
知识兔

二、获取secret对象

root@VM-0-8-ubuntu:/home/ubuntu/project-volume# kubectl get secrets
NAME TYPE DATA AGE
default-token-gqfrx kubernetes.io/service-account-token 3 20d
mysecret Opaque 2 1m
pass Opaque 1 6m
user Opaque 1 6m
知识兔

三、通过pod使用secret示例

这里指定了volume是projected类型,引用的是secret的user和pass,挂载路径为/projected-volume

apiVersion: v1
kind: Pod
metadata:
  name: test-projected-volume 
spec:
  containers:
  - name: test-secret-volume
    image: busybox
    args:
    - sleep
    - "86400"
    volumeMounts:
    - name: mysql-cred
      mountPath: "/projected-volume"
      readOnly: true
  volumes:
  - name: mysql-cred
    projected:
      sources:
      - secret:
          name: user
      - secret:
          name: pass
知识兔

执行创建

kubectl apply -f test-projected-volume.yaml
知识兔

查看pod已经创建出来

root@VM-0-8-ubuntu:/home/ubuntu/project-volume# kubectl get pod
NAME READY STATUS RESTARTS AGE
test-projected-volume 1/1 Running 0 5m
知识兔

再进入pod内查看,看到文件已经存在,并且内容和设置的一样

root@VM-0-8-ubuntu:/home/ubuntu/project-volume# kubectl exec -it test-projected-volume -- /bin/sh
/ # ls /projected-volume/
password.txt username.txt
/ # cat /projected-volume/username.txt
chenqionghe
知识兔
计算机