配置加载:在应用程序启动时,Spring Cloud Vault 会根据配置文件中的设置连接到 Vault 服务器,并从指定路径加载配置数据。
属性注入:加载的配置数据会被注入到 Spring 的 Environment
中,应用程序可以通过 @Value
注解或 Environment
对象访问这些配置属性。
安全访问:通过使用 Vault 的访问控制策略,确保只有授权的应用程序和用户能够访问特定的配置数据。
docker run --cap-add=IPC_LOCK -e 'VAULT_DEV_ROOT_TOKEN_ID=root' -e 'VAULT_DEV_LISTEN_ADDRESS=0.0.0.0:8200' -p 8200:8200 --name=vault -d vault:1.13.3
env config
export VAULT_TOKEN="hvs.9rUli4rwArRrAUYkVp0NVUlu"
export VAULT_ADDR="http://0.0.0.0:8200"
init datas
vault kv put secret/application example.username=myuser example.password=mypassword
you can init by using web UI
Spring Boot读取vault里面的值
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springcloud-demo</artifactId>
<groupId>com.et</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-vault</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Cloud Vault Config -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-vault-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-vault-config-databases</artifactId>
</dependency>
<!-- Spring Boot Starter Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
package com.et;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
class SecretController {
@Value("${example.username}")
private String username;
@Value("${example.password}")
private String password;
@GetMapping("/secrets")
public String getSecrets() {
return "Username: " + username + ", Password: " + password;
}
}
package com.et;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class VaultDemoApplication {
public static void main(String[] args) {
SpringApplication.run(VaultDemoApplication.class, args);
}
}
logging:
level:
org.springframework.cloud.vault: DEBUG
spring:
application:
name: vault-demo
config:
import: vault://
cloud:
vault:
uri: http://localhost:8200
token: hvs.9rUli4rwArRrAUYkVp0NVUlu
kv:
enabled: true
backend: secret
default-context: application
Username: harries, Password: 123456