gpt4 book ai didi

java - 如何设置不需要凭据的 Localstack 容器?

转载 作者:行者123 更新时间:2023-12-05 07:17:05 31 4
gpt4 key购买 nike

我有以下代码片段,应该在 AWS Lambda 函数中运行:

AWSSecretsManager client = AWSSecretsManagerClientBuilder.standard().withRegion(AWS_REGION).build();
GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest().withSecretId(SECRET_NAME);
GetSecretValueResult secretValue = client.getSecretValue(getSecretValueRequest);

由于 lambda 函数将在与 secret 管理器相同的 VPC 中运行,因此我不必为其提供凭证(AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEY)。

我将 Localstack 与 Testcontainers 一起用于集成测试,并在测试设置中设置 secret ,如下所示:

AWSSecretsManager secretsManager = AWSSecretsManagerClientBuilder.standard()
.withEndpointConfiguration(secretsmanager.getEndpointConfiguration(SECRETSMANAGER))
.withCredentials(secretsmanager.getDefaultCredentialsProvider())
.build();
String secretString = "{'engine':'mysql','port':" + mysql.getMappedPort(3306) + ",'host':'" + mysql.getContainerIpAddress() + "'}";
CreateSecretRequest request = new CreateSecretRequest().withName("aurora")
.withSecretString(secretString)
.withRequestCredentialsProvider(secretsmanager.getDefaultCredentialsProvider());
secretsManager.createSecret(request);

现在测试崩溃并报错:

com.amazonaws.services.secretsmanager.model.AWSSecretsManagerException: 
The security token included in the request is invalid.
(Service: AWSSecretsManager;
Status Code: 400; Error Code:
UnrecognizedClientException;
Request ID: ...

这里也是测试中使用的localstack容器的定义:

@ClassRule
public static LocalStackContainer secretsmanager = new LocalStackContainer("0.10.4")
.withServices(LocalStackContainer.Service.SECRETSMANAGER)
.withEnv("DEFAULT_REGION", "eu-west-1")
.withExposedPorts(4584);

我如何配置 LocalStackContainer 以在不进行任何凭据验证的情况下接受请求?

最佳答案

假设您是一个合理的 java 开发人员,更喜欢 spring boot 测试和 junit5 而不是替代品,@DynamicPropertySource 在这里会非常方便

private static final LocalStackContainer LOCALSTACK = ...;

@DynamicPropertySource
static void setCredentials(DynamicPropertyRegistry registry) {
var credentials = LOCALSTACK.getDefaultCredentialsProvider().getCredentials();
registry.add("cloud.aws.region.static", () -> "eu-central-1");
registry.add("cloud.aws.credentials.access-key", () -> credentials.getAWSAccessKeyId());
registry.add("cloud.aws.credentials.secret-key", () -> credentials.getAWSSecretKey());
registry.add("cloud.aws.s3.endpoint", () -> LOCALSTACK.getEndpointOverride(S3));
}

另外请仔细检查您是否覆盖了您所依赖的端点(在我的示例中为 s3),否则您可能会请求真正的 AWS API 而不是容器化的 API

关于java - 如何设置不需要凭据的 Localstack 容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58914341/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com