Kubernetes的Secret對象使用
- 2019 年 10 月 3 日
- 筆記
Secret可以把想要訪問的加密數據,存放到Etcd中,然後Pod可以通過的Volume的方式,訪問到Secret保存的信息 ,每當數據修改的時候,Pod掛載的Secret文件也會被修改,特別適合用來存放賬戶密碼
一、創建Secret對象
1. 通過文件創建
生成兩個文件,分別是username.txt和password.txt
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
2. 通過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
然後我們修改一下username的secret文件,將chenqionghe修改為cqh(對應的base編碼為Y3FoCg==)
kubectl edit secret user
修改內容如下
apiVersion: v1 data: username.txt: Y3FoCg== kind: Secret metadata: creationTimestamp: 2019-09-27T09:14:00Z name: user namespace: default resourceVersion: "2108808" selfLink: /api/v1/namespaces/default/secrets/user uid: 24566f8f-e107-11e9-8c22-f242c645cfec type: Opaque
再次查看pod中掛載的文件,已經發生變化
root@VM-0-8-ubuntu:/home/ubuntu# kubectl exec -it test-projected-volume -- cat /projected-volume/username.txt cqh