Search code examples
spring-bootamazon-s3aws-sdkaws-java-sdk

Access s3 bucket from other region using java aws-java-sdk


I have s3 bucket from ap-south-1 which I have accessing using aws java sdk AmazonS3 amazonS3 = AmazonS3ClientBuilder.standard(). withRegion(Regions.AP_SOUTH_1).defaultClient();

awazonS3.putObject(putObjectRequest);

It was working fine when my service is running in "ap-south-1". Now, when I move the service moved to "ap-south-2" reason same code is giving error.

The ap-south-1 location constraint is incompatible for the region specific endpoint this request was sent to. (Service: Amazon S3; Status Code: 400; Error Code: IllegalLocationConstraintException; Request ID: TTTTDW5T2GF0J28S8; S3 Extended Request ID: l3djAuSl5RXWgSLn12gTnyXyF1P7Q60OAMxTNhyrnmIJxIZ2MjRRzmOMT1hsEW6+KjqA=; Proxy: null)

currently i m using

    `<dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk</artifactId>
        <version>1.12.145</version>
    </dependency>`

I want to access same bucket of ap-south-1 in ap-south-2


Solution

  • The problem is you are using .defaultClient() which I think ignores the Region you set

    Try using .build() instead which Builds a client with the configure properties.

    so

    AmazonS3 amazonS3 = AmazonS3ClientBuilder
                        .standard()
                        .withRegion(Regions.AP_SOUTH_1)
                        .build();
    

    Note, you can also specify the S3 endpoint explicitly, as follows (but the above code is simpler):

    AmazonS3 amazonS3 = AmazonS3ClientBuilder
                        .standard()
                        .withEndpointConfiguration(
                           new EndpointConfiguration("https://s3.ap-south-1.amazonaws.com", "ap-south-1"))
                        .build();