kubernetes configmap

创建configmap

1
2
# kubectl  get cm/calico-config -n kube-system  -o yaml
# kubectl get cm/kube-flannel-cfg -n kube-system -o yaml
1
2
3
4
5
kubectl  create ns  cm-ns
kubectl create cm -h
kubectl create cm filebeat-cfg -n cm-ns \
--from-literal=redis_host="redis.default.svc.cluster.local" \
--from-literal=log_level="Info"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
kubectl get cm/filebeat-cfg -n cm-ns -o yaml
apiVersion: v1
data:
log_level: Info
redis_host: redis.default.svc.cluster.local
kind: ConfigMap
metadata:
creationTimestamp: "2021-01-11T05:58:23Z"
managedFields:
- apiVersion: v1
fieldsType: FieldsV1
fieldsV1:
f:data:
.: {}
f:log_level: {}
f:redis_host: {}
manager: kubectl-create
operation: Update
time: "2021-01-11T05:58:23Z"
name: filebeat-cfg
namespace: cm-ns
resourceVersion: "573737"
uid: b06442dc-90e6-446b-8a3c-f119f26226d4

启一个pod运用configmap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
root@k8s-m:/data/configmap# cat filebeat-pod.yaml 
apiVersion: v1
kind: Pod
metadata:
name: filebeat-pod
namespace: cm-ns
spec:
containers:
- name: filebeat
image: ikubernetes/filebeat:5.6.5-alpine
env:
- name: REDIS_HOST
valueFrom:
configMapKeyRef:
name: filebeat-cfg # configmap名字
key: redis_host # 定义的键名
- name: LOG_LEVEL
valueFrom:
configMapKeyRef:
name: filebeat-cfg # configmap名字
key: log_level # 定义的键名

root@k8s-m:/data/configmap# kubectl apply -f filebeat-pod.yaml
#pod内部是能查到的定义变量的
root@k8s-m:/data/configmap# kubectl exec -it pods/filebeat-pod -n cm-ns -- env | grep REDIS_HOST
REDIS_HOST=redis.default.svc.cluster.local

定义2个数据文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
root@k8s-m:/data/configmap/nginx# cat server1.conf 
server {
server_name www.first.com;
listen 80;
location / {
root "/html/first";
}

}
root@k8s-m:/data/configmap/nginx# cat server2.conf
server {
server_name www.second.com;
listen 80;
location / {
root "/html/second";
}

}

创建nginx-cfg

1
kubectl  create cm nginx-cfg --from-file=server1.conf  --from-file=server-sec.conf=server2.conf -n cm-ns

pod使用nginx-cfg

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
[root@k8smaster nginx]# cat nginx-pod.yaml 
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
namespace: cm-ns
spec:
containers:
- name: nginx-t
image: nginx
volumeMounts:
- name: config-vol
mountPath: /etc/nginx/conf.d/
volumes:
- name: config-vol
configMap:
name: nginx-cfg
items:
- key: server1.conf # 定义configmap时的key
path: server-first.conf # pod内部的文件名
- key: server-sec.conf # 定义configmap时的key
path: server-second.conf # pod内部的文件名

[root@k8smaster nginx]# kubectl apply -f nginx-pod.yaml
[root@k8smaster nginx]# kubectl exec -it pods/nginx-pod -n cm-ns -- ls /etc/nginx/conf.d
server-first.conf server-second.conf

kubectl edit cm/nginx-cfg -n cm-ns # 修改能在60s生效

总结

configmap也是一种存储卷,特殊的存储卷,用于保存pod内程序变量配置或文件等