configMap资源和secret资源

-
2024-07-08

区别:

ConfigMap适用于非敏感的配置信息,而Secret则用于敏感的机密信息。

configmap

[root@k8s ~]# cat conf_map.yaml
apiVersion: v1
kind: ConfigMap
metadata:
    name: test
data:
#定义一堆
    all: |
adasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
#定义单个
    one: bbbbbbbbbbbbbbbbbbbbbbbbbbbbb

 

使用:

基于env

apiVersion: v1
kind: Pod
metadata:
  name: alpine-nginx-tomcat-cm-env1
spec:
  nodeName: k8s1
  containers:
    - name: nginx
      image: nginx:1.23.4-alpine
      env:
        - name: test_cm
          valueFrom:
              name: test  # ConfigMap 的名称
              key: all     # ConfigMap 中的键名

基于volume

apiVersion: v1
kind: Pod
metadata:
  name: alpine-nginx-tomcat-cm-volum
spec:
  nodeName: k8s2
  containers:
    - name: nginx
      image: nginx:1.23.4-alpine
      volumeMounts:
        - name: nginx-conf
          mountPath: /etc/nginx/conf.d/default.conf
          subPath: default.conf #和volumes的items.path一致表示挂载点是文件而不是目录
      command: ["tail","-f","/etc/hosts"]
      
  volumes:
    - name: nginx-conf
      configMap:
        name: test
        items:
          - key: all
            path: default.conf

Secret资源

apiVersion: v1
kind: Secret
metadata:
  name: es-https
data:
  username: ZWxhc3RpYwo=
  password: b2xkYm95ZWR1Cg==
  hostip: MTAuMC4wLjI1MAo=

这里的数据可以用base64加密,secret资源会自动解密

apiVersion: v1
kind: Pod
metadata:
  name: linux85-game-secret-001
spec:
  nodeName: k8s1
  containers:
  - name: game
    image: nginx
    env:
    - name: USERNAME
      valueFrom:
        # 指定引用的secret资源
        secretKeyRef:
          # 指定secret的名称
          name: es-https
          # 指定secret的KEY
          key: username
    - name: PASSWORD
      valueFrom:
        secretKeyRef:
          name: es-https
          key: password
    - name: HOSTIP
      valueFrom:
        secretKeyRef:
          name: es-https
          key: hostip

Pod基于存储卷引用secret资源案例

apiVersion: v1
kind: Pod
metadata:
  name: secret-003
spec:
  nodeName: web
  volumes:
  - name: data
    # 指定存储卷的类型为secret
    secret:
      # 指定secret的名称
      secretName: es-https
      items:
      - key: username
        path: username.info
      - key: password
        path: password.info
      - key: hostip
        path: hostip.info
      containers:
  - name: web
    image: nginx:1.20.1-alpine
    command: ["tail","-f","/etc/hosts"]
    volumeMounts:
    - name: data
      # mountPath: /data
      mountPath: /etc/nginx/nginx.conf
      subPath: username.info
    - name: data
      mountPath: /etc/nginx/password.conf
      subPath: password.info
    - name: data
      mountPath: /etc/nginx/hostip.conf
      subPath: hostip.info

 

 


目录