如何使用AWS Java SDK创建新的AWS实例

时间:2017-05-27 17:21:32

标签: java amazon-web-services amazon-ec2

我尝试使用AWS Java SDK创建新的AWS EC2实例,但获取参数groupId的" Value()无效。该值不能为空" 。这是我的代码:

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(Regions.US_WEST_2)
    .build();

}

RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
String ami_id = "ami-efd0428f";     //ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-20170414
Collection<String> securityGroups = new ArrayList<>();
securityGroups.add("launch-wizard-1");
securityGroups.add("sg-9405c2f3");
runInstancesRequest.withImageId(ami_id) 
    .withInstanceType("t2.medium")
    .withMinCount(1)
    .withMaxCount(1)
    .withKeyName("MyKeyName")
    .withSecurityGroups(securityGroups);

RunInstancesResult run_response = ec2.runInstances(runInstancesRequest);  // fails here!

String instance_id = run_response.getReservation().getReservationId();

Tag tag = new Tag()
    .withKey("Name")
    .withValue(tfCompanyName.getText());
Collection<Tag> tags = new ArrayList<>();
tags.add(tag);

CreateTagsRequest tag_request = new CreateTagsRequest();
tag_request.setTags(tags);

CreateTagsResult tag_response = ec2.createTags(tag_request);

String s = String.format("Successfully started EC2 instance %s based on AMI %s",instance_id, ami_id);
System.out.println(s);

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您可能还需要添加VPC详细信息。

PrivateIpAddresses,监控是其他必填字段。

我建议您尝试使用AWS控制台手动创建EC2实例,看看它要求的参数是什么?