k8s管理機密信息

Secret介紹:

應用啓動過程中可能需要一些敏感信息,比如訪問數據庫的用戶名密碼或者祕鑰。將這些信息直接保存在容器鏡像中顯然不妥,Kubernetes 提供的解決方案是 Secret。

Secret 會以密文的方式存儲數據,避免了直接在配置文件中保存敏感信息。Secret 會以 Volume 的形式被 mount 到 Pod,容器可通過文件的方式使用 Secret 中的敏感數據;此外,容器也可以環境變量的方式使用這些數據。

Secret 可通過命令行或 YAML 創建。比如希望 Secret 中包含如下信息:

  1. 用戶名 admin

  2. 密碼 123456

 

 

創建 Secret

有四種方法創建 Secret:

1. 通過 --from-literal

#kubectl create secret generic mysecret --from-literal=username=admin --from-literal=password=123

 

 

2. 通過 --from-file

#echo -n admin > ./username

#echo -n 123456 > ./password

#kubectl create secret generic mysecret1 --from-file=./username --from-file=./password

 

3. 通過 --from-env-file

#cat << EOF > env.txt

username=admin

password=123456

EOF

#kubectl create secret generic mysecret2 --from-env-file=env.txt

 

 

4. 通過 YAML 配置文件:

文件中的敏感數據必須是通過 base64 編碼後的結果。

執行 kubectl apply 創建 Secret:

如果還想查看 Value,可以用 kubectl edit secret mysecret

然後通過 base64 將 Value 反編碼:

volume 方式使用 Secret

Pod 可以通過 Volume 或者環境變量的方式使用 Secret,先學習 Volume 方式。

(1)Pod 的配置文件如下所示:

#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

 

可以看到,Kubernetes 會在指定的路徑 /etc/foo 下爲每條敏感數據創建一個文件,文件名就是數據條目的 Key,這裏是 /etc/foo/username 和 /etc/foo/password,Value 則以明文存放在文件中。

① 定義 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。

幾秒鐘或,新的 password 會同步到容器。

 

環境變量方式使用 Secret

通過 Volume 使用 Secret,容器必須從文件讀取數據,會稍顯麻煩,Kubernetes 還支持通過環境變量使用 Secret。

Pod 配置文件示例如下:

 

創建 Pod 並讀取 Secret。

 

通過環境變量 SECRET_USERNAME 和 SECRET_PASSWORD 成功讀取到 Secret 的數據。

需要注意的是,環境變量讀取 Secret 很方便,但無法支撐 Secret 動態更新。

Secret 可以爲 Pod 提供密碼、Token、私鑰等敏感數據;

 

刪除

#kubectl delete secret mysecret
或
#kubectl delete -f mysecret.yml

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章