屬性來源
Vault 有許多不同的使用方式。其中一個特定的用例是使用 Vault 儲存加密的屬性。Spring Vault 支援 Vault 作為屬性來源,以使用 Spring 的 PropertySource 抽象概念取得組態屬性。
您可以參考儲存在 Vault 內部的屬性於其他屬性來源,或使用 @Value(…) 進行值注入。當啟動需要儲存在 Vault 內資料的 beans 時,需要特別注意。必須在那時初始化 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
屬性,它將被偵測到並在任何其他 PropertySource
中的任何 foo
屬性之前返回。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 secret 後端取得的密鑰與 TTL (refresh_interval ) 相關聯,但與租約 ID 無關。Spring Vault 的 PropertySource 在達到其 TTL 時輪換通用密鑰。 |
您可以使用 @VaultPropertySource 從版本化的 Key-Value 後端取得最新的密鑰版本。請確保路徑中不包含 data/ 段。 |
@VaultPropertySource
路徑中存在的任何 ${…}
佔位符都會針對已向環境註冊的屬性來源集進行解析,如下例所示
@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
類別是透過元件掃描註冊的,則順序很難預測。在這種情況下 - 且如果覆寫很重要 - 建議使用者退回使用程式化的 PropertySource API。有關詳細資訊,請參閱 ConfigurableEnvironment
和 MutablePropertySources
。