简体   繁体   中英

AWS EC2 Java SDK: Start an instance with custom instance type

I am trying to start an EC2 instance though Java code. I added this maven dependency in my project:

https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-ec2/1.11.308

It provides me with a class, which can be used to request starting an instance. The code is as follows:

StartInstancesRequest startReq = new StartInstancesRequest()
                .withInstanceIds(instanceID);

ec2Client.startInstances(startReq);

But, there is no with* method in StartInstancesRequest class, which takes instance type as input.

Can anyone please tell me how can I specify instance type too?

The startInstances call is really used to start instances that are in the stopped state - that's why it takes instance ids.

I use runInstances when I want to customize the instance. With it you can do things like:

RunInstancesRequest runInstancesRequest = new RunInstancesRequest();

runInstancesRequest.withImageId("ami-4b814f22")
                   .withInstanceType("m1.small")
                   .withMinCount(1)
                   .withMaxCount(1)
                   .withKeyName("my-key-pair")
                   .withSecurityGroups("my-security-group");

(taken directly from Run an Amazon EC2 Instance ).

This has tons of customization that you can use to configure the new instance.

If you don't want to use AMI and use the runInstances, why not change the instance type before you start your instance as follows

// Change the instance type
ModifyInstanceAttributeRequest modReq = new ModifyInstanceAttributeRequest()
.withInstanceType(instanceType)
.withInstanceId(instanceID);

ec2client.modifyInstanceAttribute(modReq);

// Then start your instance
StartInstancesRequest startReq = new StartInstancesRequest()
            .withInstanceIds(instanceID);

ec2Client.startInstances(startReq);

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