Kubernetes之使用ConfigMap配置Pod


  官方參考:https://kubernetes.io/zh/docs/tasks/configure-pod-container/configure-pod-configmap/

  創建ConfigMap  

  可以在 kustomization.yaml 中使用 kubectl create configmap 或 ConfigMap 生成器來創建ConfigMap。注意,從 1.14 版本開始, kubectl 開始支持 kustomization.yaml

  使用kubectl創建ConfigMap

  在目錄,文件或文字值中使用kubelet create configmap命令創建configmap

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

   其中, <map-name> 是要分配給 ConfigMap 的名稱,<data-source> 是要從中提取數據的目錄,文件或者文字值。

  數據源對應於 ConfigMap 中的 key-value (鍵值對)

  •  key=在命令行上題庫的文件名或者秘鑰
  •  value=在命令行上提供的文件內容或者文字值

  可以使用 kubelet describe或者kubelet get檢索有關ConfigMap的信息

  根據目錄創建ConfigMap

  你可以使用 kubectl create configmap 從同一目錄中的多個文件創建 ConfigMap。

#創建本地目錄
mkdir -p configure-pod-container/configmap/
#將樣板文件下載到創建的目錄
wget https://kubernetes.io/examples/configmap/game.properties -O configure-pod-container/configmap/game.properties
wget https://kubernetes.io/examples/configmap/ui.properties -O configure-pod-container/configmap/ui.properties
#創建configmap
kubectl create configmap game-config --from-file=configure-pod-container/configmap/

   合並了以下兩個文件的內容

# cat configure-pod-container/configmap/game.properties 
enemies=aliens
lives=3
enemies.cheat=true
enemies.cheat.level=noGoodRotten
secret.code.passphrase=UUDDLRLRBABAS
secret.code.allowed=true

# cat configure-pod-container/configmap/ui.properties 
color.good=purple
color.bad=yellow
allow.textmode=true
how.nice.to.look=fairlyNice

   進入以下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

Events:  <none>

   

kubectl get configmap game-config -o yaml

   輸出以下內容

apiVersion: v1
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
kind: ConfigMap
metadata:
  creationTimestamp: "2020-03-17T08:12:49Z"
  name: game-config
  namespace: default
  resourceVersion: "505452"
  selfLink: /api/v1/namespaces/default/configmaps/game-config
  uid: 1f3868e4-7a6b-4bf3-9317-00911ebc6e91

   根據文件創建ConfigMap

  可以使用kubelet 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
Events:  <none>

   可以傳入多個 --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

Events:  <none>

   使用 --from-env-file 選項從環境文件創建 ConfigMap,例如:

# 環境文件包含環境變量列表。
# 語法規則:
#   env 文件中的每一行必須為 VAR = VAL 格式。
#   以#開頭的行(即注釋)將被忽略。
#   空行將被忽略。
#   引號沒有特殊處理(即它們將成為 ConfigMap 值的一部分)。

# 將樣本文件下載到 `configure-pod-container/configmap/` 目錄
wget https://kubernetes.io/examples/configmap/game-env-file.properties -O configure-pod-container/configmap/game-env-file.properties

# env文件 `game-env-file.properties` 如下所示
cat configure-pod-container/configmap/game-env-file.properties
enemies=aliens
lives=3
allowed="true"

# 注釋及其上方的空行將被忽略

 

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

 

   將產生以下ConfigMap

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

   輸出類似以下內容

apiVersion: v1
data:
  allowed: '"true"'
  enemies: aliens
  lives: "3"
kind: ConfigMap
metadata:
  creationTimestamp: "2020-03-17T08:25:11Z"
  name: game-config-env-file
  namespace: default
  resourceVersion: "507620"
  selfLink: /api/v1/namespaces/default/configmaps/game-config-env-file
  uid: f22b64e7-2232-4c6a-aa85-afbbafb6bcac

   當使用多個 --from-env-file 來從多個數據源創建 ConfigMap 時,僅僅最后一個 env 文件有效:

# 將樣本文件下載到 `configure-pod-container/configmap/` 目錄
wget https://k8s.io/examples/configmap/ui-env-file.properties -O configure-pod-container/configmap/ui-env-file.properties

# 創建 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
data:
  color: purple
  how: fairlyNice
  textmode: "true"
kind: ConfigMap
metadata:
  creationTimestamp: "2020-03-17T08:31:36Z"
  name: config-multi-env-files
  namespace: default
  resourceVersion: "508738"
  selfLink: /api/v1/namespaces/default/configmaps/config-multi-env-files
  uid: d09564b2-b683-455c-8360-423edd3dbbbf

   定義從文件創建 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

apiVersion: v1
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
kind: ConfigMap
metadata:
  creationTimestamp: "2020-03-17T08:36:25Z"
  name: game-config-3
  namespace: default
  resourceVersion: "509581"
  selfLink: /api/v1/namespaces/default/configmaps/game-config-3
  uid: a9ca7b2b-28d1-4fc2-ac13-48e7147fcf87

   PS:使用文件創建的configmap默認的建名是文件名,以上自定義了其他建名不指定建名創建做對比

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

 

   根據文字值生成ConfigMap

  您可以將 kubectl create configmap 與 --from-literal 參數一起使用,從命令行定義文字值:

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
data:
  special.how: very
  special.type: charm
kind: ConfigMap
metadata:
  creationTimestamp: "2020-03-17T08:54:43Z"
  name: special-config
  namespace: default
  resourceVersion: "512776"
  selfLink: /api/v1/namespaces/default/configmaps/special-config
  uid: b7f972bf-1eef-4c74-b496-8b90cf3476d2

   根據生成器創建ConfigMap

  自 1.14 開始, kubectl 開始支持 kustomization.yaml。 您還可以從生成器創建 ConfigMap,然后將其應用於 Apiserver 創建對象。生成器應在目錄內的 kustomization.yaml 中指定。

# 使用 ConfigMapGenerator 創建 kustomization.yaml 文件
cat <<EOF >./kustomization.yaml
configMapGenerator:
- name: game-config-4
  files:
  - configure-pod-container/configmap/kubectl/game.properties
EOF

   使用 kustomization 目錄創建 ConfigMap 對象

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

   PS:文件kustomization.yaml需要與文件夾configure-pod-container在同一個目錄並且該文件夾下面沒有其他文件

   可以檢查ConfigMap是這樣創建的

# kubectl describe configmaps/game-config-4-m9dm2f92bt
Name:         game-config-4-m9dm2f92bt
Namespace:    default
Labels:       <none>
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是要使用建名

# cat kustomization.yaml 
configMapGenerator:
- name: game-config-5
  files:
  - game-special-key=configure-pod-container/configmap/kubectl/game.properties

   使用 Kustomization 目錄創建 ConfigMap 對象

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

   對比

 

   從文字生成CofigMap

#cat kustomization.yaml 
configMapGenerator:
- name: special-config-2
  literals:
  - special.how=very
  - special.type=charm

   使用 Kustomization 目錄創建 ConfigMap 對象。

kubectl apply -k .

   

kubectl describe configmap special-config-2-c92b5mmcf2

 

  輸出類似以下內容

Name:         special-config-2-c92b5mmcf2
Namespace:    default
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"v1","data":{"special.how":"very","special.type":"charm"},"kind":"ConfigMap","metadata":{"annotations":{},"name":"special-co...

Data
====
special.how:
----
very
special.type:
----
charm
Events:  <none>

   使用 ConfigMap 數據定義容器環境變量

   1.在ConfigMap中將環境變量定義為鍵值對

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

   查看該鍵值對

# kubectl get configmap special-config -o yaml
apiVersion: v1
data:
  special.how: very
kind: ConfigMap
metadata:
  creationTimestamp: "2020-03-18T01:47:01Z"
  name: special-config
  namespace: default
  resourceVersion: "689548"
  selfLink: /api/v1/namespaces/default/configmaps/special-config
  uid: 89b580f2-714d-4e47-87f6-90d18aa9aa3d

   將 ConfigMap 中定義的 special.how 值分配給 Pod 規范中的 SPECIAL_LEVEL_KEY 環境變量。

  下載示例Pod

wget https://kubernetes.io/examples/pods/pod-single-configmap-env-variable.yaml

   

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: busybox
      command: [ "/bin/sh", "-c", "env" ]
      env:
        # Define the environment variable
        # 定義容器內環境變量變量名為SPECIAL_LEVEL_KEY
        - name: SPECIAL_LEVEL_KEY
          valueFrom:
            configMapKeyRef:
              # The ConfigMap containing the value you want to assign to SPECIAL_LEVEL_KEY
              # 包含鍵值映射的configmap為special-config
              name: special-config
              # Specify the key associated with the value
              # 對應的key為special.how該key對應的值為very
              key: special.how
  restartPolicy: Never

   創建Pod

kubectl apply -f pod-single-configmap-env-variable.yaml

   該Pod運行日志輸出環境變量,查看日志

# kubectl logs dapi-test-pod
KUBERNETES_PORT=tcp://10.0.0.1:443
KUBERNETES_SERVICE_PORT=443
MY_SERVICE_PORT_80_TCP=tcp://10.0.0.47:80
HOSTNAME=dapi-test-pod
SHLVL=1
HOME=/root
MY_SERVICE_SERVICE_PORT_HTTP=80
MY_SERVICE_SERVICE_HOST=10.0.0.47
KUBERNETES_PORT_443_TCP_ADDR=10.0.0.1
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
KUBERNETES_PORT_443_TCP_PORT=443
KUBERNETES_PORT_443_TCP_PROTO=tcp
MY_SERVICE_SERVICE_PORT=80
MY_SERVICE_PORT=tcp://10.0.0.47:80
SPECIAL_LEVEL_KEY=very
MY_SERVICE_PORT_80_TCP_ADDR=10.0.0.47
KUBERNETES_SERVICE_PORT_HTTPS=443
KUBERNETES_PORT_443_TCP=tcp://10.0.0.1:443
MY_SERVICE_PORT_80_TCP_PORT=80
KUBERNETES_SERVICE_HOST=10.0.0.1
PWD=/
MY_SERVICE_PORT_80_TCP_PROTO=tcp

 

 

   該Pod執行完輸出環境變量以后因為重啟策略是Never就是完成狀態了

 

   使用多個ConfigMap定義容器變量

  創建ConfigMap

# cat configmaps.yaml 
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

   創建

kubectl apply -f configmaps.yaml 

   在Pod中定義環境變量

# cat pod-multiple-configmap-env-variable.yaml
apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: 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 apply -f pod-multiple-configmap-env-variable.yaml 

   現在,Pod 的輸出包含環境變量 SPECIAL_LEVEL_KEY=very 和 LOG_LEVEL=INFO

 

   將 ConfigMap 中的所有鍵值對配置為容器環境變量

  注意:Kubernetes v1.16和更高版本提供此功能

  創建一個包含多個鍵值對的ConfigMap

# cat configmap-multikeys.yaml 
apiVersion: v1
kind: ConfigMap
metadata:
  name: special-config
  namespace: default
data:
  SPECIAL_LEVEL: very
  SPECIAL_TYPE: charm

   創建ConfigMap

kubectl apply -f configmap-multikeys.yaml 

   查看創建的ConfigMap

# kubectl get configmap special-config -o yaml
apiVersion: v1
data:
  SPECIAL_LEVEL: very
  SPECIAL_TYPE: charm
kind: ConfigMap
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","data":{"SPECIAL_LEVEL":"very","SPECIAL_TYPE":"charm"},"kind":"ConfigMap","metadata":{"annotations":{},"name":"special-config","namespace":"default"}}
  creationTimestamp: "2020-03-18T02:13:48Z"
  name: special-config
  namespace: default
  resourceVersion: "694299"
  selfLink: /api/v1/namespaces/default/configmaps/special-config
  uid: 6df7c234-7ec6-4fad-8c5e-c34aa32f948a

  使用 envFrom 將所有 ConfigMap 的數據定義為容器環境變量,ConfigMap 中的鍵成為 Pod 中的環境變量名稱。  

  

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

  創建Pod

kubectl apply -f pod-configmap-envFrom.yaml

   現在,Pod 的輸出包含環境變量 SPECIAL_LEVEL=very 和 SPECIAL_TYPE=charm

 

   在 Pod 命令中使用 ConfigMap 定義的環境變量

# cat pod-configmap-env-var-valueFrom.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: busybox
      command: [ "/bin/sh", "-c", "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 apply -f pod-configmap-env-var-valueFrom.yaml

   在 test-container 容器中產生以下輸出:

# kubectl logs dapi-test-pod 
very charm

   將ConfigMap數據添加到一個容器中

  當您使用 --from-file 創建 ConfigMap 時,文件名成為存儲在 ConfigMap 的 data 部分中的key,文件內容成為key的值。

  本節中的示例引用了一個名為 special-config 的 ConfigMap,如下所示:

# cat configmap-multikeys.yaml 
apiVersion: v1
kind: ConfigMap
metadata:
  name: special-config
  namespace: default
data:
  SPECIAL_LEVEL: very
  SPECIAL_TYPE: charm

   創建ConfigMap

kubectl apply -f configmap-multikeys.yaml 

   使用存儲在 ConfigMap 中的數據填充容器

  在 Pod 規范的 volumes 部分下添加 ConfigMap 名稱。 這會將 ConfigMap 數據添加到指定為 volumeMounts.mountPath 的目錄(在本例中為/etc/config)。 command 引用存儲在 ConfigMap 中的 special.level

# cat pod-configmap-volume.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: 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 apply -f pod-configmap-volume.yaml

   容器運行命令 ls /etc/config/ 產生下面的輸出:

# kubectl logs dapi-test-pod 
SPECIAL_LEVEL
SPECIAL_TYPE

   注意:

  如果在/etc/config/目錄中有一些文件,他們將被刪除

  這里ls顯示的其實是兩個文件名稱

  可以修改pod-configmap-volume.yaml增加一個sleep這樣啟動Pod就不會運行完馬上退出

# cat pod-configmap-volume.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: busybox
      command: [ "/bin/sh", "-c", "ls /etc/config/ && sleep 3600" ]
      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 exec -it dapi-test-pod sh
# cd /etc/config/
# ls -l
total 0
lrwxrwxrwx    1 root     root            20 Mar 18 09:09 SPECIAL_LEVEL -> ..data/SPECIAL_LEVEL
lrwxrwxrwx    1 root     root            19 Mar 18 09:09 SPECIAL_TYPE -> ..data/SPECIAL_TYPE
#文件內容就是very和charm
# cat SPECIAL_LEVEL 
very
# cat SPECIAL_TYPE 
charm

 

  將 ConfigMap 數據添加到容器中的特定路徑

  使用 path 字段為特定的 ConfigMap 項目指定所需的文件路徑。 在這種情況下, SPECIAL_LEVEL 將安裝在 /etc/config/keys 目錄下的 config-volume 容器中。

# cat pod-configmap-volume-specific-key.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: 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 apply -f pod-configmap-volume-specific-key.yaml

   當 pod 運行時,命令 cat /etc/config/keys 產生以下輸出

# kubectl logs dapi-test-pod
very

   為什么輸出是very 修改yaml文件注釋

# cat pod-configmap-volume-specific-key.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: busybox
      #增加sleep防止運行完以后Pod處於compled狀態
      command: [ "/bin/sh","-c","cat /etc/config/keys && sleep 3600 " ]
      volumeMounts:
      #掛載對應的名稱是volumes對應的config-volume
      - name: config-volume
        #掛載的目錄是容器內目錄/etc/config
        #以keys名掛載以后的文件名稱是/etc/config/keys
        mountPath: /etc/config
  volumes:
    - name: config-volume
      configMap:
        name: special-config
        items:
        #取ConfigMap的key為SPECIAL_LEVE的值是very
        - key: SPECIAL_LEVEL
          #在volumeMount是掛載的名稱是keys
          path: keys
  restartPolicy: Never

   創建Pod

# kubectl apply -f pod-configmap-volume-specific-key.yaml 
pod/dapi-test-pod created

   登錄Pod內部查看

kubectl exec -it dapi-test-pod sh
cd /etc/config/
ls
keys
cat keys 
very

 

  了解ConfigMap和Pod

  ConfigMap API 資源將配置數據存儲為鍵值對。數據可以在 Pod 中使用,也可以提供系統組件(如控制器)的配置。ConfigMap 與 Secrets類似,但是提供了一種使用不包含敏感信息的字符串的方法。用戶和系統組件都可以在 ConfigMap 中存儲配置數據。

  ConfigMap 應該引用屬性文件,而不是替換它們。可以將 ConfigMap 表示為類似於 Linux /etc 目錄及其內容的東西。例如,如果您從 ConfigMap 創建Kubernetes Volume,則 ConfigMap 中的每個數據項都由該容器中的單個文件表示。

  ConfigMap 的 data 字段包含配置數據。如下例所示,它可以很簡單 – 就像使用 --from-literal – 定義的單個屬性一樣,也可以很復雜 – 例如使用 --from-file 定義的配置文件或 JSON blob。

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

   限制規定

  在 Pod 規范中引用它之前,必須先創建一個 ConfigMap(除非將 ConfigMap 標記為”可選”)。如果引用的 ConfigMap 不存在,則 Pod 將不會啟動。同樣,對 ConfigMap 中不存在的鍵的引用將阻止容器啟動。

  如果您使用 envFrom 從 ConfigMap 中定義環境變量,那么將忽略被認為無效的鍵。可以啟動 Pod,但無效名稱將記錄在事件日志中(InvalidVariableNames)。日志消息列出了每個跳過的鍵。例如:

kubectl get events

   如果沒有key將事件中出現類似以下提示

15m         Warning   Failed        pod/dapi-test-pod   Error: couldn't find key log_level in ConfigMap default/special-config

  ConfigMap 只能由位於相同命令空間中的 Pod 引用。

  Kubelet 不支持將 ConfigMap 用於未在 API 服務器上找到的 Pod。這包括通過 Kubelet 的 --manifest-url 參數,--config 參數或者 Kubelet REST API 創建的容器。

  使用ConfigMap來配置Redis

  目標

  創建一個包含以下內容的kustomization.yaml 文件

  • 一個ConfigMap生成器
  • 一個使用ConfigMap的Pod資源配置

  使用kubectl apply -k ./應用整個路徑的配置

  驗證配置是否正確

  使用kustomization.yaml Kubernetes版本必須1.14及以上 查看版本信息使用命令

kubectl version

   按照以下步驟,可以使用ConfigMap中的數據類配置Redis緩存

curl -OL https://k8s.io/examples/pods/config/redis-config
#文件內容如下
maxmemory 2mb
maxmemory-policy allkeys-lru

cat <<EOF >./kustomization.yaml
configMapGenerator:
- name: example-redis-config
  files:
  - redis-config
EOF

   將Pod的資源配置添加到kustomization.yaml 文件中

# cat redis-pod.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: redis
spec:
  containers:
  - name: redis
    image: redis:5.0.4
    command:
      - redis-server
      - "/redis-master/redis.conf"
    env:
    - name: MASTER
      value: "true"
    ports:
    - containerPort: 6379
    resources:
      limits:
        cpu: "0.1"
    volumeMounts:
    - mountPath: /redis-master-data
      name: data
    - mountPath: /redis-master
      name: config
  volumes:
    - name: data
      emptyDir: {}
    - name: config
      configMap:
        name: example-redis-config
        items:
        - key: redis-config
          path: redis.conf

 

curl -OL https://raw.githubusercontent.com/kubernetes/website/master/content/en/examples/pods/config/redis-pod.yaml

   在kustomization.yaml追加

cat <<EOF >>./kustomization.yaml
resources:
- redis-pod.yaml
EOF

   此時完整的kustomization.yaml內容如下

# cat kustomization.yaml 
configMapGenerator:
- name: example-redis-config
  files:
  - redis-config
resources:
- redis-pod.yaml

   應用整個 kustomization 文件夾以創建 ConfigMap 和 Pod 對象:

  首先應用文件redis-config文件創建ConfigMap,然后使用文件redis-pod.yaml創建Pod

# kubectl apply -k .
configmap/example-redis-config-dgh9dg555m created
pod/redis created

   使用以下命令檢查創建的對象

# kubectl get -k .
NAME                                        DATA   AGE
configmap/example-redis-config-dgh9dg555m   1      36s

NAME        READY   STATUS    RESTARTS   AGE
pod/redis   1/1     Running   0          36s

   在示例中,配置卷掛載在/redis-master下。它使用path將redis-config的key添加到名為redis.conf的文件中。因此,redis配置的文件路徑為/redis-master/redis.conf。 這是鏡像將在其中查找 redis master 的配置文件的位置。

  使用kubectl exec進入Pod並運行redis-cli工具來驗證配置已正確應用

# kubectl exec -it redis redis-cli
127.0.0.1:6379> CONFIG GET maxmemory
1) "maxmemory"
2) "2097152"
127.0.0.1:6379> CONFIG GET maxmemory-policy
1) "maxmemory-policy"
2) "allkeys-lru"

   PS:redis使用命令CONFIG GET 參數獲取對應配置值 這里最大內存設置的是2mb換算成byte就是2097152即2*1024*1024

  刪除創建的Pod

kubectl delete pod redis

   不使用kustomization.yaml創建一遍

  刪除剛剛創建的ConfigMap和Pod

kubectl delete pod redis
kubectl delete configmap example-redis-config-dgh9dg555m

   使用文件創建ConfigMap

#創建ConfigMap名為  example-redis-config
kubectl create configmap example-redis-config --from-file=redis-config 
configmap/example-redis-config created

   查看剛剛創建的ConfigMap

#key為文件名redis-config內容及文件內部內容
kubectl get configmap  example-redis-config -o yaml
apiVersion: v1
data:
  redis-config: |
    maxmemory 2mb
    maxmemory-policy allkeys-lru
kind: ConfigMap
metadata:
  creationTimestamp: "2020-03-18T06:06:54Z"
  name: example-redis-config
  namespace: default
  resourceVersion: "735256"
  selfLink: /api/v1/namespaces/default/configmaps/example-redis-config
  uid: 35f4baf9-b786-450f-a22c-768fa75a2d08

   創建Pod

# cat redis-pod.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: redis
spec:
  containers:
  - name: redis
    image: redis:5.0.4
    command:
      - redis-server
      - "/redis-master/redis.conf"
    env:
    - name: MASTER
      value: "true"
    ports:
    - containerPort: 6379
    resources:
      limits:
        cpu: "0.1"
    volumeMounts:
    - mountPath: /redis-master-data
      name: data
    #掛載配置文件從ConfigMap掛載目錄為容器目錄/redis-master最終掛載的文件為/redis-master/redis.conf
    #內容即文件redis-config內內容
    - mountPath: /redis-master
      name: config
  volumes:
    - name: data
      emptyDir: {}
    - name: config
      configMap:
        name: example-redis-config
        items:
        - key: redis-config
          path: redis.conf

   

# kubectl apply -f redis-pod.yaml 
pod/redis created

   可以使用以上redis-cli驗證

  也可以登錄Pod查看配置文件內容是否一致

# kubectl exec -it redis bash
# cat /redis-master/redis.conf 
maxmemory 2mb
maxmemory-policy allkeys-lru

   



  

  

 

  

   

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM