admin管理员组

文章数量:1332339

I'm tasked with writing a file into our S3 bucket from java.

I have set up the IAM role. I have a certificate, a private key, a trust-anchor-arn, a profile-arn, and a role-arn.

I can then make an S3Client using a ProcessCredentialsProvider that calls out to aws_signing_helper, which returns json that includes fields for AccessKeyId, SessionToken, etc. This works.

I do not want to call out to an external process. There doesn't seem to be a way using pure java to make the API calls.

Is it possible to get the credentials without calling out to an external program? If so, how?

I'm tasked with writing a file into our S3 bucket from java.

I have set up the IAM role. I have a certificate, a private key, a trust-anchor-arn, a profile-arn, and a role-arn.

I can then make an S3Client using a ProcessCredentialsProvider that calls out to aws_signing_helper, which returns json that includes fields for AccessKeyId, SessionToken, etc. This works.

I do not want to call out to an external process. There doesn't seem to be a way using pure java to make the API calls.

Is it possible to get the credentials without calling out to an external program? If so, how?

Share Improve this question edited Nov 21, 2024 at 21:19 Gord asked Nov 20, 2024 at 20:26 GordGord 155 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

These concepts are explained in the AWS SDK for Java V2 Developer Guide. See this topic:

Configure SDK authentication

Once you select a credentials provider, you can create a S3AsyncClient to place a file into an S3 bucket.

/**
     * Uploads a local file to an AWS S3 bucket asynchronously.
     *
     * @param bucketName the name of the S3 bucket to upload the file to
     * @param key        the key (object name) to use for the uploaded file
     * @param objectPath the local file path of the file to be uploaded
     * @return a {@link CompletableFuture} that completes with the {@link PutObjectResponse} when the upload is successful, or throws a {@link RuntimeException} if the upload fails
     */
    public CompletableFuture<PutObjectResponse> uploadLocalFileAsync(String bucketName, String key, String objectPath) {
        PutObjectRequest objectRequest = PutObjectRequest.builder()
            .bucket(bucketName)
            .key(key)
            .build();

        CompletableFuture<PutObjectResponse> response = getAsyncClient().putObject(objectRequest, AsyncRequestBody.fromFile(Paths.get(objectPath)));
        return response.whenComplete((resp, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to upload file", ex);
            }
        });
    }

credentails file

[default]
aws_access_key_id = <Value>
aws_secret_access_key = <Value>
region = us-east-1

Once you setup that file, your AWS Service clients will pick up your keys.

本文标签: amazon web servicesAWS S3 credentials in javaStack Overflow