【问题标题】:How to read secret key and value from Kubernetes volume mount using Spring Boot如何使用 Spring Boot 从 Kubernetes 卷挂载中读取密钥和值
【发布时间】:2022-01-21 00:32:35
【问题描述】:
我在 pod 中安装了一个包含用户名和密码的卷。
如果我这样做了,
kubectl exec -it my-app -- cat /mnt/secrets-store/git-token
{"USERNAME":"usernameofgit","PASSWORD":"dhdhfhehfhel"}
我想使用 spring boot 读取这个 USERNAME 和 PASSWORD。因为我是新手,有人可以帮我解决这个问题吗。
【问题讨论】:
标签:
spring
spring-boot
kubernetes
spring-boot-maven-plugin
spring-boot-admin
【解决方案1】:
假设:
- 文件 (git_token) 格式是固定的 (JSON)。
- 文件可能没有扩展后缀 (.json)。
...我们有一些问题!
我试过2.3.5. Importing Extensionless Files 喜欢:
spring.config.import=/mnt/secrets-store/git-token[.json]
但它只适用于 YAML/.properties!(使用 spring-boot:2.6.1 测试))
同样适用于2.8. Type-safe Configuration Properties。 ;(;(
在 Spring-Boot 中,我们可以(开箱即用)提供 JSON-config(仅)作为 SPRING_APPLICATION_JSON 环境/命令行属性,它必须是 json 字符串,并且不能是路径或文件(还)。
提议的 (baeldung) 文章展示了“启用 JSON 属性”的方法,但它是一篇很长的文章,有很多细节,展示了很多代码,并且有很多不足/过时(@ConfigurationProperties 上的@Component 相当“非传统”)。 .
我尝试了以下方法(在本地机器上,在上述假设下):
package com.example.demo;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Value("""
#{@jacksonObjectMapper.readValue(
T(java.nio.file.Files).newInputStream(
T(java.nio.file.Path).of('/mnt/secrets-store/git-token')),
T(com.example.demo.GitInfo)
)}""" // watch out with @Value and text blocks! (otherwise: No converter found capable of converting from type [com.example.demo.GitInfo] to type [java.lang.String])
)
GitInfo gitInfo;
@Bean
CommandLineRunner runner() {
return (String... args) -> {
System.out.println(gitInfo.getUsername());
System.out.println(gitInfo.getPassword());
};
}
}
@Data
class GitInfo {
@JsonProperty("USERNAME")
private String username;
@JsonProperty("PASSWORD")
private String password;
}
在板载(仅)spring-boot-starter-web 和 lombok 的情况下,它会打印预期的输出。
解决方案大纲:
- 为此的一个pojo
- 一个(疯狂的)
@Value——(Spring-)表达式,涉及:
【解决方案2】:
安装完卷后,您需要做的就是从 Spring Boot 应用程序中读取 JSON 文件。我推荐阅读Load Spring Boot Properties From a JSON File。
简而言之,您可以创建一个与您的 JSON 文件对应的类,就像这样。
@Component
@PropertySource("file:/mnt/secrets-store/git-token")
@ConfigurationProperties
public class GitToken {
private String username;
private String password;
// getters and setters
}
然后,您需要将其添加到 componentScan 并且您可以自动连接您的课程。