首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么服务无法读取AWS ECS Fargate中的AWS Secrets Manager

为什么服务无法读取AWS ECS Fargate中的AWS Secrets Manager
EN

Stack Overflow用户
提问于 2021-09-22 13:34:39
回答 1查看 310关注 0票数 0

我正在AWS ECS中部署一个springboot2.5.0 gradle项目,它必须在启动时读取AWS Secrets Manager。我已经写了这两个文件来阅读aws中的Secrets Manager。但是该服务仍然无法从管理器读取这些值。任何提示都会有所帮助。ECS容器中的错误

代码语言:javascript
运行
复制
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tokenManager': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'moa.aws.secrets.oidc.introspectUrl' in value "${moa.aws.secrets.oidc.introspectUrl}"

2个文件

代码语言:javascript
运行
复制
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SecretsManagerBootstrapConfiguration {

    @Bean
    public SecretsManagerPropertySourceLocator awsSecretsManager(
            @Value("${aws.secrets:}") final String[] allowedSecrets) {
        return new SecretsManagerPropertySourceLocator(allowedSecrets);
    }
}

代码语言:javascript
运行
复制
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.bootstrap.config.PropertySourceLocator;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

import com.fasterxml.jackson.databind.ObjectMapper;


public class SecretsManagerPropertySourceLocator implements PropertySourceLocator {

    private static final Logger LOGGER = LoggerFactory.getLogger(SecretsManagerPropertySourceLocator.class);
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    private String[] allowedSecrets;

    public SecretsManagerPropertySourceLocator(
            final String[] secrets) {
        this.allowedSecrets = secrets;
        for (String secret : allowedSecrets) {
             LOGGER.debug("allowed secrets ::===> " + secret);
            
        }

    }

    /**
     * @param environment the current Environment
     * @return a PropertySource or null if there is none
     * @throws IllegalStateException if there is a fail fast condition
     */
    @Override
    public PropertySource<?> locate(Environment environment) {

        final CompositePropertySource propertySource = new CompositePropertySource("aws-secrets-store");

        final MutablePropertySources sources = ((AbstractEnvironment) environment).getPropertySources();
        for (String secret : allowedSecrets
        ) {
            StreamSupport.stream(sources.spliterator(), false)
                    .filter(ps -> ps instanceof EnumerablePropertySource)
                    .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames())
                    .flatMap(Arrays::stream)
                    .distinct()
                    .filter(prop -> (prop.contains(secret)))
                    .forEach(prop -> {
                        propertySource.addPropertySource(new MapPropertySource(secret, jsonToMap(prop, environment.getProperty(prop))));

                    });
        }

        return propertySource;
    }

    private Map<String, Object> jsonToMap(final String name, String jsonString) {
    
        try {
            final Map<String, Object> map = OBJECT_MAPPER.readValue(jsonString, Map.class);
            return map.entrySet()
                    .stream()
                    .collect(
                            Collectors.toMap(
                                    e -> name.replaceAll("/", ".") + '.' + e.getKey(),
                                    Map.Entry::getValue
                            ));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2021-09-22 14:13:46

我在上面的代码示例中没有看到您的Secret Manager代码。您如何调用此AWS服务?最佳实践(来自Java应用程序)是使用Secret Manager V2 Java API。您可以在Spring应用程序中使用此Java API。要从这个服务中获取一个秘密--使用下面这样的Java V2代码:

代码语言:javascript
运行
复制
package com.example.secrets;

//snippet-start:[secretsmanager.java2.get_secret.import]
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse;
import software.amazon.awssdk.services.secretsmanager.model.SecretsManagerException;
//snippet-end:[secretsmanager.java2.get_secret.import]

/**
 * To run this AWS code example, ensure that you have setup your development environment, including your AWS credentials.
 *
 * For information, see this documentation topic:
 *
 *https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class GetSecretValue {

    public static void main(String[] args) {

        final String USAGE = "\n" +
                "Usage:\n" +
                "    GetSecretValue  <secretName> \n\n" +
                "Where:\n" +
                "    secretName - the name of the secret (for example, tutorials/MyFirstSecret). \n";

        if (args.length != 1) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String secretName = args[0];
        Region region = Region.US_EAST_1;
        SecretsManagerClient secretsClient = SecretsManagerClient.builder()
                .region(region)
                .build();

        getValue(secretsClient, secretName);
        secretsClient.close();
    }

    //snippet-start:[secretsmanager.java2.get_secret.main]
    public static void getValue(SecretsManagerClient secretsClient,String secretName) {

        try {
            GetSecretValueRequest valueRequest = GetSecretValueRequest.builder()
                .secretId(secretName)
                .build();

            GetSecretValueResponse valueResponse = secretsClient.getSecretValue(valueRequest);
            String secret = valueResponse.secretString();
            System.out.println(secret);

        } catch (SecretsManagerException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
    //snippet-end:[secretsmanager.java2.get_secret.main]
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69285330

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档