User guide
1
// Retrieves the credentials from an AWSCredentials.properties file.
AWSCredentials credentials = null;
try {
5 credentials = new PropertiesCredentials(
GettingStartedApp.class.getResourceAsStream("AwsCredentials.proper
ties"));
} catch (IOException e1) {
System.out.println("Credentials were not properly entered into AwsCre
dentials.properties.");
System.out.println(e1.getMessage());
10 System.exit(-1);
}
// Create the AmazonEC2Client object so we can call various APIs.
AmazonEC2 ec2 = new AmazonEC2Client(credentials);
15
// Initializes a Spot Instance Request
RequestSpotInstancesRequest requestRequest = new RequestSpotInstances
Request();
// Request 1 x t1.micro instance with a bid price of $0.03.
20 requestRequest.setSpotPrice("0.03");
requestRequest.setInstanceCount(Integer.valueOf(1));
// Set the valid start time to be two minutes from now.
Calendar cal = Calendar.getInstance();
25 cal.add(Calendar.MINUTE, 2);
requestRequest.setValidFrom(cal.getTime());
// Set the valid end time to be two minutes and two hours from now.
cal.add(Calendar.HOUR, 2);
30 requestRequest.setValidUntil(cal.getTime());
// Set up the specifications of the launch. This includes
// the instance type (e.g. t1.micro)
35 // and the latest Amazon Linux AMI id available.
// Note, you should always use the latest Amazon
// Linux AMI id or another of your choosing.
LaunchSpecification launchSpecification = new LaunchSpecification();
launchSpecification.setImageId("ami-8c1fece5");
40 launchSpecification.setInstanceType("t1.micro");
// Add the security group to the request.
ArrayList<String> securityGroups = new ArrayList<String>();
securityGroups.add("GettingStartedGroup");
45 launchSpecification.setSecurityGroups(securityGroups);
// Add the launch specification.
requestRequest.setLaunchSpecification(launchSpecification);
50 // Call the RequestSpotInstance API.
RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(re
questRequest);
Version v1.0.0
51
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management