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()));
}
}
}
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);
}
}
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());
}
}
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"));
}
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());
}
}
Aggregations