我应该如何将密码从AWS Secret Manager拉到春季?

时间:2018-12-10 18:44:42

标签: spring amazon-web-services spring-boot spring-properties

我想根据我的属性文件中设置的密钥名称从AWS Secret Manager中检索数据库密码。但是,似乎无法像我希望的那样从application.yml文件中读取属性。在下面的代码中,my.project.aws-secretmy.project.region都被检索为null

我是否期望此时可以检索到这些属性?这是实现此目标的正确方法,还是有更简单的方法?

这是代码。我目前正在尝试使用ApplicationListener来做到这一点,但是我也看到了将其实现为EnvironmentPostProcessor的相同问题:

ApplicationListener

public class DatasourceAwsProperties implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment environment = event.getEnvironment();
        Properties props = new Properties();

        String datasourcePassword = environment.getProperty("my.project.aws-secret"); // why is this null?
        String awsRegion = environment.getProperty("my.project.region"); // why is this null?

        String secret = getSecret(datasourcePassword, awsRegion);

        MapPropertySource newProperties = new MapPropertySource("newProperties", ImmutableMap.of("spring.datasource.password", secret));

        environment.getPropertySources().addLast(newProperties);
    }

    public static String getSecret(String secretName, String region) {
        // gets secret from aws
}

application.yml

lots:
  of:
    properties: ...

my:
  project:
    aws-secret: the-name-of-the-secret-in-aws
    region: us-east-1

0 个答案:

没有答案