一、Secret1.1概念

Secret 是用来保存密码、token、密钥等敏感数据的 k8s 资源,这类数据虽然也可以存放在 Pod 或者镜像中,但是放在 Secret 中是为了更方便的控制如何使用数据,并减少暴露的风险。

1.2Secret 三种类型

●kubernetes.io/service-account-token:由 Kubernetes 自动创建,用来访问 APIServer 的 Secret,Pod 会默认使用这个 Secret 与 APIServer 通信, 并且会自动挂载到 Pod 的 /run/secrets/kubernetes.io/serviceaccount 目录中;
●Opaque :base64 编码格式的 Secret,用来存储用户自定义的密码、密钥等,默认的 Secret 类型;
●kubernetes.io/dockerconfigjson :用来存储私有 docker registry 的认证信息。

1.3Pod 有 3 种方式来使用 secret

Pod 需要先引用才能使用某个 secret:

●作为挂载到一个或多个容器上的卷 中的文件。
●作为容器的环境变量。
●由 kubelet 在为 Pod 拉取镜像时使用。

应用场景:凭据官网:https://kubernetes.io/docs/concepts/configuration/secret/

//创建 Secret

1、用kubectl create secret命令创建Secret

echo -n 'zhangsan' > username.txtecho -n 'abc1234' > password.txtkubectl create secret generic mysecret --from-file=username.txt --from-file=password.txtkubectl get secretsNAME                  TYPE                                  DATA   AGEdefault-token-8pqp6   kubernetes.io/service-account-token   3      3d1hmysecret              Opaque                                2      51skubectl describe secret mysecretName:         mysecretNamespace:    defaultLabels:       Annotations:  Type:  OpaqueData====password.txt:  7 bytesusername.txt:  8 bytes

//get或describe指令都不会展示secret的实际内容,这是出于对数据的保护的考虑

2、内容用 base64 编码,创建Secret

echo -n zhangsan | base64emhhbmdzYW4K=echo -n abc1234 | base64YWJjMTIzNAo==vim secret.yamlapiVersion: v1kind: Secretmetadata:  name: mysecret1type: Opaquedata:  username: emhhbmdzYW4K=  password: YWJjMTIzNAo==kubectl create -f secret.yaml kubectl get secretsNAME                  TYPE                                  DATA   AGEdefault-token-8pqp6   kubernetes.io/service-account-token   3      3d1hmysecret              Opaque                                2      43mmysecret1             Opaque                                2      6skubectl get secret mysecret1 -o yamlapiVersion: v1data:  password: YWJjMTIzNAo==  username: emhhbmdzYW4K=kind: Secretmetadata:  creationTimestamp: 2021-05-24T09:11:18Z  name: mysecret1  namespace: default  resourceVersion: "45641"  selfLink: /api/v1/namespaces/default/secrets/mysecret1  uid: fffb7902-bc6f-11eb-acba-000c29d88bbatype: Opaque

//使用方式

1、将 Secret 挂载到 Volume 中,以 Volume 的形式挂载到 Pod 的某个目录下

vim secret-test.yamlapiVersion: v1kind: Podmetadata:  name: mypodspec:  containers:  - name: nginx    image: nginx    volumeMounts:    - name: secrets      mountPath: "/etc/secrets"      readOnly: true  volumes:  - name: secrets    secret:      secretName: mysecretkubectl create -f secret-test.yamlkubectl get podsNAME         READY   STATUS    RESTARTS   AGEseret-test   1/1     Running   0          16skubectl exec -it seret-test bash # cd /etc/secrets/ # lspassword.txt  username.txt # vi password.txt  # vi username.txt

在使用kubectl exec -it seret-test bash命令进入容器使用vim命令时会出现如下错误

解决方法:

这个时候就需要安装vim,可是当你敲apt-get install vim命令时,提示:

然后再输入apt-get update 进行更新,更新后再次执行apt-get instal vim 得以成功。

2、将 Secret 导出到环境变量中

vim secret-test1.yamlapiVersion: v1kind: Podmetadata:  name: mypod1spec:  containers:  - name: nginx    image: nginx    env:      - name: TEST_USER        valueFrom:          secretKeyRef:            name: mysecret1            key: username      - name: TEST_PASSWORD        valueFrom:          secretKeyRef:            name: mysecret1            key: passwordkubectl apply -f secret-test1.yaml kubectl get podsNAME         READY   STATUS    RESTARTS   AGEmypod1       1/1     Running   0          77skubectl exec -it mypod bash # echo $TEST_USERzhangsan # echo $TEST_PASSWORDabc1234

二、ConfigMap2.1概念

与Secret类似,区别在于ConfigMap保存的是不需要加密配置的信息。
ConfigMap 功能在 Kubernetes1.2 版本中引入,许多应用程序会从配置文件、命令行参数或环境变量中读取配置信息。ConfigMap API 给我们提供了向容器中注入配置信息的机制,ConfigMap 可以被用来保存单个属性,也可以用来保存整个配置文件或者JSON二进制大对象。
应用场景:应用配置

2.1.1创建 ConfigMap1、使用目录创建

mkdir /opt/configmap/ vim /opt/configmap/game.propertiesenemies=alienslives=3enemies.cheat=trueenemies.cheat.level=noGoodRottensecret.code.passphrase=UUDDLRLRBABASsecret.code.allowed=truesecret.code.lives=30 vim /opt/configmap/ui.propertiescolor.good=purplecolor.bad=yellowallow.textmode=truehow.nice.to.look=fairlyNicels /opt/configmap/game.propertiesui.propertieskubectl create configmap game-config --from-file=/opt/configmap/

//–from-file 指定在目录下的所有文件都会被用在 ConfigMap 里面创建一个键值对,键的名字就是文件名,值就是文件的内容

kubectl get cmNAME          DATA   AGEgame-config   2      10skubectl get cm game-config -o yamlapiVersion: v1data:  game.properties: |    enemies=aliens    lives=3    enemies.cheat=true    enemies.cheat.level=noGoodRotten    secret.code.passphrase=UUDDLRLRBABAS    secret.code.allowed=true    secret.code.lives=30  ui.properties: |    color.good=purple    color.bad=yellow    allow.textmode=true    how.nice.to.look=fairlyNicekind: ConfigMapmetadata:  creationTimestamp: 2021-05-25T06:49:18Z  name: game-config  namespace: default  resourceVersion: "87803"  selfLink: /api/v1/namespaces/default/configmaps/game-config  uid: 541b5302-bd25-11eb-acba-000c29d88bba

2、使用文件创建

只要指定为一个文件就可以从单个文件中创建 ConfigMap
–from-file 这个参数可以使用多次,即可以使用两次分别指定上个实例中的那两个配置文件,效果就跟指定整个目录是一样的

kubectl create configmap game-config-2 --from-file=/opt/configmap/game.properties --from-file=/opt/configmap/ui.propertieskubectl get configmaps game-config-2 -o yamlkubectl describe cm game-config-2

3、使用字面值创建

使用文字值创建,利用 –from-literal 参数传递配置信息,该参数可以使用多次,格式如下

kubectl create configmap special-config --from-literal=special.how=very --from-literal=special.type=goodkubectl get configmaps special-config -o yamlapiVersion: v1data:  special.how: very                    #key-value 结构  special.type: goodkind: ConfigMapmetadata:  creationTimestamp: 2021-05-25T06:59:37Z  name: special-config  namespace: default  resourceVersion: "88610"  selfLink: /api/v1/namespaces/default/configmaps/special-config  uid: c4f45936-bd26-11eb-acba-000c29d88bbakubectl delete cm --allkubectl delete pod --all

2.1.2Pod 中使用 ConfigMap1、使用 ConfigMap 来替代环境变量

vim env.yamlapiVersion: v1kind: ConfigMapmetadata:  name: special-config  namespace: defaultdata:  special.how: very  special.type: good---apiVersion: v1kind: ConfigMapmetadata:  name: env-config  namespace: defaultdata:  log_level: INFOkubectl create -f env.yaml kubectl get cmNAME             DATA   AGEenv-config       1      6sspecial-config   2      6s

//Pod的创建

vim test-pod.yamlapiVersion: v1kind: Podmetadata:  name: test-podspec:  containers:  - name: busybox    image: busybox:1.28.4    command: [ "/bin/sh", "-c", "env" ]    env:      - name: SPECIAL_HOW_KEY        valueFrom:          configMapKeyRef:            name: special-config            key: special.how      - name: SPECIAL_TYPE_KEY        valueFrom:          configMapKeyRef:            name: special-config            key: special.type    envFrom:      - configMapRef:          name: env-config  restartPolicy: Neverkubectl create -f test-pod.yamlkubectl get podsNAME         READY   STATUS      RESTARTS   AGEpod-test     0/1     Completed   0          33s

kubectl logs pod-testKUBERNETES_SERVICE_PORT=443KUBERNETES_PORT=tcp://10.0.0.1:443HOSTNAME=pod-testSHLVL=1SPECIAL_HOW_KEY=very            #赋值变量 SPECIAL_HOW_KEY 的值为 special-config 的 special.how: veryHOME=/rootSPECIAL_TYPE_KEY=good            #赋值变量 SPECIAL_TYPE_KEY 的值为 special-config 的 special.type: goodKUBERNETES_PORT_443_TCP_ADDR=10.0.0.1PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/binKUBERNETES_PORT_443_TCP_PORT=443KUBERNETES_PORT_443_TCP_PROTO=tcplog_level=INFO                    #引入 env-config 的变量 log_level: INFOKUBERNETES_PORT_443_TCP=tcp://10.0.0.1:443KUBERNETES_SERVICE_PORT_HTTPS=443KUBERNETES_SERVICE_HOST=10.0.0.1PWD=/

2、用 ConfigMap 设置命令行参数

vim test-pod2.yamlapiVersion: v1kind: Podmetadata:  name: test-pod2spec:  containers:  - name: busybox    image: busybox:1.28.4    command:     - /bin/sh    - -c    - echo "$(SPECIAL_HOW_KEY) $(SPECIAL_TYPE_KEY)"    env:      - name: SPECIAL_HOW_KEY        valueFrom:          configMapKeyRef:            name: special-config            key: special.how      - name: SPECIAL_TYPE_KEY        valueFrom:          configMapKeyRef:            name: special-config            key: special.type    envFrom:      - configMapRef:          name: env-config  restartPolicy: Neverkubectl create -f test-pod2.yamlkubectl get podsNAME        READY   STATUS      RESTARTS   AGEtest-pod2   0/1     Completed   0          34skubectl logs test-pod2very good

3、通过数据卷插件使用ConfigMap

在数据卷里面使用 ConfigMap,就是将文件填入数据卷,在这个文件中,键就是文件名,键值就是文件内容

vim test-pod3.yamlapiVersion: v1kind: Podmetadata:  name: test-pod3spec:  containers:  - name: busybox    image: busybox:1.28.4    command: [ "/bin/sh", "-c", "sleep 36000" ]    volumeMounts:    - name: config-volume      mountPath: /etc/config  volumes:    - name: config-volume      configMap:        name: special-config  restartPolicy: Neverkubectl create -f test-pod3.yaml kubectl get podsNAME        READY   STATUS      RESTARTS   AGEtest-pod3   1/1     Running     0          5skubectl exec -it test-pod3 sh # cd /etc/config/ # lsspecial.how   special.type # vi special.how  # vi special.type 

2.1.3ConfigMap 的热更新

vim test-pod4.yamlapiVersion: v1kind: ConfigMapmetadata:  name: log-config  namespace: defaultdata:  log_level: INFO---apiVersion: extensions/v1beta1     #因为我的 k8s 版本是 1.16.2,在这个版本中 Deployment 已经从 extensions/v1beta1 弃用kind: Deploymentmetadata:  name: my-nginxspec:  replicas: 1  template:    metadata:      labels:        run: my-nginx    spec:      containers:      - name: my-nginx        image: nginx        ports:        - containerPort: 80        volumeMounts:        - name: config-volume          mountPath: /etc/config      volumes:        - name: config-volume          configMap:            name: log-configkubectl apply -f test-pod5.yamlkubectl get pods NAME                        READY   STATUS    RESTARTS   AGEmy-nginx-76b6489f44-6dwxh   1/1     Running   0          46s

kubectl exec -it my-nginx-76b6489f44-6dwxh -- cat /etc/config/log_levelINFOkubectl edit configmap log-configapiVersion: v1data:  log_level: DEBUG        #INFO 修改成 DEBUGkind: ConfigMapmetadata:  annotations:    kubectl.kubernetes.io/last-applied-configuration: |      {"apiVersion":"v1","data":{"log_level":"DEBUG"},"kind":"ConfigMap","metadata":{"annotations":{},"name":"log-config","namespace":"default"}}            #INFO 修改成 DEBUG  creationTimestamp: 2021-05-25T07:59:18Z  name: log-config  namespace: default  resourceVersion: "93616"  selfLink: /api/v1/namespaces/default/configmaps/log-config  uid: 1b8115de-bd2f-11eb-acba-000c29d88bba

//等大概10秒左右,使用该 ConfigMap 挂载的 Volume 中的数据同步更新

kubectl exec -it my-nginx-76b6489f44-6dwxh -- cat /etc/config/log_levelDEBUG

2.1.4ConfigMap 更新后滚动更新 Pod

更新 ConfigMap 目前并不会触发相关 Pod 的滚动更新,可以通过在 .spec.template.metadata.annotations 中添加 version/config ,每次通过修改 version/config 来触发滚动更新

kubectl patch deployment my-nginx --patch '{"spec": {"template": {"metadata": {"annotations": {"version/config": "20210525" }}}}}'

kubectl get pods NAME                        READY   STATUS              RESTARTS   AGEmy-nginx-665dd4dc8c-j4k9t   0/1     ContainerCreating   0          4smy-nginx-76b6489f44-6dwxh   0/1     Terminating         0          10mkubectl get pods NAME                        READY   STATUS    RESTARTS   AGEmy-nginx-665dd4dc8c-j4k9t   1/1     Running   0          74s

PS:更新 ConfigMap 后:
●使用该 ConfigMap 挂载的 Env 不会同步更新。
●使用该 ConfigMap 挂载的 Volume 中的数据需要一段时间(实测大概10秒)才能同步更新。