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

20,423

Solution 1

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:

Solution 2

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.

Share:
20,423

Related videos on Youtube

diya
Author by

diya

Updated on January 22, 2020

Comments

  • diya
    diya over 4 years

    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.

Related