Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in AWS by (19.1k points)

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

Any bits of help is greatly appreciated as I have spent a day while trying to sort this out.

1 Answer

0 votes
by (44.4k points)

This is not very complicated, and this is how an EC2 instance can be started:

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

I found this code which is completely available on Bitbucket and this is the link - EC2.java

Check out these links for more insight and to learn functions about Starting, Stopping, and Rebooting instances. 

Related questions

0 votes
1 answer
Want to get 50% Hike on your Salary?

Learn how we helped 50,000+ professionals like you !

0 votes
1 answer
0 votes
1 answer
asked Jul 8, 2019 in AWS by yuvraj (19.1k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...