Secret解决了密码、token、密钥等敏感数据的配置问题,而不需要把这些敏感数据暴露到镜像或者Pod Spec中。

Secret使用:
1. Volume
2. 环境变量

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

secret Opaque类型使用 - Volume

  • secret通过yaml创建
apiVersion: v1
kind: Secret
metadata:
  name: mysecret
type: Opaque
data:
  password: dmFsdWUtMg0K
  username: dmFsdWUtMQ0K
  • 查看创建好的secret
[root@controller01 secret]# kubectl get secret  mysecret -o yaml
apiVersion: v1
data:
  password: dmFsdWUtMg0K
  username: dmFsdWUtMQ0K
kind: Secret
metadata:
  creationTimestamp: 2017-06-23T03:12:03Z
  name: mysecret
  namespace: default
  resourceVersion: "2730149"
  selfLink: /api/v1/namespaces/default/secrets/mysecret
  uid: bb3c0004-57c1-11e7-901f-6c92bf2e6e88
type: Opaque
  • 在pod中使用,pod yaml文件
apiVersion: v1
kind: Pod
metadata: 
    name: mypod
    namespace: default
spec: 
    volumes:
    - name: foott
      secret:
        secretName: mysecret
    - name: nginx-config-volume
      configMap:
          name: nginx-conf
          items:
              - key: nginx.conf
                path: nginx.conf
    containers: 
      - name: mypod
        image:  10.21.1.151/quicksilver/deploy_openresty:1.2
        command: ["/bin/sh", "-c", "/usr/local/openresty/nginx/sbin/nginx -c /tmp/nginx.conf"]
        volumeMounts: 
          - name: foott
            mountPath: /etc/foott
            readOnly: true
          - name: nginx-config-volume
            mountPath: /tmp/
  • 进入pod,查看映射的文件
[root@mypod foott]# cat /etc/foott/username 
value-1
[root@mypod foott]# cat /etc/foott/password 
value-2

我们可以发现pod中的username和password文件与secret中的不一样,因为secret中的是经过base64加密过的。

[root@mypod foott]# echo -n "value-1" | base64
dmFsdWUtMQ==
[root@mypod foott]# echo -n "value-2" | base64
dmFsdWUtMg==

secret Opaque类型使用 - ENV

  • 通过yaml创建pod
apiVersion: v1
kind: Pod
metadata: 
    name: mypod
    namespace: default
spec: 
    volumes:
    - name: foott
      secret:
        secretName: mysecret
    - name: nginx-config-volume
      configMap:
          name: nginx-conf
          items:
              - key: nginx.conf
                path: nginx.conf
    containers: 
      - name: mypod
        image:  10.21.1.151/quicksilver/deploy_openresty:1.2
        command: ["/bin/sh", "-c", "/usr/local/openresty/nginx/sbin/nginx -c /tmp/nginx.conf"]
        volumeMounts: 
          - name: nginx-config-volume
            mountPath: /tmp/
        env:
          - name: WORDPRESS_DB_USER
            valueFrom:
              secretKeyRef:
                name: mysecret
                key: username
          - name: WORDPRESS_DB_PASSWORD
            valueFrom:
              secretKeyRef:
                name: mysecret
                key: password

  • 查看pod中的环境变量
[root@mypod /]# env | grep ^WORD*
WORDPRESS_DB_PASSWORD=value-2
WORDPRESS_DB_USER=value-1
Logo

开源、云原生的融合云平台

更多推荐