Search in sources :

Example 1 with InstancesClient

use of com.google.cloud.compute.v1.InstancesClient in project java-docs-samples by GoogleCloudPlatform.

the class CreateInstance method createInstance.

// Create a new instance with the provided "instanceName" value in the specified project and zone.
public static void createInstance(String project, String zone, String instanceName) throws IOException, InterruptedException, ExecutionException {
    // Below are sample values that can be replaced.
    // machineType: machine type of the VM being created. This value uses the format zones/{zone}/machineTypes/{type_name}. For a list of machine types, see https://cloud.google.com/compute/docs/machine-types
    // sourceImage: path to the operating system image to mount. For details about images you can mount, see https://cloud.google.com/compute/docs/images
    // diskSizeGb: storage size of the boot disk to attach to the instance.
    // networkName: network interface to associate with the instance.
    String machineType = String.format("zones/%s/machineTypes/n1-standard-1", zone);
    String sourceImage = String.format("projects/debian-cloud/global/images/family/%s", "debian-10");
    long diskSizeGb = 10L;
    String networkName = "default";
    // clean up any remaining background resources.
    try (InstancesClient instancesClient = InstancesClient.create()) {
        // Instance creation requires at least one persistent disk and one network interface.
        AttachedDisk disk = AttachedDisk.newBuilder().setBoot(true).setAutoDelete(true).setType(Type.PERSISTENT.toString()).setDeviceName("disk-1").setInitializeParams(AttachedDiskInitializeParams.newBuilder().setSourceImage(sourceImage).setDiskSizeGb(diskSizeGb).build()).build();
        // Use the network interface provided in the networkName argument.
        NetworkInterface networkInterface = NetworkInterface.newBuilder().setName(networkName).build();
        // Bind `instanceName`, `machineType`, `disk`, and `networkInterface` to an instance.
        Instance instanceResource = Instance.newBuilder().setName(instanceName).setMachineType(machineType).addDisks(disk).addNetworkInterfaces(networkInterface).build();
        System.out.printf("Creating instance: %s at %s %n", instanceName, zone);
        // Insert the instance in the specified project and zone.
        InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder().setProject(project).setZone(zone).setInstanceResource(instanceResource).build();
        OperationFuture<Operation, Operation> operation = instancesClient.insertAsync(insertInstanceRequest);
        // Wait for the operation to complete.
        Operation response = operation.get();
        if (response.hasError()) {
            System.out.println("Instance creation failed ! ! " + response);
            return;
        }
        System.out.println("Operation Status: " + response.getStatus());
    }
}
Also used : InsertInstanceRequest(com.google.cloud.compute.v1.InsertInstanceRequest) Instance(com.google.cloud.compute.v1.Instance) InstancesClient(com.google.cloud.compute.v1.InstancesClient) AttachedDisk(com.google.cloud.compute.v1.AttachedDisk) NetworkInterface(com.google.cloud.compute.v1.NetworkInterface) Operation(com.google.cloud.compute.v1.Operation)

Example 2 with InstancesClient

use of com.google.cloud.compute.v1.InstancesClient in project java-docs-samples by GoogleCloudPlatform.

the class CreateInstanceFromTemplateWithOverrides method createInstanceFromTemplateWithOverrides.

// Creates a Compute Engine VM instance from an instance template,
// but overrides the disk and machine type options in the template.
public static void createInstanceFromTemplateWithOverrides(String projectId, String zone, String instanceName, String instanceTemplateName) throws IOException, ExecutionException, InterruptedException {
    try (InstancesClient instancesClient = InstancesClient.create();
        InstanceTemplatesClient instanceTemplatesClient = InstanceTemplatesClient.create()) {
        String machineType = "n1-standard-1";
        String newDiskSourceImage = "projects/debian-cloud/global/images/family/debian-10";
        // Retrieve an instance template.
        InstanceTemplate instanceTemplate = instanceTemplatesClient.get(projectId, instanceTemplateName);
        AttachedDisk newdisk = AttachedDisk.newBuilder().setInitializeParams(AttachedDiskInitializeParams.newBuilder().setDiskSizeGb(10).setSourceImage(newDiskSourceImage).build()).setAutoDelete(true).setBoot(false).setType(AttachedDisk.Type.PERSISTENT.toString()).build();
        Instance instance = Instance.newBuilder().setName(instanceName).setMachineType(String.format("zones/%s/machineTypes/%s", zone, machineType)).addAllDisks(instanceTemplate.getProperties().getDisksList()).addDisks(newdisk).build();
        InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder().setProject(projectId).setZone(zone).setInstanceResource(instance).setSourceInstanceTemplate(instanceTemplate.getSelfLink()).build();
        Operation response = instancesClient.insertAsync(insertInstanceRequest).get();
        if (response.hasError()) {
            System.out.println("Instance creation from template with overrides failed ! ! " + response);
            return;
        }
        System.out.printf("Instance creation from template with overrides: Operation Status %s: %s ", instanceName, response.getStatus());
    }
}
Also used : InsertInstanceRequest(com.google.cloud.compute.v1.InsertInstanceRequest) Instance(com.google.cloud.compute.v1.Instance) InstancesClient(com.google.cloud.compute.v1.InstancesClient) AttachedDisk(com.google.cloud.compute.v1.AttachedDisk) Operation(com.google.cloud.compute.v1.Operation) InstanceTemplatesClient(com.google.cloud.compute.v1.InstanceTemplatesClient) InstanceTemplate(com.google.cloud.compute.v1.InstanceTemplate)

Example 3 with InstancesClient

use of com.google.cloud.compute.v1.InstancesClient in project java-docs-samples by GoogleCloudPlatform.

the class DeleteInstance method deleteInstance.

// Delete the instance specified by `instanceName`
// if it's present in the given project and zone.
public static void deleteInstance(String project, String zone, String instanceName) throws IOException, InterruptedException, ExecutionException {
    // clean up any remaining background resources.
    try (InstancesClient instancesClient = InstancesClient.create()) {
        System.out.printf("Deleting instance: %s ", instanceName);
        // Describe which instance is to be deleted.
        DeleteInstanceRequest deleteInstanceRequest = DeleteInstanceRequest.newBuilder().setProject(project).setZone(zone).setInstance(instanceName).build();
        OperationFuture<Operation, Operation> operation = instancesClient.deleteAsync(deleteInstanceRequest);
        // Wait for the operation to complete.
        Operation response = operation.get();
        if (response.hasError()) {
            System.out.println("Instance deletion failed ! ! " + response);
            return;
        }
        System.out.println("Operation Status: " + response.getStatus());
    }
}
Also used : InstancesClient(com.google.cloud.compute.v1.InstancesClient) Operation(com.google.cloud.compute.v1.Operation) DeleteInstanceRequest(com.google.cloud.compute.v1.DeleteInstanceRequest)

Example 4 with InstancesClient

use of com.google.cloud.compute.v1.InstancesClient in project java-docs-samples by GoogleCloudPlatform.

the class ListAllInstances method listAllInstances.

// List all instances in the specified project ID.
public static AggregatedListPagedResponse listAllInstances(String project) throws IOException {
    // safely clean up any remaining background resources.
    try (InstancesClient instancesClient = InstancesClient.create()) {
        // Use the `setMaxResults` parameter to limit the number of results
        // that the API returns per response page.
        AggregatedListInstancesRequest aggregatedListInstancesRequest = AggregatedListInstancesRequest.newBuilder().setProject(project).setMaxResults(5).build();
        InstancesClient.AggregatedListPagedResponse response = instancesClient.aggregatedList(aggregatedListInstancesRequest);
        // automatically, requesting next pages as you iterate over the results.
        for (Map.Entry<String, InstancesScopedList> zoneInstances : response.iterateAll()) {
            // Instances scoped by each zone
            String zone = zoneInstances.getKey();
            if (!zoneInstances.getValue().getInstancesList().isEmpty()) {
                // zoneInstances.getKey() returns the fully qualified address.
                // Hence, strip it to get the zone name only
                System.out.printf("Instances at %s: ", zone.substring(zone.lastIndexOf('/') + 1));
                for (Instance instance : zoneInstances.getValue().getInstancesList()) {
                    System.out.println(instance.getName());
                }
            }
        }
        System.out.println("####### Listing all instances complete #######");
        return response;
    }
}
Also used : InstancesScopedList(com.google.cloud.compute.v1.InstancesScopedList) Instance(com.google.cloud.compute.v1.Instance) AggregatedListPagedResponse(com.google.cloud.compute.v1.InstancesClient.AggregatedListPagedResponse) InstancesClient(com.google.cloud.compute.v1.InstancesClient) AggregatedListInstancesRequest(com.google.cloud.compute.v1.AggregatedListInstancesRequest) Map(java.util.Map)

Example 5 with InstancesClient

use of com.google.cloud.compute.v1.InstancesClient in project java-docs-samples by GoogleCloudPlatform.

the class CreateInstanceWithCustomHostname method createInstanceWithCustomHostname.

// Creates an instance with custom hostname.
public static void createInstanceWithCustomHostname(String projectId, String zone, String instanceName, String hostName) throws IOException, ExecutionException, InterruptedException {
    // machineType - Machine type for the VM instance specified in the following format:
    // *    "zones/{zone}/machineTypes/{type_name}". For example:
    // *    "zones/europe-west3-c/machineTypes/f1-micro"
    // *    You can find the list of available machine types by using this gcloud command:
    // *    $ gcloud compute machine-types list
    // sourceImage - Path of the disk image you want to use for your boot
    // *    disk. This image can be one of the public images
    // *    eg: "projects/...
    // *    or a private image you have access to.
    // *    You can check the list of available public images using:
    // *    $ gcloud compute images list
    // networkName - Name of the network you want the new instance to use.
    // *    For example: global/networks/default - if you want to use the default network.
    String machineType = "n1-standard-1";
    String sourceImage = String.format("projects/%s/global/images/family/%s", "debian-cloud", "debian-11");
    String networkName = "global/networks/default";
    try (InstancesClient instancesClient = InstancesClient.create()) {
        System.out.printf("Creating the %s instance in %s with hostname %s...", instanceName, zone, hostName);
        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(10).build()).build();
        // Use the network interface provided in the networkName argument.
        NetworkInterface networkInterface = NetworkInterface.newBuilder().setName(networkName).build();
        Instance instanceResource = Instance.newBuilder().setName(instanceName).setHostname(hostName).addDisks(disk).setMachineType(String.format("zones/%s/machineTypes/%s", zone, machineType)).addNetworkInterfaces(networkInterface).build();
        InsertInstanceRequest request = InsertInstanceRequest.newBuilder().setProject(projectId).setZone(zone).setInstanceResource(instanceResource).build();
        // Wait for the create operation to complete.
        Operation response = instancesClient.insertAsync(request).get();
        if (response.hasError()) {
            System.out.printf("Instance creation failed for instance: %s ; Response: %s ! ! ", instanceName, response);
            return;
        }
        System.out.printf("Instance created : %s", instanceName);
        System.out.printf("Operation Status for instance %s is %s: ", instanceName, response.getStatus());
    }
}
Also used : InsertInstanceRequest(com.google.cloud.compute.v1.InsertInstanceRequest) Instance(com.google.cloud.compute.v1.Instance) InstancesClient(com.google.cloud.compute.v1.InstancesClient) AttachedDisk(com.google.cloud.compute.v1.AttachedDisk) NetworkInterface(com.google.cloud.compute.v1.NetworkInterface) Operation(com.google.cloud.compute.v1.Operation)

Aggregations

InstancesClient (com.google.cloud.compute.v1.InstancesClient)18 Operation (com.google.cloud.compute.v1.Operation)13 Instance (com.google.cloud.compute.v1.Instance)11 InsertInstanceRequest (com.google.cloud.compute.v1.InsertInstanceRequest)7 AttachedDisk (com.google.cloud.compute.v1.AttachedDisk)5 NetworkInterface (com.google.cloud.compute.v1.NetworkInterface)5 GetInstanceRequest (com.google.cloud.compute.v1.GetInstanceRequest)2 AggregatedListInstancesRequest (com.google.cloud.compute.v1.AggregatedListInstancesRequest)1 CustomerEncryptionKeyProtectedDisk (com.google.cloud.compute.v1.CustomerEncryptionKeyProtectedDisk)1 DeleteInstanceRequest (com.google.cloud.compute.v1.DeleteInstanceRequest)1 InstanceTemplate (com.google.cloud.compute.v1.InstanceTemplate)1 InstanceTemplatesClient (com.google.cloud.compute.v1.InstanceTemplatesClient)1 AggregatedListPagedResponse (com.google.cloud.compute.v1.InstancesClient.AggregatedListPagedResponse)1 InstancesScopedList (com.google.cloud.compute.v1.InstancesScopedList)1 InstancesStartWithEncryptionKeyRequest (com.google.cloud.compute.v1.InstancesStartWithEncryptionKeyRequest)1 ResetInstanceRequest (com.google.cloud.compute.v1.ResetInstanceRequest)1 SetDeletionProtectionInstanceRequest (com.google.cloud.compute.v1.SetDeletionProtectionInstanceRequest)1 SetLabelsInstanceRequest (com.google.cloud.compute.v1.SetLabelsInstanceRequest)1 StartInstanceRequest (com.google.cloud.compute.v1.StartInstanceRequest)1 StartWithEncryptionKeyInstanceRequest (com.google.cloud.compute.v1.StartWithEncryptionKeyInstanceRequest)1