User guide
DescribeSpotInstanceRequestsResult describeResult = ec2.describeS
potInstanceRequests(describeRequest);
175 List<SpotInstanceRequest> describeResponses = describeResult.get
SpotInstanceRequests();
// Look through each request and determine if they are all
// in the active state.
for (SpotInstanceRequest describeResponse : describeResponses) {
180 // If the state is open, it hasn't changed since we
// attempted to request it. There is the potential
// for it to transition almost immediately to closed or
// canceled so we compare against open instead of active.
if (describeResponse.getState().equals("open")) {
185 anyOpen = true;
break;
}
// Add the instance id to the list we will
190 // eventually terminate.
instanceIds.add(describeResponse.getInstanceId());
}
} catch (AmazonServiceException e) {
// If we have an exception, ensure we don't break out
195 // of the loop. This prevents the scenario where there
// was blip on the wire.
anyOpen = true;
}
200 try {
// Sleep for 60 seconds.
Thread.sleep(60*1000);
} catch (Exception e) {
// Do nothing because it woke up early.
205 }
} while (anyOpen);
//========================================================//
//============= Tag the Spot Instances ====================//
210 //========================================================//
// Create the list of tags we want to create
ArrayList<Tag> instanceTags = new ArrayList<Tag>();
instanceTags.add(new Tag("keyname1","value1"));
215
// Create a tag request for instances.
CreateTagsRequest createTagsRequest_instances = new CreateTagsRequest();
createTagsRequest_instances.setResources(instanceIds);
createTagsRequest_instances.setTags(instanceTags);
220
// Try to tag the Spot instance started.
try {
ec2.createTags(createTagsRequest_instances);
} catch (AmazonServiceException e) {
225 // Write out any exceptions that may have occurred.
System.out.println("Error terminating instances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
Version v1.0.0
61
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management