属性源
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
property 在任何其他PropertySource
.MutablePropertySources
公开了许多允许精确
作属性源集。
@VaultPropertySource
这@VaultPropertySource
注解提供了一个方便且声明性的
添加PropertySource
到 Spring 的Environment
与@Configuration
类。
@VaultPropertySource
采用 Vault 路径,例如secret/my-application
并将存储在节点中的数据公开在PropertySource
.@VaultPropertySource
支持与租约关联的密钥的租约
(即来自mysql
backend) 和终端上的凭证轮换
租约到期。默认情况下,租约续订处于禁用状态。
{
// …
"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 secret 后端与 TTL (refresh_interval ),而不是租约 ID 的PropertySource 在达到其 TTL 时轮换通用密钥。 |
您可以使用@VaultPropertySource 从受版本控制的 Key-Value 后端获取最新的密钥版本。确保不包含data/ 段。 |
任何${…}
placeholder 存在于@VaultPropertySource
path 根据已针对环境注册的属性源集进行解析,如下例所示:
@VaultPropertySource
使用占位符的路径@Configuration
@VaultPropertySource(value = "aws/creds/${my.placeholder:fallback/value}",
propertyNamePrefix = "aws.",
renewal = Renewal.ROTATE)
public class AppConfig {
}
假设my.placeholder
存在于已注册的属性源之一(例如,系统属性或环境变量)中,则占位符将解析为相应的值。
如果不是,则fallback/value
用作默认值。
如果未指定 default 且无法解析属性,则IllegalArgumentException
被抛出。
在某些情况下,严格控制可能是不可能的或不切实际的
使用@VaultPropertySource
附注。
例如,如果@Configuration
以上类是通过
component-scanning 中,顺序很难预测。
在这种情况下 - 如果覆盖很重要 - 建议将
用户回退到使用编程式 PropertySource API。
看ConfigurableEnvironment
和MutablePropertySources
了解详情。