一、Configmap
1.1 关于Configmap
Configmap 是k8s中的资源对象,用于保存非机密性的配置的,数据可以用key/value键值对的形式保存,也可以使用文件的形式保存。
k8s中的pod(服务)都有自己的配置文件,如果需要扩容时,为保证服务的一致性,可以将Configmap做成volume,并挂载到新扩容的服务上。
1.2 Configmap 创建方法
1.2.1 命令行方式创建
命令行中指定configmap参数创建,通过使用--from-literal 指定参数
命令解释:
kubectl create configmap nginx --from-literal=nginx-port=80
create configmap (创建), nginx (为创建的名称),--from-literal=(定义key)=(key的值)
1.2.2 通过文件方式创建
通过指定的文件创建一个Configmap,--from-file=(文件名称)
1.2.3 指定目录创建
可以将目录下的文件都做成configmap
1.2.4 通过yaml文件创建
如下(1.2.4.1~~1.2.4.2)两种方式使用环境变量的方式将configmap注入到pod容器中
2.4.3使用volume卷方式进行挂载到pod容器内。
使用环境变量方式进行
1.2.4.1 使用configMapKeyRef
通过环境变量引入:使用env字段下的configMapKeyRef编写configmap资源清单的yaml文件来创建
通过如下命令查看 configmap的字段信息: kubectl explain cm (configmap可缩写为cm) 如下图所示:
1.2.4.2 使用envfrom
使用volume方式进行
1.2.4.3 使用volume 方式创建
上方两种方式是使用环境变量的方式将configmap注入到容器中,如下将使用存储卷的方式将configmap做成volume,然后将其挂到pod容器中进行使用。
1.3 Configmap 热更新
当configmap文件已经做成了volume并挂载到了pod容器中之后,该configmap文件发生了更新,pod中也需要一并实现更新
如上方2.4.3标题内容所示,该configmap文件已经挂载到了pod-03中,此时更新configmap,查看已挂载过的pod是否同步更新
PS:上方1.2.4.1~~1.2.4.2使用变量方式挂载configmap到pod中的方式,在更新了configmap之后,pod中是不会发生改变的。
二、Secret
2.1 关于Secret
与Configmap不同的是,Configmap是管理存放明文数据的,如配置文件,而对于一些敏感数据,如密码、私钥等数据保存时,需要使用到Secret
Secret解决了密码、token、秘钥等敏感数据的配置问题,而不需要把这些敏感数据暴露到镜像或者Pod Spec中。Secret可以以Volume或者环境变量的方式使用。
想要使用Secret,pod需要引用Secret,pod有两种方式使用Secret:
1、作为volume中的文件被挂载到pod中的一个或者多个容器里。
2、当kubelet为pod拉取镜像时使用。
2.2 Secret 可用参数及类型
secret可选参数有三种:
1、generic: 通用类型,通常用于存储密码数据。
2、tls: 此类型仅用于存储私钥和证书。
3、docker-registry: 若要保存docker仓库的认证信息的话,就必须使用此种类型来创建。
Secret类型也可分为三种:
1、Service Account:用于被 serviceaccount 引用。serviceaccout 创建时 Kubernetes 会默认创建对应的 secret。Pod 如果使用了 serviceaccount,对应的 secret 会自动挂载到 Pod 的 /run/secrets/kubernetes.io/serviceaccount 目录中。
2、Opaque:base64编码格式的Secret,用来存储密码、秘钥等。可以通过base64 --decode解码获得原始数据,因此安全性弱
3、kubernetes.io/dockerconfigjson:用来存储私有docker registry的认证信息。
可使用如下命令进行查看secret的字段信息:如下图所示
kubectl explain secret
2.3 使用Secret
2.3.1 环境变量方式
创建一个pod并通过使用环境变量的方式引用Secret至pod容器内
2.3.2 使用volume方式进行
2.3.3 测试热更新
测试更新secret文本的值,已挂载进pod容器中的值是否会发生改变