設定 Pod 以使用 ConfigMap

許多應用程式依賴組態,這些組態在應用程式初始化或執行階段期間使用。大多數時候,都需要調整指派給組態參數的值。ConfigMap 是一種 Kubernetes 機制,可讓您將組態資料注入應用程式pod

ConfigMap 概念可讓您將組態成品與映像檔內容分離,以保持容器化應用程式的可攜性。例如,您可以下載並執行相同的容器映像檔,以啟動容器以用於本機開發、系統測試或執行即時最終使用者工作負載。

本頁提供一系列使用範例,示範如何建立 ConfigMap 以及如何使用儲存在 ConfigMap 中的資料設定 Pod。

準備開始

您需要有一個 Kubernetes 叢集,並且必須設定 kubectl 命令列工具以與您的叢集通訊。建議在至少有兩個節點且未充當控制平面主機的叢集上執行本教學課程。如果您還沒有叢集,可以使用minikube建立一個,或者您可以使用這些 Kubernetes Playground 之一

您需要安裝 wget 工具。如果您有不同的工具 (例如 curl),並且沒有 wget,則需要調整下載範例資料的步驟。

建立 ConfigMap

您可以使用 kubectl create configmapkustomization.yaml 中的 ConfigMap 產生器來建立 ConfigMap。

使用 kubectl create configmap 建立 ConfigMap

使用 kubectl create configmap 命令從目錄檔案文字值建立 ConfigMap

kubectl create configmap <map-name> <data-source>

其中 <map-name> 是您要指派給 ConfigMap 的名稱,而 <data-source> 是要從中提取資料的目錄、檔案或文字值。ConfigMap 物件的名稱必須是有效的DNS 子網域名稱

當您根據檔案建立 ConfigMap 時,<data-source> 中的金鑰預設為檔案的基本名稱,而值預設為檔案內容。

您可以使用kubectl describekubectl get 來檢索有關 ConfigMap 的資訊。

從目錄建立 ConfigMap

您可以使用 kubectl create configmap 從同一目錄中的多個檔案建立 ConfigMap。當您根據目錄建立 ConfigMap 時,kubectl 會識別目錄中檔名為有效金鑰的檔案,並將每個檔案打包到新的 ConfigMap 中。除了常規檔案之外的任何目錄項目都會被忽略 (例如:子目錄、符號連結、裝置、管道等)。

建立本機目錄

mkdir -p configure-pod-container/configmap/

現在,下載範例組態並建立 ConfigMap

# Download the sample files into `configure-pod-container/configmap/` directory
wget https://kubernetes.dev.org.tw/examples/configmap/game.properties -O configure-pod-container/configmap/game.properties
wget https://kubernetes.dev.org.tw/examples/configmap/ui.properties -O configure-pod-container/configmap/ui.properties

# Create the ConfigMap
kubectl create configmap game-config --from-file=configure-pod-container/configmap/

上述指令會將每個檔案(在此範例中為 game.propertiesui.properties)封裝到 configure-pod-container/configmap/ 目錄中,成為 game-config ConfigMap。您可以使用以下指令顯示 ConfigMap 的詳細資訊

kubectl describe configmaps game-config

輸出結果會類似於這樣:

Name:         game-config
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
game.properties:
----
enemies=aliens
lives=3
enemies.cheat=true
enemies.cheat.level=noGoodRotten
secret.code.passphrase=UUDDLRLRBABAS
secret.code.allowed=true
secret.code.lives=30
ui.properties:
----
color.good=purple
color.bad=yellow
allow.textmode=true
how.nice.to.look=fairlyNice

configure-pod-container/configmap/ 目錄中的 game.propertiesui.properties 檔案會以 ConfigMap 的 data 區段呈現。

kubectl get configmaps game-config -o yaml

輸出結果會類似於這樣:

apiVersion: v1
kind: ConfigMap
metadata:
  creationTimestamp: 2022-02-18T18:52:05Z
  name: game-config
  namespace: default
  resourceVersion: "516"
  uid: b4952dc3-d670-11e5-8cd0-68f728db1985
data:
  game.properties: |
    enemies=aliens
    lives=3
    enemies.cheat=true
    enemies.cheat.level=noGoodRotten
    secret.code.passphrase=UUDDLRLRBABAS
    secret.code.allowed=true
    secret.code.lives=30    
  ui.properties: |
    color.good=purple
    color.bad=yellow
    allow.textmode=true
    how.nice.to.look=fairlyNice    

從檔案建立 ConfigMap

您可以使用 kubectl create configmap 從單個檔案或多個檔案建立 ConfigMap。

例如:

kubectl create configmap game-config-2 --from-file=configure-pod-container/configmap/game.properties

會產生以下 ConfigMap

kubectl describe configmaps game-config-2

其中輸出結果會類似於這樣:

Name:         game-config-2
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
game.properties:
----
enemies=aliens
lives=3
enemies.cheat=true
enemies.cheat.level=noGoodRotten
secret.code.passphrase=UUDDLRLRBABAS
secret.code.allowed=true
secret.code.lives=30

您可以多次傳遞 --from-file 引數,以從多個資料來源建立 ConfigMap。

kubectl create configmap game-config-2 --from-file=configure-pod-container/configmap/game.properties --from-file=configure-pod-container/configmap/ui.properties

您可以使用以下指令顯示 game-config-2 ConfigMap 的詳細資訊

kubectl describe configmaps game-config-2

輸出結果會類似於這樣:

Name:         game-config-2
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
game.properties:
----
enemies=aliens
lives=3
enemies.cheat=true
enemies.cheat.level=noGoodRotten
secret.code.passphrase=UUDDLRLRBABAS
secret.code.allowed=true
secret.code.lives=30
ui.properties:
----
color.good=purple
color.bad=yellow
allow.textmode=true
how.nice.to.look=fairlyNice

使用 --from-env-file 選項從 env-file 建立 ConfigMap,例如:

# Env-files contain a list of environment variables.
# These syntax rules apply:
#   Each line in an env file has to be in VAR=VAL format.
#   Lines beginning with # (i.e. comments) are ignored.
#   Blank lines are ignored.
#   There is no special handling of quotation marks (i.e. they will be part of the ConfigMap value)).

# Download the sample files into `configure-pod-container/configmap/` directory
wget https://kubernetes.dev.org.tw/examples/configmap/game-env-file.properties -O configure-pod-container/configmap/game-env-file.properties
wget https://kubernetes.dev.org.tw/examples/configmap/ui-env-file.properties -O configure-pod-container/configmap/ui-env-file.properties

# The env-file `game-env-file.properties` looks like below
cat configure-pod-container/configmap/game-env-file.properties
enemies=aliens
lives=3
allowed="true"

# This comment and the empty line above it are ignored
kubectl create configmap game-config-env-file \
       --from-env-file=configure-pod-container/configmap/game-env-file.properties

會產生一個 ConfigMap。檢視 ConfigMap:

kubectl get configmap game-config-env-file -o yaml

輸出結果會類似於:

apiVersion: v1
kind: ConfigMap
metadata:
  creationTimestamp: 2019-12-27T18:36:28Z
  name: game-config-env-file
  namespace: default
  resourceVersion: "809965"
  uid: d9d1ca5b-eb34-11e7-887b-42010a8002b8
data:
  allowed: '"true"'
  enemies: aliens
  lives: "3"

從 Kubernetes v1.23 開始,kubectl 支援多次指定 --from-env-file 引數,以從多個資料來源建立 ConfigMap。

kubectl create configmap config-multi-env-files \
        --from-env-file=configure-pod-container/configmap/game-env-file.properties \
        --from-env-file=configure-pod-container/configmap/ui-env-file.properties

會產生以下 ConfigMap

kubectl get configmap config-multi-env-files -o yaml

其中輸出結果會類似於這樣:

apiVersion: v1
kind: ConfigMap
metadata:
  creationTimestamp: 2019-12-27T18:38:34Z
  name: config-multi-env-files
  namespace: default
  resourceVersion: "810136"
  uid: 252c4572-eb35-11e7-887b-42010a8002b8
data:
  allowed: '"true"'
  color: purple
  enemies: aliens
  how: fairlyNice
  lives: "3"
  textmode: "true"

定義從檔案建立 ConfigMap 時要使用的鍵

當使用 --from-file 引數時,您可以定義一個不同於檔案名稱的鍵,以在 ConfigMap 的 data 區段中使用。

kubectl create configmap game-config-3 --from-file=<my-key-name>=<path-to-file>

其中 <my-key-name> 是您想要在 ConfigMap 中使用的鍵,而 <path-to-file> 是您希望鍵代表的資料來源檔案位置。

例如:

kubectl create configmap game-config-3 --from-file=game-special-key=configure-pod-container/configmap/game.properties

會產生以下 ConfigMap

kubectl get configmaps game-config-3 -o yaml

其中輸出結果會類似於這樣:

apiVersion: v1
kind: ConfigMap
metadata:
  creationTimestamp: 2022-02-18T18:54:22Z
  name: game-config-3
  namespace: default
  resourceVersion: "530"
  uid: 05f8da22-d671-11e5-8cd0-68f728db1985
data:
  game-special-key: |
    enemies=aliens
    lives=3
    enemies.cheat=true
    enemies.cheat.level=noGoodRotten
    secret.code.passphrase=UUDDLRLRBABAS
    secret.code.allowed=true
    secret.code.lives=30    

從字面值建立 ConfigMap

您可以使用帶有 --from-literal 引數的 kubectl create configmap,從命令列定義字面值。

kubectl create configmap special-config --from-literal=special.how=very --from-literal=special.type=charm

您可以傳遞多個鍵值對。命令列上提供的每個鍵值對都以 ConfigMap 的 data 區段中的個別條目表示。

kubectl get configmaps special-config -o yaml

輸出結果會類似於這樣:

apiVersion: v1
kind: ConfigMap
metadata:
  creationTimestamp: 2022-02-18T19:14:38Z
  name: special-config
  namespace: default
  resourceVersion: "651"
  uid: dadce046-d673-11e5-8cd0-68f728db1985
data:
  special.how: very
  special.type: charm

從產生器建立 ConfigMap

您也可以從產生器建立 ConfigMap,然後套用它以在叢集的 API 伺服器中建立物件。您應該在目錄中的 kustomization.yaml 檔案中指定產生器。

從檔案產生 ConfigMap

例如,從檔案 configure-pod-container/configmap/game.properties 產生 ConfigMap:

# Create a kustomization.yaml file with ConfigMapGenerator
cat <<EOF >./kustomization.yaml
configMapGenerator:
- name: game-config-4
  options:
    labels:
      game-config: config-4
  files:
  - configure-pod-container/configmap/game.properties
EOF

套用 kustomization 目錄以建立 ConfigMap 物件

kubectl apply -k .
configmap/game-config-4-m9dm2f92bt created

您可以像這樣檢查 ConfigMap 是否已建立

kubectl get configmap
NAME                       DATA   AGE
game-config-4-m9dm2f92bt   1      37s

以及

kubectl describe configmaps/game-config-4-m9dm2f92bt
Name:         game-config-4-m9dm2f92bt
Namespace:    default
Labels:       game-config=config-4
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"v1","data":{"game.properties":"enemies=aliens\nlives=3\nenemies.cheat=true\nenemies.cheat.level=noGoodRotten\nsecret.code.p...

Data
====
game.properties:
----
enemies=aliens
lives=3
enemies.cheat=true
enemies.cheat.level=noGoodRotten
secret.code.passphrase=UUDDLRLRBABAS
secret.code.allowed=true
secret.code.lives=30
Events:  <none>

請注意,產生的 ConfigMap 名稱附加了一個透過雜湊內容產生的後綴。這確保了每次修改內容時都會產生新的 ConfigMap。

定義從檔案產生 ConfigMap 時要使用的鍵

您可以定義一個不同於檔案名稱的鍵,以在 ConfigMap 產生器中使用。例如,從檔案 configure-pod-container/configmap/game.properties 產生 ConfigMap,並使用鍵 game-special-key

# Create a kustomization.yaml file with ConfigMapGenerator
cat <<EOF >./kustomization.yaml
configMapGenerator:
- name: game-config-5
  options:
    labels:
      game-config: config-5
  files:
  - game-special-key=configure-pod-container/configmap/game.properties
EOF

套用 kustomization 目錄以建立 ConfigMap 物件。

kubectl apply -k .
configmap/game-config-5-m67dt67794 created

從字面值產生 ConfigMap

此範例示範如何使用 Kustomize 和 kubectl 從兩個字面鍵值對建立 ConfigMapspecial.type=charmspecial.how=very。為了實現這一點,您可以指定 ConfigMap 產生器。建立(或取代)kustomization.yaml,使其具有以下內容:

---
# kustomization.yaml contents for creating a ConfigMap from literals
configMapGenerator:
- name: special-config-2
  literals:
  - special.how=very
  - special.type=charm

套用 kustomization 目錄以建立 ConfigMap 物件

kubectl apply -k .
configmap/special-config-2-c92b5mmcf2 created

臨時清理

在繼續之前,清理您建立的一些 ConfigMap

kubectl delete configmap special-config
kubectl delete configmap env-config
kubectl delete configmap -l 'game-config in (config-4,config-5)'

現在您已經學會如何定義 ConfigMap,您可以繼續下一節,並學習如何在 Pod 中使用這些物件。


使用 ConfigMap 資料定義容器環境變數

使用來自單個 ConfigMap 的資料定義容器環境變數

  1. 將環境變數定義為 ConfigMap 中的鍵值對

    kubectl create configmap special-config --from-literal=special.how=very
    
  2. 將 ConfigMap 中定義的 special.how 值指派給 Pod 規格中的 SPECIAL_LEVEL_KEY 環境變數。

    apiVersion: v1
    kind: Pod
    metadata:
      name: dapi-test-pod
    spec:
      containers:
        - name: test-container
          image: registry.k8s.io/busybox
          command: [ "/bin/sh", "-c", "env" ]
          env:
            # Define the environment variable
            - name: SPECIAL_LEVEL_KEY
              valueFrom:
                configMapKeyRef:
                  # The ConfigMap containing the value you want to assign to SPECIAL_LEVEL_KEY
                  name: special-config
                  # Specify the key associated with the value
                  key: special.how
      restartPolicy: Never
    

    建立 Pod

    kubectl create -f https://kubernetes.dev.org.tw/examples/pods/pod-single-configmap-env-variable.yaml
    

    現在,Pod 的輸出包含環境變數 SPECIAL_LEVEL_KEY=very

使用來自多個 ConfigMap 的資料定義容器環境變數

與先前的範例一樣,首先建立 ConfigMap。以下是您將使用的 manifest:

apiVersion: v1
kind: ConfigMap
metadata:
  name: special-config
  namespace: default
data:
  special.how: very
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: env-config
  namespace: default
data:
  log_level: INFO
  • 建立 ConfigMap

    kubectl create -f https://kubernetes.dev.org.tw/examples/configmap/configmaps.yaml
    
  • 在 Pod 規格中定義環境變數。

    apiVersion: v1
    kind: Pod
    metadata:
      name: dapi-test-pod
    spec:
      containers:
        - name: test-container
          image: registry.k8s.io/busybox
          command: [ "/bin/sh", "-c", "env" ]
          env:
            - name: SPECIAL_LEVEL_KEY
              valueFrom:
                configMapKeyRef:
                  name: special-config
                  key: special.how
            - name: LOG_LEVEL
              valueFrom:
                configMapKeyRef:
                  name: env-config
                  key: log_level
      restartPolicy: Never
    

    建立 Pod

    kubectl create -f https://kubernetes.dev.org.tw/examples/pods/pod-multiple-configmap-env-variable.yaml
    

    現在,Pod 的輸出包含環境變數 SPECIAL_LEVEL_KEY=veryLOG_LEVEL=INFO

    當您準備好繼續時,刪除該 Pod 和 ConfigMap

    kubectl delete pod dapi-test-pod --now
    kubectl delete configmap special-config
    kubectl delete configmap env-config
    

將 ConfigMap 中的所有鍵值對設定為容器環境變數

  • 建立包含多個鍵值對的 ConfigMap。

    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: special-config
      namespace: default
    data:
      SPECIAL_LEVEL: very
      SPECIAL_TYPE: charm
    

    建立 ConfigMap

    kubectl create -f https://kubernetes.dev.org.tw/examples/configmap/configmap-multikeys.yaml
    
  • 使用 envFrom 將 ConfigMap 的所有資料定義為容器環境變數。ConfigMap 中的鍵會成為 Pod 中的環境變數名稱。

    apiVersion: v1
    kind: Pod
    metadata:
      name: dapi-test-pod
    spec:
      containers:
        - name: test-container
          image: registry.k8s.io/busybox
          command: [ "/bin/sh", "-c", "env" ]
          envFrom:
          - configMapRef:
              name: special-config
      restartPolicy: Never
    

    建立 Pod

    kubectl create -f https://kubernetes.dev.org.tw/examples/pods/pod-configmap-envFrom.yaml
    

    現在,Pod 的輸出包含環境變數 SPECIAL_LEVEL=verySPECIAL_TYPE=charm

    當您準備好繼續時,刪除該 Pod

    kubectl delete pod dapi-test-pod --now
    

在 Pod 指令中使用 ConfigMap 定義的環境變數

您可以使用 $(VAR_NAME) Kubernetes 替換語法,在容器的 commandargs 中使用 ConfigMap 定義的環境變數。

例如,以下 Pod manifest:

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: registry.k8s.io/busybox
      command: [ "/bin/echo", "$(SPECIAL_LEVEL_KEY) $(SPECIAL_TYPE_KEY)" ]
      env:
        - name: SPECIAL_LEVEL_KEY
          valueFrom:
            configMapKeyRef:
              name: special-config
              key: SPECIAL_LEVEL
        - name: SPECIAL_TYPE_KEY
          valueFrom:
            configMapKeyRef:
              name: special-config
              key: SPECIAL_TYPE
  restartPolicy: Never

透過執行以下指令來建立該 Pod:

kubectl create -f https://kubernetes.dev.org.tw/examples/pods/pod-configmap-env-var-valueFrom.yaml

該 Pod 從 test-container 容器產生以下輸出:

kubectl logs dapi-test-pod
very charm

當您準備好繼續時,刪除該 Pod

kubectl delete pod dapi-test-pod --now

將 ConfigMap 資料新增至 Volume

從檔案建立 ConfigMap中所述,當您使用 --from-file 建立 ConfigMap 時,檔案名稱會成為儲存在 ConfigMap 的 data 區段中的鍵。檔案內容會成為鍵的值。

本節中的範例參考名為 special-config 的 ConfigMap

apiVersion: v1
kind: ConfigMap
metadata:
  name: special-config
  namespace: default
data:
  SPECIAL_LEVEL: very
  SPECIAL_TYPE: charm

建立 ConfigMap

kubectl create -f https://kubernetes.dev.org.tw/examples/configmap/configmap-multikeys.yaml

使用儲存在 ConfigMap 中的資料填充 Volume

在 Pod 規格的 volumes 區段下新增 ConfigMap 名稱。這會將 ConfigMap 資料新增至指定為 volumeMounts.mountPath 的目錄(在本例中為 /etc/config)。command 區段列出目錄檔案,其名稱與 ConfigMap 中的鍵相符。

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: registry.k8s.io/busybox
      command: [ "/bin/sh", "-c", "ls /etc/config/" ]
      volumeMounts:
      - name: config-volume
        mountPath: /etc/config
  volumes:
    - name: config-volume
      configMap:
        # Provide the name of the ConfigMap containing the files you want
        # to add to the container
        name: special-config
  restartPolicy: Never

建立 Pod

kubectl create -f https://kubernetes.dev.org.tw/examples/pods/pod-configmap-volume.yaml

當 Pod 執行時,指令 ls /etc/config/ 會產生以下輸出:

SPECIAL_LEVEL
SPECIAL_TYPE

文字資料會使用 UTF-8 字元編碼以檔案形式公開。若要使用其他字元編碼,請使用 binaryData(詳情請參閱ConfigMap 物件)。

當您準備好繼續時,刪除該 Pod

kubectl delete pod dapi-test-pod --now

將 ConfigMap 資料新增至 Volume 中的特定路徑

使用 path 欄位指定特定 ConfigMap 項目所需的檔案路徑。在此範例中,SPECIAL_LEVEL 項目將會掛載在 config-volume Volume 的 /etc/config/keys 中。

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: registry.k8s.io/busybox
      command: [ "/bin/sh","-c","cat /etc/config/keys" ]
      volumeMounts:
      - name: config-volume
        mountPath: /etc/config
  volumes:
    - name: config-volume
      configMap:
        name: special-config
        items:
        - key: SPECIAL_LEVEL
          path: keys
  restartPolicy: Never

建立 Pod

kubectl create -f https://kubernetes.dev.org.tw/examples/pods/pod-configmap-volume-specific-key.yaml

當 Pod 執行時,指令 cat /etc/config/keys 會產生以下輸出:

very

刪除該 Pod

kubectl delete pod dapi-test-pod --now

將鍵投影到特定路徑和檔案權限

您可以將鍵投影到特定路徑。請參閱Secrets指南中的相應章節,以瞭解語法。
您可以為鍵設定 POSIX 權限。請參閱Secrets指南中的相應章節,以瞭解語法。

選用參考

ConfigMap 參考可以標記為選用。如果 ConfigMap 不存在,則掛載的 Volume 將為空。如果 ConfigMap 存在,但參考的鍵不存在,則路徑將在掛載點下方不存在。有關更多詳細資訊,請參閱選用 ConfigMap

掛載的 ConfigMap 會自動更新

當掛載的 ConfigMap 更新時,投影的內容最終也會更新。這適用於在 Pod 啟動後,選用參考的 ConfigMap 出現的情況。

Kubelet 會在每個定期同步時檢查掛載的 ConfigMap 是否為最新狀態。但是,它使用其本機基於 TTL 的快取來取得 ConfigMap 的目前值。因此,從 ConfigMap 更新到新鍵投影到 Pod 的時刻之間的總延遲,可能長達 kubelet 同步週期(預設為 1 分鐘)+ kubelet 中 ConfigMap 快取的 TTL(預設為 1 分鐘)。您可以透過更新 Pod 的其中一個註釋來觸發立即重新整理。

瞭解 ConfigMap 和 Pod

ConfigMap API 資源將組態資料儲存為鍵值對。資料可以在 Pod 中使用,或為系統元件(例如控制器)提供組態。ConfigMap 類似於 Secrets,但提供了一種處理不包含敏感資訊的字串的方法。使用者和系統元件都可以將組態資料儲存在 ConfigMap 中。

ConfigMap 的 data 欄位包含組態資料。如下例所示,這可以是簡單的(例如使用 --from-literal 定義的個別屬性),也可以是複雜的(例如使用 --from-file 定義的組態檔案或 JSON blobs)。

apiVersion: v1
kind: ConfigMap
metadata:
  creationTimestamp: 2016-02-18T19:14:38Z
  name: example-config
  namespace: default
data:
  # example of a simple property defined using --from-literal
  example.property.1: hello
  example.property.2: world
  # example of a complex property defined using --from-file
  example.property.file: |-
    property.1=value-1
    property.2=value-2
    property.3=value-3    

kubectl 從非 ASCII 或 UTF-8 的輸入建立 ConfigMap 時,該工具會將這些輸入放入 ConfigMap 的 binaryData 欄位,而不是 data 中。文字和二進位資料來源都可以組合在一個 ConfigMap 中。

如果您想檢視 ConfigMap 中的 binaryData 鍵(及其值),您可以執行 kubectl get configmap -o jsonpath='{.binaryData}' <name>

Pod 可以從使用 databinaryData 的 ConfigMap 載入資料。

選用 ConfigMap

您可以將對 ConfigMap 的參考在 Pod 規格中標記為選用。如果 ConfigMap 不存在,則 Pod 中為其提供資料的組態(例如:環境變數、掛載的 Volume)將為空。如果 ConfigMap 存在,但參考的鍵不存在,則資料也為空。

例如,以下 Pod 規格將來自 ConfigMap 的環境變數標記為選用:

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: gcr.io/google_containers/busybox
      command: ["/bin/sh", "-c", "env"]
      env:
        - name: SPECIAL_LEVEL_KEY
          valueFrom:
            configMapKeyRef:
              name: a-config
              key: akey
              optional: true # mark the variable as optional
  restartPolicy: Never

如果您執行此 Pod,且沒有名為 a-config 的 ConfigMap,則輸出為空。如果您執行此 Pod,並且有名為 a-config 的 ConfigMap,但該 ConfigMap 沒有名為 akey 的鍵,則輸出也為空。如果您確實為 a-config ConfigMap 中的 akey 設定一個值,則此 Pod 會列印該值,然後終止。

您也可以將 ConfigMap 提供的 Volume 和檔案標記為選用。即使參考的 ConfigMap 或鍵不存在,Kubernetes 始終會為 Volume 建立掛載路徑。例如,以下 Pod 規格將參考 ConfigMap 的 Volume 標記為選用:

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: gcr.io/google_containers/busybox
      command: ["/bin/sh", "-c", "ls /etc/config"]
      volumeMounts:
      - name: config-volume
        mountPath: /etc/config
  volumes:
    - name: config-volume
      configMap:
        name: no-config
        optional: true # mark the source ConfigMap as optional
  restartPolicy: Never

限制

  • 您必須先建立 ConfigMap 物件,然後才能在 Pod 規格中參考它。或者,將 Pod 規格中的 ConfigMap 參考標記為 optional(請參閱選用 ConfigMap)。如果您參考不存在的 ConfigMap,並且您沒有將參考標記為 optional,則 Pod 將無法啟動。同樣地,除非您將鍵參考標記為 optional,否則對 ConfigMap 中不存在的鍵的參考也會阻止 Pod 啟動。

  • 如果您使用 envFrom 從 ConfigMap 定義環境變數,則會跳過被視為無效的鍵。Pod 將被允許啟動,但無效的名稱將記錄在事件日誌中 (InvalidVariableNames)。日誌訊息列出每個跳過的鍵。例如:

    kubectl get events
    

    輸出結果會類似於這樣:

    LASTSEEN FIRSTSEEN COUNT NAME          KIND  SUBOBJECT  TYPE      REASON                            SOURCE                MESSAGE
    0s       0s        1     dapi-test-pod Pod              Warning   InvalidEnvironmentVariableNames   {kubelet, 127.0.0.1}  Keys [1badkey, 2alsobad] from the EnvFrom configMap default/myconfig were skipped since they are considered invalid environment variable names.
    
  • ConfigMap 位於特定的命名空間中。Pod 只能參考與 Pod 位於相同命名空間中的 ConfigMap。

  • 您不能將 ConfigMap 用於靜態 Pod,因為 kubelet 不支援此功能。

清理

刪除您建立的 ConfigMap 和 Pod

kubectl delete configmaps/game-config configmaps/game-config-2 configmaps/game-config-3 \
               configmaps/game-config-env-file
kubectl delete pod dapi-test-pod --now

# You might already have removed the next set
kubectl delete configmaps/special-config configmaps/env-config
kubectl delete configmap -l 'game-config in (config-4,config-5)'

移除您用來產生 ConfigMap 的 kustomization.yaml 檔案

rm kustomization.yaml

如果您建立了一個 configure-pod-container 目錄且不再需要它,您也應該將其移除,或將其移至垃圾桶/已刪除檔案位置。

rm -r configure-pod-container

下一步

上次修改時間為 2023 年 11 月 27 日凌晨 1:38 PST:[en] config-pod-configmap 新增清理步驟。 (2d13865044)