14、Kubernetes 存储 Secret

x33g5p2x  于2021-12-25 转载在 其他  
字(2.1k)|赞(0)|评价(0)|浏览(441)

Secret 存在意义

Secret 解决了密码、token、密钥等敏感数据的配置问题,而不需要把这些敏感数据暴露到镜像或者 Pod Spec中。Secret 可以以 Volume 或者环境变量的方式使用

Secret 有三种类型:
  • Service Account:用来访问 Kubernetes API,由 Kubernetes 自动创建,并且会自动挂载到 Pod 的/run/secrets/kubernetes.io/serviceaccount目录中
  • Opaque:base64编码格式的Secret,用来存储密码、密钥等
  • kubernetes.io/dockerconfigjson:用来存储私有 docker registry 的认证信息

Service Account

Service Account 用来访问 Kubernetes API,由 Kubernetes 自动创建,并且会自动挂载到 Pod的/run/secrets/kubernetes.io/serviceaccount目录中
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx-deploy
  template:
    metadata:
      labels:
        app: nginx-deploy
    spec:
      containers:
      - name: nginx-deployment
        image: nginx
        env:
        - name: GET_HOSTS_FROM
          value: dns
        ports:
        - containerPort: 80
kubectl exec nginx-75cd57fb6-v9t84 -it /bin/sh

Opaque Secret

1、创建说明
Opaque 类型的数据是一个 map 类型,要求 value 是 base64 编码格式:
echo -n "admin" | base64
YWRtaW4=
echo -n "wtl199201180271" | base64
d3RsMTk5MjAxMTgwMjcx

secrets.yml

apiVersion: v1
kind: Secret
metadata:
  name: mysecret
type: Opaque
data:
  password: d3RsMTk5MjAxMTgwMjcx
  username: YWRtaW4=
2、使用方式
2.1、将 Secret 挂载到 Volume 中
apiVersion: v1
kind: Pod
metadata:
  labels:
    name: secret-test
  name: secret-test
spec:
  volumes:
  - name: secrets
    secret:
      secretName: mysecret
  containers:
  - image: wangyanglinux/myapp:v1
    name: db
    volumeMounts:
    - name: secrets
      mountPath: "/etc/secret"
      readOnly: true

2.2、将 Secret 导出到环境变量中
apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      tier: nginx-deploy
  template:
    metadata:
      labels:
        tier: nginx-deploy
    spec:
      containers:
      - name: nginx-deployment
        image: wangyanglinux/myapp:v1
        ports:
        - containerPort: 80
        env:
        - name: TEST_USER
          valueFrom:
            secretKeyRef:
              name: mysecret
              key: username
        - name: TEST_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysecret
              key: password

kubernetes.io/dockerconfigjson

使用 Kuberctl 创建 docker registry 认证的 secret
kubectl create secret docker-registry myregistrykey --docker-server=DOCKER_REGISTRY_SERVER --docker-username=DOCKER_USER --docker-password=DOCKER_PASSWORD --docker-email=DOCKER_EMAIL
在创建 Pod 的时候,通过imagePullSecrets来引用刚创建的 myregistrykey
apiVersion: v1
kind: Pod
metadata:
  name: pod-test
spec:
  containers:
  - name: container-test
    image: hub.ljxwtl.cn/library/nginx-deployment:v1.0
  imagePullSecrets:
  - name: myregistrykey

相关文章