简体   繁体   中英

How to create a new AWS instance using AWS Java SDK

I'm trying to create a new AWS EC2 instance using the AWS Java SDK but getting "Value () for parameter groupId is invalid. The value cannot be empty" . Here is my code:

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);

Any suggestions?

You might need to add a VPC details also .

PrivateIpAddresses ,Monitoring are among other required fields.

I would recommend you to try creating EC2 Instance manually using AWS Console and see what are the required parameters it is asking?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM