简体   繁体   中英

How to start and stop an Amazon EC2 instance programmatically in java

How do i start and stop an amazon EC2 instance programmatically using aws-sdk in java?

Any helps are greatly appreciated as I have spent a day while trying to sort this out.

I've recently implemented this functionality within the Bamboo AWS Plugin ; it's Open Source and the code is available on Bitbucket , you can find a complete example how to start/stop/reboot an instance within EC2Task.java (should be a separate class actually, alas ...).

Fortunately this is not complicated at all, for example, an instance can be started like so:

private String startInstance(final String instanceId, AmazonEC2 ec2, final BuildLogger buildLogger)
        throws AmazonServiceException, AmazonClientException, InterruptedException
{
    StartInstancesRequest startRequest = new StartInstancesRequest().withInstanceIds(instanceId);
    StartInstancesResult startResult = ec2.startInstances(startRequest);
    List<InstanceStateChange> stateChangeList = startResult.getStartingInstances();
    buildLogger.addBuildLogEntry("Starting instance '" + instanceId + "':");

    // Wait for the instance to be started
    return waitForTransitionCompletion(stateChangeList, "running", ec2, instanceId, buildLogger); }

BuildLogger is Bamboo specific and waitForTransitionCompletion() is an implementation specific helper to report back on the process/result. The AmazonEC2 ec2 parameter passes the reference to an AmazonEC2Client object by means of the AmazonEC2 interface, which defines all relevant methods (amongst many others), specifically:

If you have already used AWS API , it's simple call on AmazonEC2Client object. Use the following methods

Also, you might be knowing the start/stop mechanism works only for the images with root device backed by EBS.

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