Secret介紹:
應用啓動過程中可能需要一些敏感信息,比如訪問數據庫的用戶名密碼或者祕鑰。將這些信息直接保存在容器鏡像中顯然不妥,Kubernetes 提供的解決方案是 Secret。
Secret 可通過命令行或 YAML 創建。比如希望 Secret 中包含如下信息:
創建 Secret
#kubectl create secret generic mysecret --from-literal=username=admin --from-literal=password=123
#echo -n admin > ./username
#echo -n 123456 > ./password
#kubectl create secret generic mysecret1 --from-file=./username --from-file=./password
#cat << EOF > env.txt
username=admin
password=123456
EOF
#kubectl create secret generic mysecret2 --from-env-file=env.txt
如果還想查看 Value,可以用 kubectl edit secret mysecret
volume 方式使用 Secret
Pod 可以通過 Volume 或者環境變量的方式使用 Secret,先學習 Volume 方式。
#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
① 定義 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
通過 Volume 使用 Secret,容器必須從文件讀取數據,會稍顯麻煩,Kubernetes 還支持通過環境變量使用 Secret。
通過環境變量 SECRET_USERNAME 和 SECRET_PASSWORD 成功讀取到 Secret 的數據。
需要注意的是,環境變量讀取 Secret 很方便,但無法支撐 Secret 動態更新。
Secret 可以爲 Pod 提供密碼、Token、私鑰等敏感數據;
刪除
#kubectl delete secret mysecret
或
#kubectl delete -f mysecret.yml