【问题标题】:How to get spring datasoure properties value from AWS parameter store?如何从 AWS 参数存储中获取 spring 数据源属性值?
【发布时间】:2020-03-15 20:34:21
【问题描述】:

在我的 Spring Boot 应用程序中,我在 application.properties 文件中维护了 spring.datasource.url。我需要保护 URL/用户和密码,并且这些值在 AWS 参数存储中可用。我引用了这个doc 只是简单地添加了对 (spring-cloud-starter-aws-parameter-store-config) 启动模块的依赖来激活支持。我实际上不知道如何维护配置参数以及如何将参数存储值检索到我的项目中。

如何在不使用以下 (application.properties) 属性中的硬编码值的情况下实现此目的?

spring.datasource.url= url
spring.datasource.username = root
spring.datasource.password = xxxxxx

【问题讨论】:

    标签: java spring-boot aws-parameter-store


    【解决方案1】:

    要在 Spring Boot 应用程序中将 AWS System Manager Parameter Store 用作 PropertySource,请执行以下步骤。

    将以下依赖添加到build.gradle

    dependencyManagement {
        imports {
            mavenBom 'org.springframework.cloud:spring-cloud-dependencies:Greenwich.SR3'
        }
    }
    
    dependencies {
        implementation 'org.springframework.cloud:spring-cloud-starter-aws-parameter-store-config'
    }
    

    将指定应用程序名称的属性添加到src/main/resources/bootstrap.properties

    spring.application.name=my-app
    

    默认情况下,Spring Cloud AWS 依赖于 DefaultAWSCredentialsProviderChainDefaultAwsRegionProviderChain

    如果应用程序不是在 EC2/Fargate 实例上运行,请通过设置以下环境变量来配置 AWS 凭证和区域:

    AWS_ACCESS_KEY_ID=
    AWS_SECRET_ACCESS_KEY=
    AWS_REGION=us-west-1
    

    或者确保您拥有有效的 AWS 配置文件 ~/.aws/credentials~/.aws/config

    在 AWS System Manager Parameter Store 中定义以下属性:

    /config/my-app/spring.datasource.url
    /config/my-app/spring.datasource.username
    /config/my-app/spring.datasource.password
    

    【讨论】:

    • 是否可以处理来自 AWS 参数存储的 AWS 凭证?因为我们处于临时环境中,所以我们不使用 EC2 机器上的配置
    • AWS 凭证和区域必须在环境变量、系统属性或文件 (~/.aws/credentials) 中指定。见docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/…
    • 如果应用程序在 aws cloud(EC2/Fargate) 中运行,那么 spring-cloud 足够智能,可以获取 aws 凭据。我们不需要配置任何环境变量或 ~/.aws/* 。确保添加了 spring-cloud-aws-autoconfigure 依赖项
    • Spring Cloud 不配置 AWS 凭证,它依赖于 DefaultAWSCredentialsProviderChain,它会尽力找到 AWS 凭证提供者。请参阅 Javadoc。
    猜你喜欢
    • 1970-01-01
    • 2020-04-26
    • 2020-06-05
    • 2021-01-04
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多