配置管理系列(二) ConfigMap

一、简介

  从ConfigMap名称也能知晓它是和配置相关的功能,ConfigMap 是一个 API 对象, 给我们提供了向容器中注入配置信息的机制,可以被用来保存单个属性,也可以用来保存整个配置文件或者JSON二进制大对象。它是存储不加密的数据到etcd,然后也是和Secret相同,可以常使用下面两种方式:

  • 以变量形式挂载到Pod中
  • 以数据卷(volume)形式挂载到Pod中

二、使用

 1、以数据卷形式挂载到Pod中

  • 创建ConfigMap

比如从一个redis的配置文件创建ConfigMap:

redis.properties

redis.host=127.0.0.1
redis.port=6379
redis.password=123456

创建ConfigMap

# 根据配置文件创建ConfigMap
[root@k8smaster ~]# kubectl create configmap redis-config --from-file=redis.properties 
configmap/redis-config created

# 查看ConfigMap,可简写cm
[root@k8smaster ~]# kubectl get cm
NAME           DATA   AGE
redis-config   1      13s

# 查看创建的ConfigMap redis-config详细信息
[root@k8smaster ~]# kubectl describe cm redis-config
Name:         redis-config
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
redis.properties:
----
redis.host=127.0.0.1
redis.port=6379
redis.password=123456


Events:  <none>
  • 挂载到Pod中

config_volume.yaml

apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
    - name: busybox
      image: busybox
      command: [ "/bin/sh","-c","cat /etc/config/redis.properties" ]
      volumeMounts:
      - name: config-volume
        mountPath: /etc/config
  volumes:
    - name: config-volume
      configMap:
        name: redis-config
  restartPolicy: Never

执行:

[root@k8smaster ~]# kubectl apply -f config_volume.yaml 
pod/mypod created

查看结果:

[root@k8smaster ~]# kubectl logs mypod
redis.host=127.0.0.1
redis.port=6379
redis.password=123456

2、以变量形式挂载到Pod中

  • 创建ConfigMap

myconfigmap.yaml

apiVersion: v1
kind: ConfigMap
metadata:
  name: myconfig
  namespace: default
data:
  special.level: hello
  special.type: world

声明变量信息,然后创建ConfigMap,最后执行,查看:

[root@k8smaster ~]# kubectl apply -f myconfigmap.yaml 
configmap/myconfig created

[root@k8smaster ~]# kubectl get cm
NAME           DATA   AGE
myconfig       2      20s
  • 使用ConfigMap

configmapvar.yaml

apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
    - name: busybox
      image: busybox
      command: [ "/bin/sh", "-c", "echo $(LEVEL) $(TYPE)" ]
      env:
        - name: LEVEL
          valueFrom:
            configMapKeyRef:
              name: myconfig
              key: special.level
        - name: TYPE
          valueFrom:
            configMapKeyRef:
              name: myconfig
              key: special.type
  restartPolicy: Never

执行并且查看:

[root@k8smaster ~]# kubectl apply -f configmapvar.yaml 
pod/mypod created
[root@k8smaster ~]# kubectl logs mypod

 

配置管理系列(二) ConfigMap

上一篇:Android照片墙完整版,的完美结合LruCache和DiskLruCache


下一篇:信号和中断