k8s Secret

内容纲要

概述

在我们的业务开发中,我们的应用或者服务需要很多配置,我们业务需求中很多配置很多都可以通过ConfigMap解决,但是有一些机密信息需要使用Secret,例如:数据库账号密码,Redis密码,MQ的认证信息等等,同时在不同环境也需要不同的配置。
k8s提供了Secret资源对象为我们的应用提供了敏感信息配置。

适用场景

Secret的应用场景就是敏感信息。

Secret创建

Secret可以通过以下方式创建:

  1. 通过字面值
  2. 通过普通文件
  3. 通过Yaml

通过字面值

kubectl create secret generic literal-credential --from-literal=hello1=world1 --from-literal=hell2=world2

secret/literal-credential created

通过普通文件

通过文件创建secret,一个文件对应secret中的key-value键值对,key为文件名,文件内容为value,例如:

echo -n world1 >./hello1
echo -n world2 >./hello2

kubectl create secret generic file-credential --from-file=./hello1 --from-file=./hello2

secret/file-credential created

查看我们创建好的file-credential,

kubectl describe secret/file-credential

file

通过Yaml

通过Yaml方式创建,通过Yaml方式创建需要我们对secret中的value进行一次Base64编码,如下:
我们先对value进行Base64编码

echo -n world1 | base64
echo -n world2 | base64

编写Seret Yaml:

kind: Secret
apiVersion: v1
metadata:
  name: yaml-credential
  namespace: default
data:
  hello1: d29ybGQx
  hello2: d29ybGQy
type: Opaque

file
创建secret:

kubectl create -f helloworld.yaml

secret/yaml-credential created

查看Secret:
file

查看Secret

# 查看secret列表
kubectl get secret

# 查看secret中的key
kubectl describe secert/literal-credential

file

Secret使用

Secret使用的方式和ConfigMap一样,有两种方式:

  1. 环境变量
  2. Volume

环境变量

环境变量方式在k8s中有两种方式:

  1. env
  2. envFrom

env

deployment中引用刚才创建的literal-helloworld中的key和value。

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  namespace: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - image: nginx:1.14.0
        ports:
        - containerPort: 80
      - env:
        - name: hello
          valueFrom:
            secretKeyRef:
              key: hello1
              name: yaml-credential

envFrom

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: nginx
  name: nginx
  namespace: default
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - image: nginx:1.14.0
        ports:
        - containerPort: 80
        name: nginx
        envFrom:
          - secretRef:
              name: yaml-credential

Volume

apiVersoin: v1
kind: Pod
metadata:
  name: hellopod
sepc:
  containers:
  - name: hellopod
    image: nginx:1.14.0
    volumeMounts:
    - name:
      mountPath: "/etc/helloworld"
      readOnly: true
  volumes:
  - name: helloworld
    secret:
      secretName: yaml-credential

8人评论了“k8s Secret”

  1. I’m often to blogging and i really appreciate your content. The article has actually peaks my interest. I’m going to bookmark your web site and maintain checking for brand spanking new information.

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部