如何使用Kubernetes的configmap经过环境变量注入到pod里

在Kubernetes官网里,有这样一篇文章,提到了Kubernetes里的一个最佳实践就是把应用代码同配置信息分开,一种方式就是使用Kubernetes 1.2里引入的configmap概念。git

https://kubernetes.io/blog/2016/04/configuration-management-with-containers/github

configmap实际上就是一系列键值对,存储于etcd里。etcd的官网有这样一句话:docker

etcd is a distributed key-value store designed to reliably and quickly preserve and provide access to critical data.shell

https://github.com/etcd-io/etcd/blob/master/Documentation/docs.mdapi

etcd是一个高性能的分布式键值对存储库,用于存储和访问关键数据。分布式

使用下面的命令行建立一个Kubernetes config map:ide

kubectl create configmap test-config --from-literal=test.type=unit --from-literal=test.exec=always性能

建立一个名为test-config的键值对,key为test.type,值为unit,key为test.exec, 值为always。ui

下面我打算建立一个pod,消费这个名为test-config的configmap。命令行

建立一个内容以下的yaml文件:

apiVersion: v1

kind: Pod

metadata:

name: test-configmap

spec:

containers:

- name: test-container

image: alpine:3.8

command: [ "/bin/sh", "-c", "env" ]

env:

- name: TEST_TYPE

valueFrom:

configMapKeyRef:

name: test-config

key: test.type

- name: TEST_EXEC

valueFrom:

configMapKeyRef:

name: test-config

key: test.exec

restartPolicy: Never

这个yaml文件定义的pod基于docker镜像alpine,执行shell命令/bin/sh -c env查看环境变量。

在env区域,我给该pod注入一个名为TEST_TYPE的环境变量,值从configMap键值对的键名称为test.type的值中取。

kubectl create -f 建立这个pod:

使用命令kubectl logs test-configmap查看这个pod运行生成的日志,发现输出的环境变量列表中,出现了TEST_TYPE=unit,这个TEST_TYPE是我在yaml文件里注入的环境变量名称,而unit就来自configmap里test-config的值unit。

要获取更多Jerry的原创文章,请关注公众号"汪子熙":

相关文章
相关标签/搜索