Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 566
diya Avatar asked Jan 21 '12 06:01

diya


People also ask

How do I stop and start Amazon EC2 Instances?

In the navigation pane, choose Instances and select the instance. Choose Instance state, Stop instance. If this option is disabled, either the instance is already stopped or its root device is an instance store volume. When prompted for confirmation, choose Stop.


1 Answers

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:

  • StartInstances()
  • StopInstances()
  • RebootInstances()
like image 98
Steffen Opel Avatar answered Sep 21 '22 15:09

Steffen Opel