k8s配置资源管理

Secret

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

类型

kubernetes.io/service-account-token

由k8s自动创建,用来访问APIServer的Secret,Pod会默认使用这个Secret与APIServer通信,并且会自动挂载到Pod 的 /run/secrets/kubernetes.io/serviceaccount 目录中

Opaque

base64编码格式的Secret,用来存储用户自定义密码,密钥等,默认的secret类型

kubernetes.io/dockerconfigjson

用来存储私有 docker registry 的认证信息

Pod使用secret

Pod 需要先引用才能使用某个 secret,Pod 有 3 种方式来使用 secret:

作为挂载到一个或多个容器的卷

作为容器的环境变量

由kubelet在为Pod拉取镜像时使用

创建secret

创建secret

1.用kubectl create secret 命令创建Secret
echo -n 'emmm' > username.txt
echo -n 'abc123' > password.txt

kubectl create secret generic mysecret --from-file=username.txt --from-file=password.txt

kubectl get secrets
NAME                                 TYPE                                  DATA   AGE
default-token-kr2xl                  kubernetes.io/service-account-token   3      17d
mysecret                             Opaque                                2      5s
nfs-client-provisioner-token-nszdh   kubernetes.io/service-account-token   3      44h

kubectl describe secret mysecret
Name:         mysecret
Namespace:    default
Labels:       <none>
Annotations:  <none>

Type:  Opaque

Data
====
username.txt:  4 bytes
password.txt:  6 bytes
#get或describe指令都不会展示secret的实际内容,这是出于对数据的保护的考虑



2.使用 base64编码,创建secret
echo -n emmm | base 64
ZW1tbQ==
echo -n abc123 | base 64
YWJjMTIz

vim secret.yaml
apiVersion: v1
kind: Secret
metadata:
  name: mysecret1
type: Opaque
data:
  username: ZW1tbQ==
  password: YWJjMTIz

kubectl apply -f secret.yaml


kubectl get secrets
NAME                                 TYPE                                  DATA   AGE
default-token-kr2xl                  kubernetes.io/service-account-token   3      17d
mysecret                             Opaque                                2      8m57s
mysecret1                            Opaque                                2      8s
nfs-client-provisioner-token-nszdh   kubernetes.io/service-account-token   3      44h


kubectl get secret mysecret1 -o yaml

apiVersion: v1
data:
  password.txt: YWJjMTIz
  username.txt: ZW1tbQ==
kind: Secret
metadata:
  creationTimestamp: "2024-06-03T06:55:08Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:password.txt: {}
        f:username.txt: {}
      f:type: {}
    manager: kubectl-create
    operation: Update
    time: "2024-06-03T06:55:08Z"
  name: mysecret
  namespace: default
  resourceVersion: "210634"
  selfLink: /api/v1/namespaces/default/secrets/mysecret
  uid: 950d1b75-b1fd-4c34-b7a9-07cd74763ad5
type: Opaque

使用方式

使用方式
1.将Secret挂载到volume中,以volume的形式挂载到Pod的某个目录下
vim secret-test.yaml
apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
  - name: nginx
    image: nginx
    volumeMounts:
    - name: secrets
      mountPath: "/etc/secrets"
  volumes:
  - name: secrets
    secret:
      secretName: mysecret

kubectl apply -f secret-test.yaml

kubectl get pods   
NAME    READY   STATUS    RESTARTS   AGE
mypod   1/1     Running   0          59s


kubectl exec -it seret-test bash
 # cd /etc/secrets/
 # ls
password.txt  username.txt



2.将Secret导出到环境变量中
vim secret-test1.yaml

apiVersion: v1
kind: Pod
metadata:
  name: mypod1
spec:
  containers:
  - name: nginx
    image: nginx
    env:
      - name: TEST_USER
        valueFrom:
          secretKeyRef:
            name: mysecret1
            key: username
      - name: TEST_PASSWORD
        valueFrom:
          secretKeyRef:
            name: mysecret1
            key: password

kubectl apply -f secret-test1.yaml

kubectl get pods
NAME     READY   STATUS    RESTARTS   AGE
mypod    1/1     Running   0          46m
mypod1   1/1     Running   0          18s


kubectl exec -it mypod1 bash

root@mypod1:/# echo $TEST_USER
emmm
root@mypod1:/# echo $TEST_PASSWORD
abc123

ConfigMap

与Secret类似,区别在于ConfigMap保存的是不需要加密的信息

ConfigMap功能在kubernetes1.2版本中引入,许多应用程序会从配置文件,命令行参数或环境变量中读取配置信息

ConfigMap API 给我们提供了向容器中注入配置信息的机制,ConfigMap可以被用来保存单个属性,也可以用来保存整个配置文件或者JSON二进制对象

应用场景:应用配置

创建configmap

创建ConfigMap

1.使用目录创建
mkdir /opt/configmap/

vim /opt/configmap/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

vim /opt/configmap/ui.properties
color.good=purple
color.bad=yellow
allow.textmode=true
how.nice.to.look=fairlyNice

ls /opt/configmap/

game.properties  ui.properties

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

kubectl get cm
NAME               DATA   AGE
game-config        2      4s
kube-root-ca.crt   1      18d


kubectl get cm game-config -o yaml
apiVersion: v1
data:
  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=fairlyNice

kind: ConfigMap
metadata:
  creationTimestamp: "2024-06-03T08:14:20Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:game.properties: {}
        f:ui.properties: {}
    manager: kubectl-create
    operation: Update
    time: "2024-06-03T08:14:20Z"
  name: game-config
  namespace: default
  resourceVersion: "217323"
  selfLink: /api/v1/namespaces/default/configmaps/game-config
  uid: 298d4bfd-ec91-4f09-9a78-7fd778c53251




2.使用文件创建
使用文字值创建,利用 --from-literal 参数传递配置信息,该参数可以使用多次,格式如下
kubectl create configmap special-config --from-literal=special.how=very --from-literal=special.type=good

kubectl get configmaps special-config -o yaml

apiVersion: v1
data:
  special.how: very
  special.type: good
kind: ConfigMap
metadata:
  creationTimestamp: "2024-06-03T08:25:37Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:special.how: {}
        f:special.type: {}
    manager: kubectl-create
    operation: Update
    time: "2024-06-03T08:25:37Z"
  name: special-config
  namespace: default
  resourceVersion: "218272"
  selfLink: /api/v1/namespaces/default/configmaps/special-config
  uid: ded882f9-8665-4c60-949e-5c2a7a088e08

kubectl delete cm --all
kubectl delete pod --all

pod使用configmap

1.使用configmap来替代环境变量
vim env.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: special-config
  namespace: default
data:
  special.how: very
  special.type: good
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: env-config
  namespace: default
data:
  log_level: INFO

kubectl create -f env.yaml

kubectl get cm
NAME               DATA   AGE
env-config         1      10s
kube-root-ca.crt   1      8m23s
special-config     2      10s


POD的创建
vim test-pod.yaml

apiVersion: v1
kind: Pod
metadata:
  name: test-pod
spec:
  containers:
  - name: busybox
    image: busybox:1.28.4
    command: ["/bin/sh","-c","env"]
    env:
      - name: SPECIAL_HOW_KEY
        valueFrom:
          configMapKeyRef:
            name: special-config
            key: sepcial.how
      - name: SPECIAL_TYPE_KEY
        valueFrom:
          configMapKeyRef:
            name: special-config
            key: special.type
    envFrom:
      - configMapRef:
          name: env-config
  restartPolicy: Never
   

kubectl apply -f test-pod.yaml

kubectl get pods
NAME       READY   STATUS      RESTARTS   AGE
test-pod   0/1     Completed   1          4s


kubectl logs pod-test
KUBERNETES_SERVICE_PORT=443
KUBERNETES_PORT=tcp://10.96.0.1:443
HOSTNAME=test-pod
SHLVL=1
SPECIAL_HOW_KEY=very
HOME=/root
SPECIAL_TYPE_KEY=good
KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
KUBERNETES_PORT_443_TCP_PORT=443
KUBERNETES_PORT_443_TCP_PROTO=tcp
log_level=INFO
KUBERNETES_SERVICE_PORT_HTTPS=443
KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443
KUBERNETES_SERVICE_HOST=10.96.0.1
PWD=/




2.用ConfigMap设置命令行参数
vim test-pod2.yaml
apiVersion: v1
kind: Pod
metadata:
  name: test-pod2
spec:
  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: Never

kubectl create -f test-pod2.yaml

kubectl get pods
NAME        READY   STATUS      RESTARTS   AGE
test-pod    0/1     Completed   0          28m
test-pod2   0/1     Completed   0          6s


kubectl logs test-pod2
very good



3.通过数据卷插件使用ConfigMap
在数据卷里面使用 ConfigMap,就是将文件填入数据卷,在这个文件中,键就是文件名,键值就是文件内容
vim test-pod3.yaml
apiVersion: v1
kind: Pod
metadata:
  name: test-pod3
spec:
  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: Never

kubectl create -f test-pod3.yaml

kubectl get pods
NAME        READY   STATUS      RESTARTS   AGE
test-pod    0/1     Completed   0          34m
test-pod2   0/1     Completed   0          6m39s
test-pod3   1/1     Running     0          3s


kubectl exec -it test-pod3 bash
/ # cd /etc/config/
/etc/config # ls
special.how   special.type

configMap的热更新

vim test-pod4.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: log-config
  namespace: default
data:
  log_level: INFO
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: my-nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      run: my-nginx
  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-config

kubectl apply -f test-pod5.yaml


kubectl get pods 
NAME                        READY   STATUS    RESTARTS   AGE
my-nginx-7b8755d996-nvtvn   1/1     Running   0          40s

kubectl exec -it my-nginx-7b8755d996-nvtvn -- cat /etc/config/log_level
INFO

kubectl edit configmap log-config

# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: v1
data:
  log_level: DEBUG  #INFO改成DEBUG
kind: ConfigMap
metadata:
  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: "2024-06-03T10:01:11Z"
  name: log-config
  namespace: default
  resourceVersion: "226432"
  selfLink: /api/v1/namespaces/default/configmaps/log-config
  uid: 668e9b43-4bce-4095-9fd6-3f167ef0b123

等大概10秒左右,使用该 ConfigMap 挂载的 Volume 中的数据同步更新
kubectl exec -it my-nginx-7b8755d996-nvtvn -- cat /etc/config/log_level
DEBUG

ConfigMap 更新后滚动更新 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   AGE
my-nginx-5ff655678f-rb8bn   0/1     ContainerCreating   0          3s
my-nginx-7b8755d996-nvtvn   1/1     Running             0          13m
kubectl get pods 
NAME                        READY   STATUS    RESTARTS   AGE
my-nginx-5ff655678f-rb8bn   1/1     Running   0          56s



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

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值