Secret

作用:加密数据存在etcd里面,让pod容器以变量或挂载Volume方式进行访问
场景:凭证

1.创建secret加密数据

  1. apiVersion: v1
  2. kind: Secret
  3. metadate:
  4. name: mysecret
  5. type: Opaque
  6. data:
  7. username: xxx
  8. password: xxx

kubectl create -f secret.yaml
kubectl get secret

base64编码:echo -n ‘admin’ | base64

2.以变量形式挂载到pod容器中

  1. - name: SECRET_USERNAME
  2. valueFrom:
  3. secretKeyRef:
  4. name: mysecret
  5. key: username
  6. - name: SECRET_PASSWORD
  7. valueFrom:
  8. secretKeyRef:
  9. name: mysecret
  10. key: password

kubectl apply -f secret-env.yaml
kubectl get pods
kubectl exec -it pod-name /bin/bash # 进入pod中查看定义的变量是否生效
echo $SECRET_USERNAME
echo $SECRET_PASSWORD

3.以数据卷的方式挂载到pod中

  1. - name: nginx
  2. image: nginx
  3. volumeMounts:
  4. - name: foo
  5. mountPath: "/etc/foo"
  6. readOnly: true
  7. volumes:
  8. - name: foo
  9. secret:
  10. secretName: mysecret

kubectl apply -f secret-vol.yaml
kubectl get pods
kubectl exec -it pod-name /bin/bash
ls /etc/foo
cat /etc/foo/username
cat /etc/foo/password

ConfigMap

作用:存储不加密数据到etcd,让Pod以变量或者挂载Volume的方式访问
场景:配置文件

1.创建配置文件

vi redis.properties
redis.host=127.0.0.1
redis.port=6379
redis.password=123456

2.创建configmap

kubectl create configmap redis-config —from-file=redis.properties
kubectl get cm
kubectl describe cm redis-config # 查看configmap的详细内容

3.以Volume挂载到pod中

vi mypod.yaml

  1. apiVersion: v1
  2. kind: Pod
  3. metadata:
  4. name: mypod
  5. spec:
  6. containers:
  7. - name: busybox
  8. image: busybox
  9. command: ["/bin/sh", "-c","cat /etc/config/redis.properties"]
  10. volumeMounts:
  11. - name: config-volume
  12. mountPath: /etc/config
  13. volumes:
  14. - name: config-volume
  15. configMap:
  16. name: redis-config
  17. restartPolicy: Never

kubectl apply -f cm.yaml
kubectl get pods # 状态为completed
kubectl logs mypod # 查看为redis.properties内容

4.以变量形式挂载到pod容器中

1) 创建yaml,声明变量信息 configmap创建
vi myconfig.yaml

  1. apiVersion: v1
  2. kind: ConfigMap
  3. metadata:
  4. name: myconfig
  5. namespace: default
  6. data:
  7. special.level: info
  8. special.type: hello

kubectl apply -f myconfig.yaml
kubectl get cm

2) 以变量挂载
vi config-var.yaml

  1. apiVersion: v1
  2. kind: Pod
  3. metadata:
  4. name: mypod
  5. spec:
  6. containers:
  7. - name: busybox
  8. image: busybox
  9. command: ["/bin/sh", "-c","echo $(LEVEL) $(TYPE)"]
  10. env:
  11. - name: LEVEL
  12. valueFrom:
  13. configMapKeyRef:
  14. name: myconfig
  15. key: special.level
  16. - name: LEVEL
  17. valueFrom:
  18. configMapKeyRef:
  19. name: myconfig
  20. key: special.type
  21. restartPolicy: Never

kubectl apply -f config-var.yaml
kubectl get pods
kubectl logs mypod