Search in sources :

Example 6 with InstancesClient

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

the class CreateInstanceDeleteProtection method createInstanceDeleteProtection.

// Send an instance creation request to the Compute Engine API and wait for it to complete.
public static void createInstanceDeleteProtection(String projectId, String zone, String instanceName, boolean deleteProtection) throws IOException, ExecutionException, InterruptedException {
    String machineType = String.format("zones/%s/machineTypes/e2-small", zone);
    String sourceImage = String.format("projects/debian-cloud/global/images/family/%s", "debian-11");
    long diskSizeGb = 10L;
    String networkName = "default";
    // Instance creation requires at least one persistent disk and one network interface.
    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).setDeletionProtection(deleteProtection).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();
        if (response.hasError()) {
            System.out.println("Instance creation failed ! ! " + response);
            return;
        }
        System.out.printf("Instance created : %s", instanceName);
        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 7 with InstancesClient

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

the class SetDeleteProtection method setDeleteProtection.

// Updates the "Delete Protection" setting of given instance.
public static void setDeleteProtection(String projectId, String zone, String instanceName, boolean deleteProtection) throws IOException, ExecutionException, InterruptedException {
    try (InstancesClient instancesClient = InstancesClient.create()) {
        SetDeletionProtectionInstanceRequest request = SetDeletionProtectionInstanceRequest.newBuilder().setProject(projectId).setZone(zone).setResource(instanceName).setDeletionProtection(deleteProtection).build();
        instancesClient.setDeletionProtectionAsync(request).get();
        // Retrieve the updated setting from the instance.
        System.out.printf("Updated Delete Protection setting: %s", instancesClient.get(projectId, zone, instanceName).getDeletionProtection());
    }
}
Also used : SetDeletionProtectionInstanceRequest(com.google.cloud.compute.v1.SetDeletionProtectionInstanceRequest) InstancesClient(com.google.cloud.compute.v1.InstancesClient)

Example 8 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 9 with InstancesClient

use of com.google.cloud.compute.v1.InstancesClient in project java-compute by googleapis.

the class ITSmokeInstancesTest method setUp.

@BeforeClass
public static void setUp() throws IOException {
    instances = new ArrayList<>();
    InstancesSettings instanceSettings = InstancesSettings.newBuilder().build();
    instancesClient = InstancesClient.create(instanceSettings);
}
Also used : InstancesSettings(com.google.cloud.compute.v1.InstancesSettings) BeforeClass(org.junit.BeforeClass)

Example 10 with InstancesClient

use of com.google.cloud.compute.v1.InstancesClient in project java-compute by googleapis.

the class ITSmokeInstancesTest method testDefaultClient.

@Test
public void testDefaultClient() throws IOException, ExecutionException, InterruptedException {
    InstancesClient defaultClient = InstancesClient.create();
    Instance instanceResource = Instance.newBuilder().setName(INSTANCE).setMachineType(MACHINE_TYPE).addDisks(DISK).addNetworkInterfaces(NETWORK_INTERFACE).build();
    defaultClient.insertAsync(DEFAULT_PROJECT, DEFAULT_ZONE, instanceResource).get();
    instances.add(instanceResource);
    assertInstanceDetails(getInstance());
}
Also used : Instance(com.google.cloud.compute.v1.Instance) InstancesClient(com.google.cloud.compute.v1.InstancesClient) Test(org.junit.Test)

Aggregations

InstancesClient (com.google.cloud.compute.v1.InstancesClient)19 Operation (com.google.cloud.compute.v1.Operation)13 Instance (com.google.cloud.compute.v1.Instance)12 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 Test (org.junit.Test)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 InstancesSettings (com.google.cloud.compute.v1.InstancesSettings)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