Search in sources :

Example 16 with InstancesClient

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

the class AutoLabelInstance method accept.

@Override
public void accept(CloudEvent event) throws Exception {
    // Extract CloudEvent data
    if (event.getData() != null) {
        String cloudEventData = new String(event.getData().toBytes(), StandardCharsets.UTF_8);
        // Convert data to JSON
        JsonObject eventData;
        try {
            Gson gson = new Gson();
            eventData = gson.fromJson(cloudEventData, JsonObject.class);
        } catch (JsonSyntaxException error) {
            throw new RuntimeException("CloudEvent data is not valid JSON: " + error.getMessage());
        }
        // Extract the Cloud Audit Logging entry from the data's protoPayload
        JsonObject payload = eventData.getAsJsonObject("protoPayload");
        JsonObject auth = payload.getAsJsonObject("authenticationInfo");
        // Extract the email address of the authenticated user
        // (or service account on behalf of third party principal) making the request
        String creator = auth.get("principalEmail").getAsString();
        if (creator == null) {
            throw new RuntimeException("`principalEmail` not found in protoPayload.");
        }
        // Format the 'creator' parameter to match GCE label validation requirements
        creator = creator.toLowerCase().replaceAll("\\W", "-");
        // Get relevant VM instance details from the CloudEvent `subject` property
        // Example: compute.googleapis.com/projects/<PROJECT>/zones/<ZONE>/instances/<INSTANCE>
        String subject = event.getSubject();
        if (subject == null || subject == "") {
            throw new RuntimeException("Missing CloudEvent `subject`.");
        }
        String[] params = subject.split("/");
        // Validate data
        if (params.length < 7) {
            throw new RuntimeException("Can not parse resource from CloudEvent `subject`: " + subject);
        }
        String project = params[2];
        String zone = params[4];
        String instanceName = params[6];
        // Instantiate the Compute Instances client
        try (InstancesClient instancesClient = InstancesClient.create()) {
            // Get the newly-created VM instance's label fingerprint
            // This is required by the Compute Engine API to prevent duplicate labels
            GetInstanceRequest getInstanceRequest = GetInstanceRequest.newBuilder().setInstance(instanceName).setProject(project).setZone(zone).build();
            Instance instance = instancesClient.get(getInstanceRequest);
            String fingerPrint = instance.getLabelFingerprint();
            // Label the instance with its creator
            SetLabelsInstanceRequest setLabelRequest = SetLabelsInstanceRequest.newBuilder().setInstance(instanceName).setProject(project).setZone(zone).setInstancesSetLabelsRequestResource(InstancesSetLabelsRequest.newBuilder().putLabels("creator", creator).setLabelFingerprint(fingerPrint).build()).build();
            instancesClient.setLabels(setLabelRequest);
            logger.info(String.format("Adding label, \"{'creator': '%s'}\", to instance, \"%s\".", creator, instanceName));
        } catch (Exception error) {
            throw new RuntimeException(String.format("Error trying to label VM instance, %s: %s", instanceName, error.toString()));
        }
    }
}
Also used : JsonSyntaxException(com.google.gson.JsonSyntaxException) GetInstanceRequest(com.google.cloud.compute.v1.GetInstanceRequest) Instance(com.google.cloud.compute.v1.Instance) InstancesClient(com.google.cloud.compute.v1.InstancesClient) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) SetLabelsInstanceRequest(com.google.cloud.compute.v1.SetLabelsInstanceRequest) JsonSyntaxException(com.google.gson.JsonSyntaxException)

Example 17 with InstancesClient

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

the class CreateWindowsServerInstanceInternalIp method createWindowsServerInstanceInternalIp.

// Creates a new Windows Server instance that has only an internal IP address.
public static void createWindowsServerInstanceInternalIp(String projectId, String zone, String instanceName, String networkLink, String subnetworkLink) throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // machineType - Machine type you want to create in 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 using:
    // *    https://cloud.google.com/sdk/gcloud/reference/compute/machine-types/list
    String machineType = "n1-standard-1";
    // sourceImageFamily - Name of the public image family for Windows Server or SQL Server images.
    // *    https://cloud.google.com/compute/docs/images#os-compute-support
    String sourceImageFamily = "windows-2012-r2";
    // Instantiates a client.
    try (InstancesClient instancesClient = InstancesClient.create()) {
        AttachedDisk attachedDisk = AttachedDisk.newBuilder().setInitializeParams(AttachedDiskInitializeParams.newBuilder().setDiskSizeGb(64).setSourceImage(String.format("projects/windows-cloud/global/images/family/%s", sourceImageFamily)).build()).setAutoDelete(true).setBoot(true).setType(AttachedDisk.Type.PERSISTENT.toString()).build();
        Instance instance = Instance.newBuilder().setName(instanceName).setMachineType(String.format("zones/%s/machineTypes/%s", zone, machineType)).addDisks(attachedDisk).addNetworkInterfaces(NetworkInterface.newBuilder().setName(networkLink).setSubnetwork(subnetworkLink).build()).build();
        InsertInstanceRequest request = InsertInstanceRequest.newBuilder().setProject(projectId).setZone(zone).setInstanceResource(instance).build();
        // Wait for the operation to complete.
        Operation operation = instancesClient.insertAsync(request).get(3, TimeUnit.MINUTES);
        if (operation.hasError()) {
            System.out.printf("Error in creating instance %s", operation.getError());
            return;
        }
        System.out.printf("Instance created %s", instanceName);
    }
}
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)

Example 18 with InstancesClient

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

the class GetInstanceSerialPort method getInstanceSerialPort.

// Prints an instance serial port output.
public static void getInstanceSerialPort(String projectId, String zone, String instanceName) throws IOException {
    // Instantiates a client.
    try (InstancesClient instancesClient = InstancesClient.create()) {
        SerialPortOutput serialPortOutput = instancesClient.getSerialPortOutput(projectId, zone, instanceName);
        System.out.printf("Output from instance serial port %s", serialPortOutput.getContents());
    }
}
Also used : SerialPortOutput(com.google.cloud.compute.v1.SerialPortOutput) InstancesClient(com.google.cloud.compute.v1.InstancesClient)

Example 19 with InstancesClient

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

the class SnippetsIT method testWaitForOperation.

@Test
public void testWaitForOperation() throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // Construct a delete request and get the operation instance.
    InstancesClient instancesClient = InstancesClient.create();
    OperationFuture<Operation, Operation> operation = instancesClient.deleteAsync(PROJECT_ID, ZONE, MACHINE_NAME_WAIT_FOR_OP);
    // Wait for the operation to complete.
    operation.get(3, TimeUnit.MINUTES);
    assertThat(stdOut.toString().contains("Operation Status: DONE"));
}
Also used : InstancesClient(com.google.cloud.compute.v1.InstancesClient) Operation(com.google.cloud.compute.v1.Operation) Test(org.junit.jupiter.api.Test)

Example 20 with InstancesClient

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

the class CreateEncryptedInstance method createEncryptedInstance.

// Create a new encrypted instance with the provided "instanceName" value and encryption key
// in the specified project and zone.
public static void createEncryptedInstance(String project, String zone, String instanceName, String diskEncryptionKey) throws IOException, InterruptedException, ExecutionException, TimeoutException {
    /* 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-11");
    long diskSizeGb = 10L;
    String networkName = "default";
    /* Initialize client that will be used to send requests. This client only needs to be created
       once, and can be reused for multiple requests. After completing all of your requests, call
       the `instancesClient.close()` method on the client to safely
       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()).setInitializeParams(AttachedDiskInitializeParams.newBuilder().setSourceImage(sourceImage).setDiskSizeGb(diskSizeGb).build()).setDiskEncryptionKey(CustomerEncryptionKey.newBuilder().setRawKey(diskEncryptionKey).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 ", 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(3, TimeUnit.MINUTES);
        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)

Aggregations

InstancesClient (com.google.cloud.compute.v1.InstancesClient)28 Operation (com.google.cloud.compute.v1.Operation)20 Instance (com.google.cloud.compute.v1.Instance)18 InsertInstanceRequest (com.google.cloud.compute.v1.InsertInstanceRequest)11 AttachedDisk (com.google.cloud.compute.v1.AttachedDisk)9 NetworkInterface (com.google.cloud.compute.v1.NetworkInterface)6 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 Disk (com.google.cloud.compute.v1.Disk)1 DisksClient (com.google.cloud.compute.v1.DisksClient)1 Image (com.google.cloud.compute.v1.Image)1 ImagesClient (com.google.cloud.compute.v1.ImagesClient)1 InsertImageRequest (com.google.cloud.compute.v1.InsertImageRequest)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 InstancesSettings (com.google.cloud.compute.v1.InstancesSettings)1