Setting up an AWS scope programmatically
I am using aws-java-sdk version 1.11.104. According to AWS credentials, the default scope is us-east-1
however when I do not set the scope manually when I create the tenant, for example:
AWSCredentialsProvider awsCredentialsProvider =
new AWSStaticCredentialsProvider(new BasicAWSCredentials(awsAccessKey, awsSecretKey));
AmazonS3 s3Client =
AmazonS3ClientBuilder.standard().withCredentials(awsCredentialsProvider).build();
I am getting this error:
com.amazonaws.SdkClientException:
Unable to find a region via the region provider chain.
Must provide an explicit region in the builder or setup environment to supply a region.
-
Why isn't the default scope being used?
I tried adding the following before my code above, but it still doesn't work.
System.setProperty(SDKGlobalConfiguration.AWS_REGION_ENV_VAR, "us-east-1");
-
How do I programmatically configure my AWS Region? (I would like to set it at runtime for all classes in my project).
Thank you.
Edit:
I know what I can use .withRegion()
in the client builder, but I was expecting a default scope or region selected from an environment variable via the default vendor chain.
source to share
I was expecting default scope or region selected from environment variable via default provider chain.
Yes, when I read the code, it has no default scope:
-
AmazonEC2ClientBuilder
continues (up slightly)AwsClientBuilder
. -
AwsClientBuilder
uses by defaultDefaultAwsRegionProviderChain
. -
DefaultAwsRegionProviderChain
uses 3 mechanisms for scoping:-
AwsEnvVarOverrideRegionProvider
which looks into an environment variableAWS_REGION
that you cannot set at runtime. Or shouldn't (see below). -
AwsProfileRegionProvider
which reads it from your AWS profile. -
InstanceMetadataRegionProvider
which is trying to find the EC2 instance you are on and take over its scope.
-
- Why isn't the default scope being used? (see these aws docs )
I have not seen in the code any reference to us-east-1
in the source other than AwsHostNameUtils.parseRegionName(...)
. I'm not sure where this is being used.
System.setProperty (SDKGlobalConfiguration.AWS_REGION_ENV_VAR, "us-east-1");
Yes, environment is not the same as a system property. There are gross hacks that allow you to change environment variables at runtime, but the user is wary.
source to share
I have a similar scenario, we are building an AWS abstraction layer so programmers don't need to touch any AWS code. And I also had problems with unit testing and tried to set a variable AWS_REGION
with System.setProperty(String, String)
.
The solution I found is to instead set the property aws.region . The AwsSystemPropertyRegionProvider class is in the "region provider chain" and will receive a value from this property.
I set the property before my tests to @BeforeClass
:
@BeforeClass
public static void setUp() {
System.setProperty("aws.region", "us-west-2");
}
Hope it helps.
source to share