k8s ConfigMap
ConfigMap 的创建和使用方式与Secret非常类似,主要不同的是数据以明文的形式存放。
ConfigMap创建
(1) 通过 --from-literal
kubectl create configmap myconfigmap -from-literal=config1=xxxx --from-literal=config2=yyy
(2) 通过 --from-file
echo -n xxx > ./config1 echo -n yyy > ./config2 kubectl create configmap myconfigmap --from-file=./config1 --from-file=./config2
(3) 通过 --from-file, 文件env.txt 每行Key=Value 对应一个信息条目
cat << EOF > env.txt config1=xxx config2=yyy EOF kubectl create configmap myconfigmap --from-env-file=env.txt
(4) 通过YAML 配置文件, 文件中的数据直接以明文输入
apiVersion: v1
kind: ConfigMap
metadata:
name: myconfigmap
data:
config1: xxx
config2: yyy
与Secret一样,Pod 也可以通过Volume 或者环境变量的方式使用ConfigMap
Volume 方式

apiVersion: v1 kind: Pod metadata: name: mypod-configmap spec: containers: - name: mypod image: centos args: - /bin/sh - -c - sleep 10; touch /tmp/myhealthy; sleep 30000 volumeMounts: - name: foo mountPath: "/etc/foo" readOnly: true volumes: - name: foo configMap: name: myconfigmp
大多数情况下,配置信息都以文件形式提供,所以在创建ConfigMap 时通常采用 --from-file 或YAML方式,读取ConfigMap时通常采用Volume 方式。比如给Pod传递如何记录日志的配置文件
采用 --from-file 形式将其保存在文件logging.conf
class: loggging.handlers.RottingFileHandler formatter: precise level: INFO filename: %hostname-%timestamp.log kubectl create configmap myconfigmap --from-file=./logging.conf
YAML 配置文件
apiVersion: v1 kind: ConfigMap metadata: name: myconfigmap data: logging.conf: | class: loggging.handlers.RottingFileHandler formatter: precise level: INFO filename: %hostname-%timestamp.log
创建 ConfigMap
kubectl apply -f myconfigmap.yml
查看 ConfigMap
kubectl get configmap myconfigmap
在Pod中使用ConfigMap
apiVersion: v1 kind: Pod metadata: name: mypod-map spec: containers: - name: mypod image: centos args: - /bin/sh - -c - sleep 10; touch /tmp/healthy; sleep 30000 volumeMounts: - name: foo mountPath: "/etc/" volumes: - name: foo configMap: name: myconfigmap items: - key: logging.conf path: myapp/logging.conf
在volume 中指定存放配置信息的文件相对路径为 myapp/logging.conf
将volume mount 到容器的 /etc/目录
创建Pod并读取配置信息
kubectl apply -f mypod.yaml
配置信息已经保存到/etc/myapp/logging.conf文件中。
环境变量方式

piVersion: v1 kind: Pod metadata: name: mypod-2 spec: containers: - name: mypod image: centos args: - /bin/sh - -c - sleep 10; touch /tmp/healthy; sleep 30000 env: - name: CONFIG_1 valueFrom: configMapKeyRef: name: myconfigmap key: config1 - name: CONFIG_2 valueFrom: configMapKeyRef: name: myconfigmap key: config2