字符串创建
$ kubectl create configmap special-config --from-literal=special.how=very --from-literal=special.type=charm
configmap "special-config" created
$ kubectl get configmap special-config -o go-template='{{.data}}'
map[special.how:very]
指定键为special.how值为very
目录创建
[root@k8s-master ~]# ls configmap/
game.properties ui.properties
[root@k8s-master ~]# kubectl create configmap all --from-file=./configmap
[root@k8s-master ~]# kubectl describe cm all
Name: all
Namespace: default
Labels: <none>
Annotations: <none>
Data
====
game.properties:
----
enemies=aliens
#键为文件名称,值为文件内容
文件创建
apiVersion: v1
kind: ConfigMap
metadata:
name: special-config
namespace: default
data:
special.how: very
special.type: charm
作用:设置环境变量、设置容器命令行参数以及在 Volume 中直接挂载文件或目录。
设置环境变量
apiVersion: v1
kind: Pod
metadata:
name: 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: special-config #cm名称
key: special.how #引用cm的哪个键
- name: SPECIAL_TYPE_KEY
valueFrom:
configMapKeyRef:
name: special-config
key: special.type
envFrom:
- configMapRef:
name: env-config #另一种设置环境变量的方式,调用这个cm里的值
restartPolicy: Never
挂载
apiVersion: v1
kind: Pod
metadata:
name: vol-test-pod
spec:
containers:
- name: test-container
image: gcr.io/google_containers/busybox
command: ["/bin/sh", "-c", "cat /etc/config/special.how"]
volumeMounts:
- name: config-volume
mountPath: /etc/config/nginx.conf
subPath: nginx.conf #只挂载单个文件
volumes:
- name: config-volume
configMap:
name: special-config
restartPolicy: Never
#key值会做为文件名称,键为文件内容
将创建的 ConfigMap 中 special.how 这个 key 挂载到 / etc/config 目录下的一个相对路径 / keys/special.level。如果存在同名文件,直接覆盖。其他的 key 不挂载
apiVersion: v1
kind: Pod
metadata:
name: dapi-test-pod
spec:
containers:
- name: test-container
image: gcr.io/google_containers/busybox
command: ["/bin/sh","-c","cat /etc/config/keys/special.level"]
volumeMounts:
- name: config-volume
mountPath: /etc/config
subPath: special.how #使用subpath对挂载的目录不覆盖
volumes:
- name: config-volume
configMap:
name: special-config
items:
- key: special.how
path: keys/special.level
restartPolicy: Never
更新 ConfigMap 后:使用该 ConfigMap 挂载的 Env 不会同步更新使用该 ConfigMap 挂载的 Volume 中的数据需要一段时间(实测大概10秒)才能同步更新