k8s之安全信息(secret)及配置信息(configmap)管理

应用启动过程中可能需要一些敏感信息,比如访问数据库的用户名密码或者秘钥。将这些信息直接保存在容器镜像中显然不妥,Kubernetes 提供的解决方案是 Secret。

Secret 会以密文的方式存储数据,避免了直接在配置文件中保存敏感信息。Secret 会以 Volume 的形式被 mount 到 Pod,容器可通过文件的方式使用 Secret 中的敏感数据;此外,容器也可以环境变量的方式使用这些数据。

Secret 可通过命令行或 YAML 创建。比如希望 Secret 中包含如下信息:

  1. 用户名 admin
  2. 密码 123456
创建 Secret

有四种方法创建 Secret:

  1. 通过 --from-literal:

    kubectl create secret generic mysecret --from-literal=username=admin --from-literal=password=123456

    每个 --from-literal 对应一个信息条目。

  2. 通过 --from-file:
    echo -n admin > ./username
    echo -n 123456 > ./password
    kubectl create secret generic mysecret --from-file=./username --from-file=./password

    每个文件内容对应一个信息条目。

  3. 通过 --from-env-file:
    cat << EOF > env.txt
    username=admin
    password=123456
    EOF
    kubectl create secret generic mysecret --from-env-file=env.txt

    文件 env.txt 中每行 Key=Value 对应一个信息条目。

  4. 通过 YAML 配置文件:
    apiVersion: v1
    kind: Secret
    metadata:
    name: mysecret
    data:
    username: YWRtaW4=
    password: MTIzNDU2

文件中的敏感数据必须是通过 base64 编码后的结果。

[[email protected] ~]# echo -n admin |base64
YWRtaW4=
[[email protected] ~]# echo -n 123456 | base64
MTIzNDU2

执行 kubectl apply 创建 Secret:

# kubectl apply -f mysecrete.yml
secret/mysecret created
使用这些创建好的 Secret。

查看 Secre
可以通过 kubectl get secret 查看存在的 secret。

[[email protected] ~]# kubectl get secrets
NAME                  TYPE                                  DATA   AGE
default-token-5l66h   kubernetes.io/service-account-token   3      14d
mysecret              Opaque                                2      20s

显示有两个数据条目,kubectl describe secret 查看条目的 Key:

[[email protected] ~]# kubectl describe secrets mysecret
Name:         mysecret
Namespace:    default
Labels:       <none>
Annotations:
Type:         Opaque

Data
====
password:  6 bytes
username:  5 bytes
[[email protected] ~]# 

如果还想查看 Value,可以用 kubectl edit secret mysecret:

apiVersion: v1
data:
  password: MTIzNDU2
  username: YWRtaW4=
kind: Secret
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","data":{"password":"MTIzNDU2","username":"YWRtaW4="},"kind":"Secret","metadata":{"annotations":{},"name":"mysecret","namespace":"default"}}
  creationTimestamp: "2019-10-14T08:26:43Z"
  name: mysecret
  namespace: default
  resourceVersion: "13845"
  selfLink: /api/v1/namespaces/default/secrets/mysecret
  uid: a713292c-6fea-4065-b5ae-239f8fe9a76f
type: Opaque
~              

然后通过 base64 将 Value 反编码:

[[email protected] ~]# echo -n MTIzNDU2 |base64 --decode
123456

# echo -n YWRtaW4=  |base64 --decode
admin[[email protected] ~]# 

如何在 Pod 中使用 Secret。

volume 方式使用 Secret

Pod 可以通过 Volume 或者环境变量的方式使用 Secret。

Pod 的配置文件如下所示:

apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
  - name: mypod
    image: busybox
    args:
      - /bin/sh
      - -c
      - sleep 10;touch /tmp/healthy;sleep 30000
    volumeMounts:
    - name: foo
      mountPath: /etc/foo
      readOnly: true
  volumes:
  - name: foo
    secret:
      secretName: mysecret

① 定义 volume foo,来源为 secret mysecret。

② 将 foo mount 到容器路径 /etc/foo,可指定读写权限为 readOnly。

创建 Pod 并在容器中读取 Secret:

[[email protected] ~]# kubectl apply -f mypod.yml
pod/mypod created
[[email protected] ~]# kubectl exec -it mypod sh
/ # ls /etc/foo/
password  username
/ # cat /etc/foo/username
admin/ #
/ # cat /etc/foo/password
123456/ #
/ #
/ # exit

可以看到,Kubernetes 会在指定的路径 /etc/foo 下为每条敏感数据创建一个文件,文件名就是数据条目的 Key,这里是 /etc/foo/username 和 /etc/foo/password,Value 则以明文存放在文件中。

我们也可以自定义存放数据的文件名,比如将配置文件改为:


apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
  - name: mypod
    image: busybox
    args:
      - /bin/sh
      - -c
      - sleep 10;touch /tmp/healthy;sleep 30000
    volumeMounts:
    - name: foo
      mountPath: /etc/foo
      readOnly: true
  volumes:
  - name: foo
    secret:
      secretName: mysecret
      items:
      - key: username
        path: my-group/my-username
      - key: password
        path: my-group/my-password

这时数据将分别存放在 /etc/foo/my-group/my-username 和 /etc/foo/my-group/my-password 中。

以 Volume 方式使用的 Secret 支持动态更新:Secret 更新后,容器中的数据也会更新。

将 password 更新为 abcdef,base64 编码为 YWJjZGVm

[[email protected] ~]# cat mysecrete.yml
apiVersion: v1
kind: Secret
metadata:
  name: mysecret
data:
  username: YWRtaW4=
  password: YWJjZGVm

更新 Secret。

[[email protected] ~]# kubectl apply -f mysecrete.yml
secret/mysecret configured

等待,新的 password 会同步到容器。

/etc/foo/..2019_10_14_09_42_09.863448745/my-group # cat my-password
abcdef/etc/foo/..2019_10_14_09_42_09.863448745/my-group # 
环境变量方式使用 Secret

通过 Volume 使用 Secret,容器必须从文件读取数据,会稍显麻烦,Kubernetes 还支持通过环境变量使用 Secret。

Pod 配置文件示例如下:

apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
  - name: mypod
    image: busybox
    args:
      - /bin/sh
      - -c
      - sleep 10; touch /tmp/healthy; sleep 30000
    env:
      - name: SECRET_USERNAME
        valueFrom:
          secretKeyRef:
            name: mysecret
            key: username
      - name: SECRET_PASSWORD
        valueFrom:
          secretKeyRef:
            name: mysecret
            key: password

创建 Pod 并读取 Secret。

[[email protected] ~]# kubectl apply -f mysql-env.yml
pod/mypod created
[[email protected] ~]# kubectl exec -it mypod sh
/ # echo $SECRET_USERNAME
admin
/ # echo $SECRET_PASSWORD
123456
/ # 

通过环境变量 SECRET_USERNAME 和 SECRET_PASSWORD 成功读取到 Secret 的数据。

需要注意的是,环境变量读取 Secret 很方便,但无法支撑 Secret 动态更新。

Secret 可以为 Pod 提供密码、Token、私钥等敏感数据;对于一些非敏感数据,比如应用的配置信息,则可以用 ConfigMap。

用 ConfigMap 管理配置

Secret 可以为 Pod 提供密码、Token、私钥等敏感数据;对于一些非敏感数据,比如应用的配置信息,则可以用 ConfigMap。

ConfigMap 的创建和使用方式与 Secret 非常类似,主要的不同是数据以明文的形式存放。

与 Secret 一样,ConfigMap 也支持四种创建方式:

  1. 通过 --from-literal:

    kubectl create configmap myconfigmap --from-literal=config1=xxx --from-literal=config2=yyy

    每个 --from-literal 对应一个信息条目。

  2. 通过 --from-file:
    echo -n xxx > ./config1
    echo -n yyy > ./config2
    kubectl create configmap myconfigmap --from-file=./config1 --from-file=./config2

    每个文件内容对应一个信息条目。

  3. 通过 --from-env-file:
    cat << EOF > env.txt
    config1=xxx
    config2=yyy
    EOF
    kubectl create configmap myconfigmap --from-env-file=env.txt

    文件 env.txt 中每行 Key=Value 对应一个信息条目。

  4. 通过 YAML 配置文件:
    apiVersion: v1
    kind: ConfigMap
    metadata:
    name: myconfigmap1
    data:
    config1: xxx
    config2: yyy

    文件中的数据直接以明文输入。

与 Secret 一样,Pod 也可以通过 Volume 或者环境变量的方式使用 Secret。

Volume 方式:

apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
  - name: mypod
    image: busybox
    args:
      - /bin/sh
      - -c
      - sleep 10; touch /tmp/healthy; sleep 30000
    volumeMounts:
    - name: foo
      mountPath: /etc/foo
      readOnly: true
  volumes:
  - name: foo
    configMap:
      name: myconfigmap

环境变量方式:

apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
  - name: mypod
    image: busybox
    args:
      - /bin/sh
      - -c
      - sleep 10; touch /tmp/healthy; sleep 30000
    env:
      - name: CONFIG_1
        valueFrom:
          configMapKeyRef:
            name: myconfigmap
            key: config1
      - name: CONFIG_2
        valueFrom:
          configMapKeyRef:
            name: myconfigmap
            key: config2

大多数情况下,配置信息都以文件形式提供,所以在创建 ConfigMap 时通常采用 --from-file 或 YAML 方式,读取 ConfigMap 时通常采用 Volume 方式。

比如给 Pod 传递如何记录日志的配置信息:

class: logging.handlers.RotatingFileHandler
formatter: precise
level: INFO
filename: %hostname-%timestamp.log

可以采用 --from-file 形式,则将其保存在文件 logging.conf 中,然后执行命令:

# kubectl create configmap myconfigmap2 --from-file=./logging.conf 

kubectl create configmap myconfigmap --from-file=./logging.conf
如果采用 YAML 配置文件,其内容则为:

apiVersion: v1
kind: ConfigMap
metadata:
  name: myconfigmap3
data:
  logging.conf: |
    class: logging.handlers.RotatingFileHandler
    formatter: precise
    level: INFO
    filename: %hostname-%timestamp.log

注意别漏写了 Key logging.conf 后面的 | 符号。

创建并查看 ConfigMap:

[[email protected] ~]# kubectl apply -f myconfigmap2.yml
configmap/myconfigmap3 created
[[email protected] ~]# kubectl get configmaps myconfigmap3
NAME           DATA   AGE
myconfigmap3   1      2m39s
[[email protected] ~]# kubectl describe configmaps myconfigmap3
Name:         myconfigmap3
Namespace:    default
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"v1","data":{"logging.conf":"class: logging.handlers.RotatingFileHandler\nformatter: precise\nlevel: INFO\nfilename: %hostna...

Data
====
logging.conf:
----
class: logging.handlers.RotatingFileHandler
formatter: precise
level: INFO
filename: %hostname-%timestamp.log

Events:  <none>
[[email protected] ~]# 

在 Pod 中使用此 ConfigMap,配置文件为:

apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
  - name: mypod
    image: busybox
    args:
      - /bin/sh
      - -c
      - sleep 10;touch /tmp/healthy;sleep 30000
    volumeMounts:
    - name: foo
      mountPath: /etc/
  volumes:
  - name: foo
    configMap:
      name: myconfigmap3
      items:
        - key: logging.conf
          path: myapp/logging.conf

① 在 volume 中指定存放配置信息的文件相对路径为 myapp/logging.conf。

② 将 volume mount 到容器的 /etc 目录。

创建 Pod 并读取配置信息:

配置信息已经保存到 /etc/myapp/logging.conf 文件中。与 Secret 一样,Volume 形式的 ConfigMap 也支持动态更新,留给大家自己实践。

小结
向 Pod 传递配置信息。如果信息需要加密,可使用 Secret;如果是一般的配置信息,则可使用 ConfigMap。

Secret 和 ConfigMap 支持四种定义方法。Pod 在使用它们时,可以选择 Volume 方式或环境变量方式,不过只有 Volume 方式支持动态更新。

原文地址:https://blog.51cto.com/5157495/2442447

时间: 2024-08-19 07:03:13

k8s之安全信息(secret)及配置信息(configmap)管理的相关文章

log4net截取配置错误信息,(验证配置信息是否配置正确)

在</system.web>之后 <!--log4错误日志配置:开始--> <system.diagnostics> <trace autoflush="true"> <listeners> <add name="textWriterTraceListener" type="System.Diagnostics.TextWriterTraceListener" initialize

JavaWeb学习之Servlet(四)----ServletConfig获取配置信息、ServletContext的应用

[声明] 欢迎转载,但请保留文章原始出处→_→ 文章来源:http://www.cnblogs.com/smyhvae/p/4140877.html 联系方式:[email protected] [正文] 一.ServletConfig:代表当前Servlet在web.xml中的配置信息(用的不多) String getServletName()  -- 获取当前Servlet在web.xml中配置的名字 String getInitParameter(String name) -- 获取当前S

JavaWeb学习之Servlet(四)----ServletConfig获取配置信息、ServletContext的应用(转)

JavaWeb学习之Servlet(四)----ServletConfig获取配置信息.ServletContext的应用 [声明] 欢迎转载,但请保留文章原始出处→_→ 文章来源:http://www.cnblogs.com/smyhvae/p/4140877.html [正文] 一.ServletConfig:代表当前Servlet在web.xml中的配置信息(用的不多) String getServletName()  -- 获取当前Servlet在web.xml中配置的名字 String

CentOS6.8 安装配置以svnadmin管理svn代码库

一.系统环境及说明 CentOS6.8_X64 subversion版本 1.8.15 svn是版本控制软件,虽然git大用替代它的趋势,但不可否则还有很多老用户喜欢它,及svn有一个好用的功能hooks钩子功能.后面再说这个hooks的用处. 1.准备repo $cat /etc/yum.repo.d/svn.repo [WandiscoSVN] name=Wandisco SVN Repo baseurl=http://opensource.wandisco.com/centos/$rele

k8s之安全信息(Secret)及配置信息(ConfigMap)

Secret secret也是k8s中的一个资源对象,主要用于保存轻量的敏感信息,比如数据库用户名和密码,令牌,认证密钥等. 我们可以将这类敏感信息放在secret对象中,如果把它们暴露到镜像或者pod spec中稍显不妥,将其放在secret对象中可以更好地控制及使用,并降低意外暴露的风险.Secret可以使用volume或者环境变量的方式来使用这些轻量级数据. Secret有三种类型: Service Account:用来访问kubernetes API,由k8s自动创建,并且会自动挂载到p

k8s通过configmap管理应用配置信息

Secret 可以为 Pod 提供密码.Token.私钥等敏感数据:对于一些非敏感数据,比如应用的配置信息,则可以用 ConfigMap. ConfigMap 的创建和使用方式与 Secret 非常类似,主要的不同是数据以明文的形式存放. 1.configMap的创建 与 Secret 一样,ConfigMap 也支持四种创建方式: 1.1通过 --from-literal: kubectl create configmap myconfigmap --from-literal=config1=

Yii 配置信息 配置项(Configuration)

1 配置项(Configuration) 2 3 说到配置项,读者朋友们第一反应是不是Yii的配置文件?这是一段配置文件的代码: 4 5 1 6 2 7 3 8 4 9 5 10 6 11 7 12 8 13 9 14 10 15 11 16 12 17 13 18 14 19 15 20 16 21 17 22 18 23 19 24 20 25 21 26 22 27 23 28 24 29 25 30 26 31 27 32 28 33 29 34 30 35 31 36 32 37 33

JavaWEB中读取配置信息

第一种方法是使用java.io和java.util包,缺点是路径的概念要清晰, 例子: Properties prop = new Properties(); InputStream in = getClass().getResourceAsStream("/common.properties"); try { prop.load(in); pool = new JedisPool(config, prop.getProperty("pay.redis.url"))

log4j的配置信息

首先,在项目中的classes 中新建立一个log4j.properties文件即可: 在实际编程时,要使Log4j真正在系统中运行事先还要对配置文件进行定义.定义步骤就是对Logger.Appender及Layout的分别使用.Log4j支持两种配置文件格式,一种是XML格式的文件,一种是java properties(key=value)[Java特性文件(键=值)].(这里只说明properties文件) 1.配置根Logger 其语法为: log4j.rootLogger = [ lev