為了讓應用程式可以方便轉移或避免重新編譯 image, 因此會將配置與應用程式解構, 以單獨的 ConfigMap 配置. 本篇筆記將補充說明 ConfigMap 的使用範例:
假設有一個 deployment 的 yaml 檔案如下, 其中有環境變數 log_level 設定為 Error
File: reader_deployment.yaml
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: logreader
spec:
replicas: 1
template:
metadata:
labels:
name: logreader
spec:
containers:
- name: logreader
image: karthequian/reader:latest
env:
- name: log_level
value: "error"
PS C:\k8s> kubectl apply -f .\reader-deployment.yaml
deployment.extensions "logreader" created
PS C:\k8s> kubectl get pods
NAME READY STATUS RESTARTS AGE
logreader-79d45779fd-cqc26 1/1 Running 0 2m
logs logreader-79d45779fd-cqc26
觀察環境變數輸出PS C:\k8s> kubectl logs logreader-79d45779fd-cqc26
Log level passed via env variables was: 'error'
Log level passed via env variables was: 'error'
Log level passed via env variables was: 'error'
<略…>
如果我們把 log_level 改為 ConfigMap, 並且在 deployment yaml 檔案中設定. 便可以將 log_level 獨立於應用程式之外, 以下示範如何建立與使用 ConfigMap
configmap
logger --from-literal=log_level=debug 建立 configMap 物件PS C:\k8s> kubectl create configmap logger --from-literal=log_level=debug
configmap "logger" created
valueFrom: configMapKeyRef
, 取得名稱為 logger 的 log_level key 值apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: logreader-dynamic
spec:
replicas: 1
template:
metadata:
labels:
name: logreader-dynamic
spec:
containers:
- name: logreader
image: karthequian/reader:latest
env:
- name: log_level
valueFrom:
configMapKeyRef:
name: logger #Read from a configmap called log-level
key: log_level #Read the key called log_level
PS C:\k8s> kubectl create -f .\reader-configmap-deployment.yaml
deployment.extensions "logreader-dynamic" created
PS C:\k8s> kubectl get pods
NAME READY STATUS RESTARTS AGE
Running 0 15m
logreader-dynamic-7fc69448f6-tvfkn 1/1
PS C:\k8s> kubectl logs logreader-dynamic-7fc69448f6-tvfkn
Log level passed via env variables was: 'debug'
Log level passed via env variables was: 'debug'
Log level passed via env variables was: 'debug'
Log level passed via env variables was: 'debug'
<略…>
我們可以看到 log_level 變數讀取 ConfigMap 的 設定值: debug. 以上就是簡單的使用 ConfigMap 範例.
https://www.linkedin.com/learning/learning-kubernetes/dealing-with-configuration-data