使用AWS Java SDK返回带有环境变量的AmazonEC2?

时间:2018-12-05 19:25:47

标签: amazon-web-services amazon-ec2 aws-sdk

我已经成功使用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();

但是这将返回一个AmazonS3而不是一个AmazonEC2。我尝试以下方法:

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

但是没有“ AmazonEC2ClientBuilder”之类的东西

1 个答案:

答案 0 :(得分:1)

确实有一个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();

您问题中的代码似乎可以正常工作。

相关问题