configmap 基础概念就不在此赘述了。当 configmap 中变量值比较长或者很复杂时,此时再采用环境变量的方式将其暴露给 pod 就显得很不合适了,在这个场景下可以选择将复杂的字段做成文件,再暴露给 pod 使用。
创建 configmap
# configmap-multikeys.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: special-config
namespace: default
data:
SPECIAL_LEVEL: very
SPECIAL_TYPE: charm
EXTERNAL_RUNTIME_CONFIG_PATH: /etc/config/runtimes.yaml
EXTERNAL_RUNTIME_CONFIG: |
externalruntimes:
list:
- framework: "tensorflow"
version: "1.11"
device: "CPU"
image: "tensorflow:1.11.0-py36-cpu.47"
- framework: "tensorflow"
version: "1.11"
device: "GPU"
image: "tensorflow:1.11.0-py36-cu90.47"
EXTERNAL_RUNTIME_CONFIG
字段的结构比较复杂,可将该字段映射成文件,再 “mount” 到 pod 中。
创建 configmap
kubectl apply -f configmap-multikeys.yaml
查看 configmap
kubectl describe configmaps special-config
Name: special-config
Namespace: default
Labels: <none>
Annotations:
Data
====
EXTERNAL_RUNTIME_CONFIG:
----
externalruntimes:
list:
- framework: "tensorflow"
version: "1.11"
device: "CPU"
image: "tensorflow:1.11.0-py36-cpu.47"
- framework: "tensorflow"
version: "1.11"
device: "GPU"
image: "tensorflow:1.11.0-py36-cu90.47"
EXTERNAL_RUNTIME_CONFIG_PATH:
----
/etc/config/runtimes.yaml
SPECIAL_LEVEL:
----
very
SPECIAL_TYPE:
----
charm
Events: <none>
创建 pod
# pod-configmap-volume-specific-key.yaml
apiVersion: v1
kind: Pod
metadata:
name: dapi-test-pod
spec:
containers:
- name: test-container
image: busybox:1.28
command: ["sleep", "3600"]
env:
- name: EXTERNAL_RUNTIME_CONFIG_PATH
valueFrom:
configMapKeyRef:
name: special-config
key: EXTERNAL_RUNTIME_CONFIG_PATH
volumeMounts:
- name: config-volume
mountPath: /etc/config
volumes:
- name: config-volume
configMap:
name: special-config
items:
- key: EXTERNAL_RUNTIME_CONFIG
path: runtimes.yaml
创建 pod
kubetcl create -f pod-configmap-volume-specific-key.yaml
这块的思路很容易理解:首先,将 special-config 中的 EXTERNAL_RUNTIME_CONFIG 字段的值做成文件,文件名字叫 runtimes.yaml,并存放在名叫 config-volume 的 volume 中。更直率的说就是创建一个 volume 里面有个 runtimes.yaml 文件。接着再将 volume 中的 runtimes.yaml 文件放到容器(test-container)的 /etc/config 路径下面。通过前两步的操作,在 test-container 容器中就会有 /etc/config/runtimes.yaml 文件 出现,“将 configmap 中的字段以文件的形式绑定到容器中” 这个目的就算是实现了。更进一步,容器中的应用程序如何才能访问到 runtimes.yaml 文件呢?这会给 test-container 配的环境变量 EXTERNAL_RUNTIME_CONFIG_PATH 就起作用了,它是从 configmap 中拿的,而且它的值正好是 runtimes.yaml 文件在容器中的路径,无论应用程序是哪种语言写的,只要通过获取环境变量就可以访问到runtimes.yaml 文件。
进入容器
kl exec -it dapi-test-pod -- sh
查看 runtimes.yaml 文件
/ # ls /etc/config/
runtimes.yaml
/ # cat /etc/config/runtimes.yaml
externalruntimes:
list:
- framework: "tensorflow"
version: "1.11"
device: "CPU"
image: "tensorflow:1.11.0-py36-cpu.47"
- framework: "tensorflow"
version: "1.11"
device: "GPU"
image: "tensorflow:1.11.0-py36-cu90.47"
查看 EXTERNAL_RUNTIME_CONFIG_PATH 环境变量
/ # env | grep "EXTERNAL"
EXTERNAL_RUNTIME_CONFIG_PATH=/etc/config/runtimes.yaml
/ # echo $EXTERNAL_RUNTIME_CONFIG_PATH
/etc/config/runtimes.yaml