User guide

questRequest);
If you want to ensure that all instances within a request are launched in the same Availability Zone, and
you don't care which one, you can leverage Availability Zone groups. An Availability Zone group is a label
that groups a set of instances together in the same Availability Zone. All instances that share an Availability
Zone group and are fulfilled at the same time will start in the same Availability Zone. An example of how
to set an Availability Zone group follows.
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 5 x t1.micro instance with a bid price of $0.03.
20 requestRequest.setSpotPrice("0.03");
requestRequest.setInstanceCount(Integer.valueOf(5));
// Set the availability zone group.
requestRequest.setAvailabilityZoneGroup("ADVANCED-DEMO-AZ-GROUP");
25
// Set up 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 Amazon Linux AMI id or another
// of your choosing.
30 LaunchSpecification launchSpecification = new LaunchSpecification();
launchSpecification.setImageId("ami-8c1fece5");
launchSpecification.setInstanceType("t1.micro");
// Add the security group to the request.
35 ArrayList<String> securityGroups = new ArrayList<String>();
securityGroups.add("GettingStartedGroup");
launchSpecification.setSecurityGroups(securityGroups);
// Add the launch specification.
40 requestRequest.setLaunchSpecification(launchSpecification);
// Call the RequestSpotInstance API.
RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(re
questRequest);
Version v1.0.0
53
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management