目录
一,概念:
configmap是一种api对象,用来将非加密数据保存到键值对中,可以用作环境变量。configmap可以将环境变量配置信息和容器镜像解耦,便于应用配置的修改,如果需要存储加密信息时可以使用secret对象
二,创建,
1,通过命令进行创建configmap
可以使用kubectl create configmap从文件,目录或者key-value字符等创建configmap
通过文件创建:
echo hello > test1.txt
echo world > test2.txt
kubectl create configmap my-config --from-file=key1=test1.txt --from-file=key2=test2.txt
kubectl describe configmap my-config
2,通过文件夹创建configmap
mkdir config
echo hello1 > config/test1
echo world1 > config/test1
kubectl create configmap dir-config --from-file=config/
kubectl describe configmap literal-config
3,通过键值对configmap
kubectl create configmap literal-config --from-literal=key1=hello2 --from-literal=key2=world2
kubectl describe configmap literal-config
4,通过yaml文件创建
vim config.yaml
apiVersion: v1
kind: configMap
metadata:
name: my-config
data:
key1: hello3
key2: world3
kubectl create -f config.yamlkubectl describe configmap-config
二,pod的使用方式:
1,将configMap中的数据设置为容器的环境变量
2,及那个configMap中的数据设置为命令行数
3,使用volume将configmap作为文件或目录挂载。
4,编写代码载pod中运行,使用kubernetesAPI来读取configmap
三,基于yaml文件的基础之上:
配置到容器的环境变量:
apiVersion: v1
kind: Pod
metadata:
name: test-pod-configmap
spec:
containers:
- name: test-busybox
image: busybox
imagePullPolicy: IfNotPresent
args:
- sleep
- "86400"
env:
- name: KEY1
valueFrom:
configMapKeyRef:
name: my-config
key: key1
- name: KEY2
valueFrom:
configMapKeyRef:
name: my-config
key: key2kubectl create -f test-pod-configmap.yaml
查看效果
kubectl exec -it test-pod-configmap -- /bin/sh
env | grep KEY将configmap挂载到容器中:
apiVersion: v1
kind: Pod
metadata:
name: test-pod-projected-configmap-volume
spec:
containers:
- name: test-pod-busybox
image: busybox
imagePullPolicy: IfNotPresent
args:
- sleep
- "86400"
volumeMounts:
- name: config-volume
mountPath: "/projected-volume"
readOnly: true
volumes:
- name: config-volume
projected:
sources:
- configMap:
name: my-config
kubectl create -f test-pod-projected-configmap-volume.yaml
查看效果
kubectl exec -it test-pod-projected-configmap-volume -- /bin/sh
cd projected-volume
ls
cat -n key1
cat -n key2通过volume挂载和环境变量的区别:通过volume挂载到容器内部时,当该configmap的值发生变化时,容器内部具备自动更新的能力,但是通过环境变量设置到容器内部该值不具备自动更新的能力。
注意: configmap必须子啊pod使用之前创建
使用envFrom时,将会自动忽略无效的键
pod只能使用同一个命名空间的configmap