User guide

LaunchSpecification for the request, which includes the instance type, AMI ID, and security group
you want to use. Once the request is populated, you call the requestSpotInstances method on the
AmazonEC2Client object. The following example shows how to request a Spot Instance.
1 // Retrieves the credentials from a AWSCrentials.properties file.
AWSCredentials credentials = null;
try {
credentials = new PropertiesCredentials(
5 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());
System.exit(-1);
10 }
// 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.
requestRequest.setSpotPrice("0.03");
20 requestRequest.setInstanceCount(Integer.valueOf(1));
// Setup the specifications of the launch. This includes the
// instance type (e.g. t1.micro) and the latest Amazon Linux
// AMI id available. Note, you should always use the latest
25 // Amazon Linux AMI id or another of your choosing.
LaunchSpecification launchSpecification = new LaunchSpecification();
launchSpecification.setImageId("ami-8c1fece5");
launchSpecification.setInstanceType("t1.micro");
30 // Add the security group to the request.
ArrayList<String> securityGroups = new ArrayList<String>();
securityGroups.add("GettingStartedGroup");
launchSpecification.setSecurityGroups(securityGroups);
35 // Add the launch specifications to the request.
requestRequest.setLaunchSpecification(launchSpecification);
// Call the RequestSpotInstance API.
RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(re
questRequest);
Running this code will launch a new Spot Instance Request.There are other options you can use to
configure your Spot Requests.To learn more, please visit the Java Developers: Advanced Spot Features
Tutorials or the RequestSpotInstances API in the SDK for Java.
Note
You will be charged for any Spot Instances that are actually launched, so make sure that you
cancel any requests and terminate any instances you launch to reduce any associated fees.
Version v1.0.0
41
AWS SDK for Java Developer Guide
Tutorial: Amazon EC2 Spot Instances