演示如何使用 configtree 将 Kubernetes Secret 挂载为配置属性

解读

国内云原生面试里,**“把 K8s Secret 变成 Spring Boot 配置”**是高频考点。
考官想确认三件事:

  1. 你真的在集群里跑过代码,而不是只会本地 application.yml;
  2. 知道 Secret 与 ConfigMap 的权限差异(Secret 默认 base64,需只读挂载);
  3. 能讲出 Spring Boot 2.3+ 引入的 configtree 机制,而不是老掉牙的 VolumeMount + @PostConstruct 手动解析。
    答不出“为什么要用 spring.config.import=kubernetes:”基本就挂。

知识点

  1. configtree 本质:
    Spring Boot 把文件夹当成 PropertySource,文件名=key,文件内容=value,天然适配 K8s 的 subPath 挂载。
  2. Secret 挂载约束:
    必须 defaultMode=0400、readOnly=true,防止进程回写触发 K8s 告警;路径推荐 /etc/secrets/<secretName>。
  3. 导入口令:
    spring.config.import=optional:configtree:/etc/secrets/ 一句即可,optional 保证本地 IDE 启动不报错。
  4. 刷新策略:
    Secret 更新后,Pod 需要滚动重启(Secret 是 tmpfs,不支持热更新);如要热刷新,需结合 Spring Cloud Kubernetes @ConfigurationProperties + @RefreshScope。
  5. 安全红线:
    国内等保 2.0 要求敏感字段不落盘,所以必须 memory 型 emptyDir,禁止 hostPath。

答案

step1 制作 Secret

kubectl create secret generic db-auth \
  --from-literal=username=root \
  --from-literal=password=Spring@2024

step2 部署片段(只给关键字段)

volumeMounts:
  - name: db-secret
    mountPath: /etc/secrets/db-auth
    readOnly: true
volumes:
  - name: db-secret
    secret:
      secretName: db-auth
      defaultMode: 0400

step3 application.yml

spring:
  config:
    import: "optional:configtree:/etc/secrets/"
  datasource:
    url: jdbc:mysql://10.0.0.30:3306/test
    username: ${db-auth/username}   # 文件名即 key
    password: ${db-auth/password}

step4 启动验证
本地 IDE 无 /etc/secrets 也能启动(optional 作用);
打到集群后,curl actuator/env 能看到 db-auth/password 来源为 ConfigTreePropertySource,证明挂载成功。

拓展思考

  1. 多环境复用:
    通过 spring.profiles.active=gray + Secret/ConfigMap 名后缀 -gray,实现同一镜像不同集群只改挂载不改包。
  2. 与 Vault 对比:
    国内金融公司若已上 HashiCorp Vault,可用 Spring Cloud Vault 做动态秘钥,避免 Secret 长期驻留 etcd;但 Vault 需要双边网络打通,configtree 方案对存量集群 0 侵入。
  3. 灰度发布:
    结合 Argo Rollout,在 analysisTemplate 里校验新 Secret 挂载后数据源连通性,不通则自动回滚,把配置错误拦截在流量接入前。