使用 AWS java SDK 来 return 带有环境变量的 AmazonEC2?

Using the AWS java SDK to return a AmazonEC2 with environment variables?

我已成功使用 Java SDK,使用 ~/.aws/credentials 文件返回 AmazonEc2 实例,如下所示:

private AmazonEC2 getEc2Client() {
    AWSCredentials credentials = new ProfileCredentialsProvider().getCredentials();

    AmazonEC2 amazonEC2 = new AmazonEC2Client(credentials);
    Region govCloud = Region.getRegion(Regions.GovCloud);
    amazonEC2.setRegion(govCloud);

    return amazonEC2;
}

但是我现在想切换到使用环境变量,而不是文件。我设置了我的环境变量,但我不知道用什么代码来做。示例 (https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html) 显示如下:

AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                       .withCredentials(new EnvironmentVariableCredentialsProvider())
                       .build();

但是 returns AmazonS3 而不是 AmazonEC2。我尝试以下操作:

    AmazonEC2 amazonEC2 = AmazonEC2ClientBuilder.standard()
        .withCredentials(new EnvironmentVariableCredentialsProvider())
        .build();

但是没有 "AmazonEC2ClientBuilder"

确实有一个AmazonEC2ClientBuilder

aws-sdk-java samples 中的一些示例用法:

AmazonEC2 ec2 = null;

/*
 * The ProfileCredentialsProvider will return your [default]
 * credential profile by reading from the credentials file located at
 * (~/.aws/credentials).
 */
AWSCredentials credentials = null;
try {
        credentials = new ProfileCredentialsProvider().getCredentials();
} catch (Exception e) {
        throw new AmazonClientException(
                "Cannot load the credentials from the credential profiles file. " +
                "Please make sure that your credentials file is at the correct " +
                "location (~/.aws/credentials), and is in valid format.",
                e);
}

ec2 = AmazonEC2ClientBuilder.standard()
        .withCredentials(new AWSStaticCredentialsProvider(credentials))
        .withRegion("us-west-2")
        .build();

您问题中的代码看起来可以正常工作。