属性来源
Vault 可以以多种不同的方式使用。一个特定的用例是使用Vault 来存储加密属性。Spring Vault 支持 Vault 作为属性source 来使用 Spring 的 PropertySource 抽象获取配置属性。
您可以在其他属性源中引用存储在 Vault 中的属性,也可以将值注入与@Value(…). 引导需要存储在 Vault 内部的数据的 Bean 时需要特别注意。 一个VaultPropertySource必须在该时初始化才能从 Vault 检索属性。 |
| Spring Boot/Spring Cloud 用户可以从 Spring Cloud Vault 的配置集成中受益,该集成在应用程序启动期间初始化各种属性源。 |
注册VaultPropertySource
Spring Vault 提供了一个VaultPropertySource与 Vault 一起使用以获取 性能。 它使用嵌套的data元素来公开存储的属性,并在 Vault 中加密。
ConfigurableApplicationContext ctx = new GenericApplicationContext();
MutablePropertySources sources = ctx.getEnvironment().getPropertySources();
sources.addFirst(new VaultPropertySource(vaultTemplate, "secret/my-application"));
在上面的代码中,VaultPropertySource已以最高优先级添加在搜索中。如果它包含“foo”属性,则将检测到并返回它在任何之前foo属性PropertySource.MutablePropertySources公开了许多允许精确作一组属性源。
@VaultPropertySource
这@VaultPropertySource注释提供了一个方便的声明性机制,用于添加PropertySource到 Spring 的Environment与@Configuration类。
@VaultPropertySource采用 Vault 路径,例如secret/my-application并将存储在节点上的数据公开在PropertySource.@VaultPropertySource支持与租约关联的密钥的租约续订(即来自mysql后端)和终端上的凭据轮换租约到期。默认情况下,租约续订处于禁用状态。
{
// …
"data": {
"database": {
"password": ...
},
"user.name": ...,
}
// …
}
@VaultPropertySource@Configuration
@VaultPropertySource("secret/my-application")
public class AppConfig {
@Autowired Environment env;
@Bean
public TestBean testBean() {
TestBean testBean = new TestBean();
testBean.setUser(env.getProperty("user.name"));
testBean.setPassword(env.getProperty("database.password"));
return testBean;
}
}
@VaultPropertySource使用凭据轮换和前缀@Configuration
@VaultPropertySource(value = "aws/creds/s3-access",
propertyNamePrefix = "aws.",
renewal = Renewal.ROTATE)
public class AppConfig {
// provides aws.access_key and aws.secret_key properties
}
从中获得的秘密generic秘密后端与 TTL (refresh_interval),但不是租约 Id。Spring Vault 的PropertySource在达到其 TTL 时轮换通用密钥。 |
您可以使用@VaultPropertySource从版本化的键值后端获取最新的密钥版本。确保不包含data/路径中的段。 |
任何${…}占位符@VaultPropertySourcepath 是针对已针对环境注册的属性源集进行解析的,如以下示例所示:
@VaultPropertySource使用占位符的路径@Configuration
@VaultPropertySource(value = "aws/creds/${my.placeholder:fallback/value}",
propertyNamePrefix = "aws.",
renewal = Renewal.ROTATE)
public class AppConfig {
}
假设my.placeholder存在于已注册的属性源之一(例如,系统属性或环境变量)中,则占位符将解析为相应的值。如果没有,则fallback/value用作默认值。如果未指定默认值并且无法解析属性,则IllegalArgumentException被抛出。
在某些情况下,严格控制可能不可能或不切实际使用时的属性来源排序@VaultPropertySource附注。 例如,如果@Configuration上述类是通过component-scanning 注册的,因此很难预测顺序。在这种情况下 - 如果覆盖很重要 - 建议user 回退到使用编程 PropertySource API。 看ConfigurableEnvironment和MutablePropertySources了解详情。