use of com.google.cloud.compute.v1.InsertInstanceRequest in project java-docs-samples by GoogleCloudPlatform.
the class CreatePreemptibleInstance method createPremptibleInstance.
// Send an instance creation request with preemptible settings to the Compute Engine API
// and wait for it to complete.
public static void createPremptibleInstance(String projectId, String zone, String instanceName) throws IOException, ExecutionException, InterruptedException, TimeoutException {
String machineType = String.format("zones/%s/machineTypes/e2-small", zone);
String sourceImage = "projects/debian-cloud/global/images/family/debian-11";
long diskSizeGb = 10L;
String networkName = "default";
try (InstancesClient instancesClient = InstancesClient.create()) {
AttachedDisk disk = AttachedDisk.newBuilder().setBoot(true).setAutoDelete(true).setType(AttachedDisk.Type.PERSISTENT.toString()).setInitializeParams(// Describe the size and source image of the boot disk to attach to the instance.
AttachedDiskInitializeParams.newBuilder().setSourceImage(sourceImage).setDiskSizeGb(diskSizeGb).build()).build();
// Use the default VPC network.
NetworkInterface networkInterface = NetworkInterface.newBuilder().setName(networkName).build();
// Collect information into the Instance object.
Instance instanceResource = Instance.newBuilder().setName(instanceName).setMachineType(machineType).addDisks(disk).addNetworkInterfaces(networkInterface).setScheduling(Scheduling.newBuilder().setPreemptible(true).build()).build();
System.out.printf("Creating instance: %s at %s %n", instanceName, zone);
// Prepare the request to insert an instance.
InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder().setProject(projectId).setZone(zone).setInstanceResource(instanceResource).build();
// Wait for the create operation to complete.
Operation response = instancesClient.insertAsync(insertInstanceRequest).get(3, TimeUnit.MINUTES);
;
if (response.hasError()) {
System.out.println("Instance creation failed ! ! " + response);
return;
}
System.out.printf("Instance created : %s\n", instanceName);
System.out.println("Operation Status: " + response.getStatus());
}
}
Aggregations