configmap的创建和使用详解
configmap的创建
configmap通过命令行可以有以下几种创建方式
- –from-literal=key=value 指定的健值对
- –from-file=file/diectory 指定的文件或者文件夹。从文件创建时如果不指定key,则文件名为默认的key,同时从文件创建也可以指定key;从文件夹创建时,不能遍历文件夹中的文件
- –from-env-file=file的环境变量文件,环境变量文件内容为每行的key=value
–from-literal=key=value 指定的健值对
kubectl create cm cm-1 --from-literal=key1=value1 --from-literal=key2=value2
查看创建的cm
–from-file=file/diectory 指定的文件或者文件夹
从文件创建:
kubectl create cm cm-2 --from-file=test-cm=test1 --from-file=test2
查看创建的cm
从文件创建cm,不指定key时,文件名为默认的key,文件内容为value值。
从文件夹创建
文件夹下的所有文件名为key,文件内容为value
–from-env-file=file的环境变量文件
会将env文件中的健值对全部放入cm中
configmap的使用
configmap主要有两种使用场景
- 作为环境变量注入pod
- 作为volume挂载文件给pod,一般挂载一些配置文件
作为环境变量注入pod
- cm全部注入pod环境变量
apiVersion: v1
kind: Pod
metadata:
name: pod-configmap
spec:
containers:
- name: nginx
image: nginx
envFrom:
- configMapRef:
name: cm-4
以上这一整个cm中的健值对全部注入pod的环境变量中
- 指定cm中相应的key,给相应pod注入环境变量
apiVersion: v1
kind: Pod
metadata:
name: pod-configmap-single
spec:
containers:
- name: nginx
image: nginx
env:
- name: test
valueFrom:
configMapKeyRef:
name: cka-test
key: key1
- 作为volume挂载文件给pod,一般挂载一些配置文件
- 将一整个configmap挂载给pod
apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
containers:
- name: mypod
image: redis
volumeMounts:
- name: foo
mountPath: "/tmp"
readOnly: true
volumes:
- name: foo
configMap:
name: cm-3
进入pod查看
configmap中所有健值对以健名为文件名,健值为内容挂载到了容器
- 指定configmap中的健挂载相应的值给相应pod中文件
方法一:
apiVersion: v1
kind: Pod
metadata:
name: configmap-demo-pod
spec:
containers:
- name: demo
image: alpine
command: ["sleep", "3600"]
volumeMounts:
- name: config
mountPath: "/config"
readOnly: true
volumes:
- name: config
configMap:
name: cm-3
items:
- key: "test3"
path: "test/test3"
进入pod查看
这样就将configmap中一个健值挂载给了pod中的相应文件
方法二:
apiVersion: v1
kind: Pod
metadata:
name: configmap-demo-pod
spec:
containers:
- name: demo
image: alpine
command: ["sleep", "3600"]
volumeMounts:
- name: config
mountPath: "/tmp/myfile"
subPath: test3
readOnly: true
volumes:
- name: config
configMap:
name: cm-3
挂载的时候指定subpath,subpath为cm中的指定的健
两种方法中,方法一可以实现configmap的热更新,方法二则不行
总结:
虽然configmap的创建方式有很多种,但是configmap中本质就是健值对,其实我们只需要清楚每一种方式都是怎么生成健值对的;挂载给pod方式也有好几种,我们只需要真正弄清楚挂载到pod中的文件名以及路径怎么取值的即可