com.google.api.services.compute.model.Instance Java Examples

The following examples show how to use com.google.api.services.compute.model.Instance. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GoogleProviderUtils.java    From halyard with Apache License 2.0 6 votes vote down vote up
static String getInstanceIp(
    AccountDeploymentDetails<GoogleAccount> details, String instanceName) {
  Compute compute = getCompute(details);
  Instance instance = null;
  try {
    instance =
        compute
            .instances()
            .get(details.getAccount().getProject(), "us-central1-f", instanceName)
            .execute();
  } catch (IOException e) {
    throw new HalException(FATAL, "Unable to get instance " + instanceName);
  }

  return instance.getNetworkInterfaces().stream()
      .map(
          i ->
              i.getAccessConfigs().stream()
                  .map(AccessConfig::getNatIP)
                  .filter(ip -> !StringUtils.isEmpty(ip))
                  .findFirst())
      .filter(Optional::isPresent)
      .map(Optional::get)
      .findFirst()
      .orElseThrow(() -> new HalException(FATAL, "No public IP associated with" + instanceName));
}
 
Example #2
Source File: GcpInstanceResourceBuilder.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private CloudVmInstanceStatus stopStart(GcpContext context, AuthenticatedContext auth, CloudInstance instance, boolean stopRequest) {
    String projectId = GcpStackUtil.getProjectId(auth.getCloudCredential());
    String availabilityZone = context.getLocation().getAvailabilityZone().value();
    Compute compute = context.getCompute();
    String instanceId = instance.getInstanceId();
    try {
        Get get = compute.instances().get(projectId, availabilityZone, instanceId);
        String state = stopRequest ? "RUNNING" : "TERMINATED";
        Instance instanceResponse = get.execute();
        if (state.equals(instanceResponse.getStatus())) {
            Operation operation = stopRequest ? compute.instances().stop(projectId, availabilityZone, instanceId).setPrettyPrint(true).execute()
                    : executeStartOperation(projectId, availabilityZone, compute, instanceId, instance.getTemplate(), instanceResponse.getDisks());
            CloudInstance operationAwareCloudInstance = createOperationAwareCloudInstance(instance, operation);
            return new CloudVmInstanceStatus(operationAwareCloudInstance, InstanceStatus.IN_PROGRESS);
        } else {
            LOGGER.debug("Instance {} is not in {} state - won't start it.", state, instanceId);
            return null;
        }
    } catch (IOException e) {
        throw new GcpResourceException(String.format("An error occurred while stopping the vm '%s'", instanceId), e);
    }
}
 
Example #3
Source File: GcpInstanceResourceBuilderTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
public void doTestDefaultDiskEncryption(ImmutableMap<String, Object> params) throws Exception {
    Group group = newGroupWithParams(params);
    List<CloudResource> buildableResources = builder.create(context, privateId, authenticatedContext, group, image);
    context.addComputeResources(0L, buildableResources);

    when(compute.instances()).thenReturn(instances);
    ArgumentCaptor<Instance> instanceArgumentCaptor = ArgumentCaptor.forClass(Instance.class);
    when(instances.insert(anyString(), anyString(), instanceArgumentCaptor.capture())).thenReturn(insert);
    when(insert.execute()).thenReturn(operation);

    builder.build(context, privateId, authenticatedContext, group, buildableResources, cloudStack);

    verify(gcpDiskEncryptionService, times(0)).addEncryptionKeyToDisk(any(InstanceTemplate.class), any(AttachedDisk.class));

    instanceArgumentCaptor.getValue().getDisks().forEach(attachedDisk -> assertNull(attachedDisk.getDiskEncryptionKey()));
}
 
Example #4
Source File: GcpNetworkInterfaceProvider.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
public List<Instance> getInstances(AuthenticatedContext authenticatedContext, String instanceNamePrefix) {
    List<Instance> instances = new ArrayList<>();
    CloudContext cloudContext = authenticatedContext.getCloudContext();
    String stackName = cloudContext.getName();
    LOGGER.debug(String.format("Collecting instances for stack: %s", stackName));
    long startTime = new Date().getTime();

    try {
        Compute.Instances.List request = getRequest(authenticatedContext, instanceNamePrefix);
        InstanceList response;
        do {
            response = request.execute();
            if (response.getItems() == null) {
                continue;
            }
            instances.addAll(response.getItems());
            request.setPageToken(response.getNextPageToken());
        } while (response.getNextPageToken() != null);
    } catch (IOException e) {
        LOGGER.debug("Error during instance collection", e);
    }
    logResponse(instances, startTime, stackName);
    return instances;
}
 
Example #5
Source File: GcpInstanceResourceBuilderTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void isSchedulingPreemptibleTest() throws Exception {
    // GIVEN
    Group group = newGroupWithParams(ImmutableMap.of("preemptible", true));
    List<CloudResource> buildableResources = builder.create(context, privateId, authenticatedContext, group, image);
    context.addComputeResources(0L, buildableResources);

    // WHEN
    when(compute.instances()).thenReturn(instances);
    when(instances.insert(anyString(), anyString(), any(Instance.class))).thenReturn(insert);
    when(insert.setPrettyPrint(anyBoolean())).thenReturn(insert);
    when(insert.execute()).thenReturn(operation);

    builder.build(context, privateId, authenticatedContext, group, buildableResources, cloudStack);

    // THEN
    verify(compute).instances();
    verify(instances).insert(anyString(), anyString(), instanceArg.capture());
    assertTrue(instanceArg.getValue().getScheduling().getPreemptible());
}
 
Example #6
Source File: GcpInstanceResourceBuilderTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void isSchedulingNotPreemptibleTest() throws Exception {
    // GIVEN
    Group group = newGroupWithParams(ImmutableMap.of("preemptible", false));
    List<CloudResource> buildableResources = builder.create(context, privateId, authenticatedContext, group, image);
    context.addComputeResources(0L, buildableResources);

    // WHEN
    when(compute.instances()).thenReturn(instances);
    when(instances.insert(anyString(), anyString(), any(Instance.class))).thenReturn(insert);
    when(insert.setPrettyPrint(anyBoolean())).thenReturn(insert);
    when(insert.execute()).thenReturn(operation);

    builder.build(context, privateId, authenticatedContext, group, buildableResources, cloudStack);

    // THEN
    verify(compute).instances();
    verify(instances).insert(anyString(), anyString(), instanceArg.capture());
    assertFalse(instanceArg.getValue().getScheduling().getPreemptible());
}
 
Example #7
Source File: GcpInstanceResourceBuilderTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void preemptibleParameterNotSetTest() throws Exception {
    // GIVEN
    Group group = newGroupWithParams(ImmutableMap.of());
    List<CloudResource> buildableResources = builder.create(context, privateId, authenticatedContext, group, image);
    context.addComputeResources(0L, buildableResources);

    // WHEN
    when(compute.instances()).thenReturn(instances);
    when(instances.insert(anyString(), anyString(), any(Instance.class))).thenReturn(insert);
    when(insert.setPrettyPrint(anyBoolean())).thenReturn(insert);
    when(insert.execute()).thenReturn(operation);

    builder.build(context, privateId, authenticatedContext, group, buildableResources, cloudStack);

    // THEN
    verify(compute).instances();
    verify(instances).insert(anyString(), anyString(), instanceArg.capture());
    assertFalse(instanceArg.getValue().getScheduling().getPreemptible());
}
 
Example #8
Source File: GcpInstanceResourceBuilderTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void extraxtServiceAccountWhenServiceEmailEmpty() throws Exception {
    // GIVEN
    Group group = newGroupWithParams(ImmutableMap.of());
    List<CloudResource> buildableResources = builder.create(context, privateId, authenticatedContext, group, image);
    context.addComputeResources(0L, buildableResources);

    // WHEN
    when(compute.instances()).thenReturn(instances);
    when(instances.insert(anyString(), anyString(), any(Instance.class))).thenReturn(insert);
    when(insert.setPrettyPrint(anyBoolean())).thenReturn(insert);
    when(insert.execute()).thenReturn(operation);

    builder.build(context, privateId, authenticatedContext, group, buildableResources, cloudStack);

    // THEN
    verify(compute).instances();
    verify(instances).insert(anyString(), anyString(), instanceArg.capture());
    assertNull(instanceArg.getValue().getServiceAccounts());
}
 
Example #9
Source File: GcpInstanceResourceBuilder.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void updateDiskSetWithInstanceName(AuthenticatedContext auth, List<CloudResource> computeResources, Instance instance) {
    for (CloudResource resource : filterResourcesByType(computeResources, ResourceType.GCP_ATTACHED_DISKSET)) {
        resource.setInstanceId(instance.getName());
        resource.setStatus(CommonStatus.CREATED);
        persistenceNotifier.notifyUpdate(resource, auth.getCloudContext());
    }
}
 
Example #10
Source File: GcpInstanceResourceBuilder.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public List<CloudVmInstanceStatus> checkInstances(GcpContext context, AuthenticatedContext auth, List<CloudInstance> instances) {
    List<CloudVmInstanceStatus> result = new ArrayList<>();
    String instanceName = instances.isEmpty() ? "" : instances.get(0).getInstanceId();
    if (!StringUtils.isEmpty(instanceName)) {
        List<Instance> gcpInstances = gcpNetworkInterfaceProvider.getInstances(auth, instanceName.split("-")[0]);
        for (CloudInstance instance : instances) {
            Optional<Instance> gcpInstanceOpt = gcpInstances.stream().filter(inst -> inst.getName().equalsIgnoreCase(instance.getInstanceId())).findFirst();
            if (gcpInstanceOpt.isPresent()) {
                Instance gcpInstance = gcpInstanceOpt.get();
                InstanceStatus status;
                switch (gcpInstance.getStatus()) {
                    case "RUNNING":
                        status = InstanceStatus.STARTED;
                        break;
                    case "TERMINATED":
                        status = InstanceStatus.STOPPED;
                        break;
                    default:
                        status = InstanceStatus.IN_PROGRESS;
                }
                result.add(new CloudVmInstanceStatus(instance, status));
            } else {
                LOGGER.debug("Instance {} cannot be found", instance.getInstanceId());
                result.add(new CloudVmInstanceStatus(instance, InstanceStatus.TERMINATED));
            }
        }
    }
    return result;
}
 
Example #11
Source File: GcpInstanceResourceBuilderTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public void doTestDefaultEncryption(CloudInstance cloudInstance) throws IOException {
    when(compute.instances()).thenReturn(instances);

    Get get = Mockito.mock(Get.class);
    when(instances.get(anyString(), anyString(), anyString())).thenReturn(get);
    Start start = Mockito.mock(Start.class);
    when(instances.start(anyString(), anyString(), anyString())).thenReturn(start);

    String expectedSource = "google.disk";
    AttachedDisk disk = new AttachedDisk();
    disk.setSource(expectedSource);
    Instance instance = new Instance();
    instance.setDisks(List.of(disk));
    instance.setStatus("TERMINATED");
    when(get.execute()).thenReturn(instance);

    when(start.setPrettyPrint(true)).thenReturn(start);
    when(start.execute()).thenReturn(operation);

    CloudVmInstanceStatus vmInstanceStatus = builder.start(context, authenticatedContext, cloudInstance);

    assertEquals(InstanceStatus.IN_PROGRESS, vmInstanceStatus.getStatus());

    verify(gcpDiskEncryptionService, times(0)).addEncryptionKeyToDisk(any(InstanceTemplate.class), any(Disk.class));
    verify(instances, times(0))
            .startWithEncryptionKey(anyString(), anyString(), anyString(), any(InstancesStartWithEncryptionKeyRequest.class));
}
 
Example #12
Source File: GcpInstanceResourceBuilderTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void doTestDiskEncryption(String encryptionKey, ImmutableMap<String, Object> templateParams) throws Exception {
    Group group = newGroupWithParams(templateParams);
    CloudResource requestedDisk = CloudResource.builder()
            .type(ResourceType.GCP_DISK)
            .status(CommonStatus.REQUESTED)
            .name("dasdisk")
            .build();
    List<CloudResource> buildableResources = List.of(requestedDisk);
    context.addComputeResources(0L, buildableResources);

    when(compute.instances()).thenReturn(instances);

    ArgumentCaptor<Instance> instanceArgumentCaptor = ArgumentCaptor.forClass(Instance.class);
    when(instances.insert(anyString(), anyString(), instanceArgumentCaptor.capture())).thenReturn(insert);
    when(insert.execute()).thenReturn(operation);

    CustomerEncryptionKey customerEncryptionKey = new CustomerEncryptionKey();
    customerEncryptionKey.setRawKey("encodedKey==");
    doAnswer(invocation -> {
        AttachedDisk argument = invocation.getArgument(1);
        argument.setDiskEncryptionKey(customerEncryptionKey);
        return invocation;
    }).when(gcpDiskEncryptionService).addEncryptionKeyToDisk(any(InstanceTemplate.class), any(AttachedDisk.class));

    builder.build(context, privateId, authenticatedContext, group, buildableResources, cloudStack);

    verify(gcpDiskEncryptionService, times(1)).addEncryptionKeyToDisk(any(InstanceTemplate.class), any(AttachedDisk.class));

    instanceArgumentCaptor.getValue().getDisks().forEach(attachedDisk -> {
        assertNotNull(attachedDisk.getDiskEncryptionKey());
        assertEquals(customerEncryptionKey, attachedDisk.getDiskEncryptionKey());
    });
}
 
Example #13
Source File: GcpInstanceResourceBuilderTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void extraxtServiceAccountWhenServiceEmailNotEmpty() throws Exception {
    // GIVEN
    Group group = newGroupWithParams(ImmutableMap.of());
    List<CloudResource> buildableResources = builder.create(context, privateId, authenticatedContext, group, image);
    context.addComputeResources(0L, buildableResources);

    String email = "[email protected]";
    CloudGcsView cloudGcsView = new CloudGcsView(CloudIdentityType.LOG);
    cloudGcsView.setServiceAccountEmail(email);

    CloudStack cloudStack = new CloudStack(Collections.emptyList(), new Network(null), image,
            emptyMap(), emptyMap(), null, null, null, null,
            new SpiFileSystem("test", FileSystemType.GCS, List.of(cloudGcsView)));

    // WHEN
    when(compute.instances()).thenReturn(instances);
    when(instances.insert(anyString(), anyString(), any(Instance.class))).thenReturn(insert);
    when(insert.setPrettyPrint(anyBoolean())).thenReturn(insert);
    when(insert.execute()).thenReturn(operation);

    builder.build(context, privateId, authenticatedContext, group, buildableResources, cloudStack);

    // THEN
    verify(compute).instances();
    verify(instances).insert(anyString(), anyString(), instanceArg.capture());
    assertEquals(instanceArg.getValue().getServiceAccounts().get(0).getEmail(), email);
}
 
Example #14
Source File: GcpNetworkInterfaceProvider.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void logResponse(List<Instance> instanceList, long startTime, String stackName) {
    long endTime = new Date().getTime();
    if (instanceList != null) {
        LOGGER.debug(String.format("%d instance retrieved for stack %s during %dms", instanceList.size(), stackName, endTime - startTime));
    } else {
        LOGGER.debug(String.format("There are no instances found for stack %s", stackName));
    }
}
 
Example #15
Source File: GcpNetworkInterfaceProviderTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
private Instance createInstance(String name) {
    Instance instance = new Instance();
    instance.setName(name);
    instance.setNetworkInterfaces(List.of(new NetworkInterface()));
    return instance;
}
 
Example #16
Source File: GcpInstanceResourceBuilderTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
public void doTestCustomEncryption(Map<String, Object> params, CustomerEncryptionKey encryptionKey) throws IOException {
    InstanceAuthentication instanceAuthentication = new InstanceAuthentication("sshkey", "", "cloudbreak");
    CloudInstance cloudInstance = newCloudInstance(params, instanceAuthentication);
    when(compute.instances()).thenReturn(instances);

    ArgumentCaptor<InstancesStartWithEncryptionKeyRequest> requestCaptor = ArgumentCaptor.forClass(InstancesStartWithEncryptionKeyRequest.class);

    Get get = Mockito.mock(Get.class);
    when(instances.get(anyString(), anyString(), anyString())).thenReturn(get);
    StartWithEncryptionKey start = Mockito.mock(StartWithEncryptionKey.class);
    when(instances.startWithEncryptionKey(anyString(), anyString(), anyString(), requestCaptor.capture())).thenReturn(start);

    String expectedSource = "google.disk";
    AttachedDisk disk = new AttachedDisk();
    disk.setSource(expectedSource);
    Instance instance = new Instance();
    instance.setDisks(List.of(disk));
    instance.setStatus("TERMINATED");
    when(get.execute()).thenReturn(instance);

    when(start.setPrettyPrint(true)).thenReturn(start);
    when(start.execute()).thenReturn(operation);

    when(gcpDiskEncryptionService.hasCustomEncryptionRequested(any(InstanceTemplate.class))).thenReturn(true);
    when(gcpDiskEncryptionService.createCustomerEncryptionKey(any(InstanceTemplate.class))).thenReturn(encryptionKey);

    CloudVmInstanceStatus vmInstanceStatus = builder.start(context, authenticatedContext, cloudInstance);

    assertEquals(InstanceStatus.IN_PROGRESS, vmInstanceStatus.getStatus());

    verify(gcpDiskEncryptionService, times(1)).createCustomerEncryptionKey(any(InstanceTemplate.class));
    verify(instances, times(0)).start(anyString(), anyString(), anyString());

    InstancesStartWithEncryptionKeyRequest keyRequest = requestCaptor.getValue();
    assertNotNull(keyRequest.getDisks());
    assertEquals(1, keyRequest.getDisks().size());

    CustomerEncryptionKeyProtectedDisk protectedDisk = keyRequest.getDisks().iterator().next();
    assertEquals(encryptionKey, protectedDisk.getDiskEncryptionKey());
    assertEquals(expectedSource, protectedDisk.getSource());
}
 
Example #17
Source File: GcpNetworkInterfaceProvider.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
private Function<CloudResource, Optional<NetworkInterface>> getOptionalNetworkInterfaces(List<Instance> gcpInstances) {
    return instance -> gcpInstances.stream()
            .filter(gcpInstance -> instance.getName().equals(gcpInstance.getName()))
            .findFirst()
            .map(gcpInstance -> gcpInstance.getNetworkInterfaces().get(0));
}
 
Example #18
Source File: GcpNetworkInterfaceProvider.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
private Map<String, Optional<NetworkInterface>> getNetworkMap(List<Instance> gcpInstances, List<CloudResource> instances) {
    return instances.stream().collect(Collectors.toMap(CloudResource::getName, getOptionalNetworkInterfaces(gcpInstances)));
}
 
Example #19
Source File: GcpNetworkInterfaceProvider.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
Map<String, Optional<NetworkInterface>> provide(AuthenticatedContext authenticatedContext, List<CloudResource> instances) {
    String instanceNamePrefix = getInstanceNamePrefix(instances);
    List<Instance> gcpInstances = getInstances(authenticatedContext, instanceNamePrefix);
    return getNetworkMap(gcpInstances, instances);
}
 
Example #20
Source File: GcpInstanceConnector.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
private Instance getInstance(CloudContext context, CloudCredential credential, Compute compute, String instanceName) throws IOException {
    return compute.instances().get(GcpStackUtil.getProjectId(credential),
            context.getLocation().getAvailabilityZone().value(), instanceName).execute();
}
 
Example #21
Source File: GcpInstanceResourceBuilder.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
public List<CloudResource> build(GcpContext context, long privateId, AuthenticatedContext auth, Group group, List<CloudResource> buildableResource,
        CloudStack cloudStack) throws Exception {
    InstanceTemplate template = group.getReferenceInstanceConfiguration().getTemplate();
    String projectId = context.getProjectId();
    Location location = context.getLocation();
    Compute compute = context.getCompute();

    List<CloudResource> computeResources = context.getComputeResources(privateId);
    List<AttachedDisk> listOfDisks = new ArrayList<>();

    listOfDisks.addAll(getBootDiskList(computeResources, projectId, location.getAvailabilityZone()));
    listOfDisks.addAll(getAttachedDisks(computeResources, projectId));

    listOfDisks.forEach(disk -> gcpDiskEncryptionService.addEncryptionKeyToDisk(template, disk));

    Instance instance = new Instance();
    instance.setMachineType(String.format("https://www.googleapis.com/compute/v1/projects/%s/zones/%s/machineTypes/%s",
            projectId, location.getAvailabilityZone().value(), template.getFlavor()));
    instance.setName(buildableResource.get(0).getName());
    instance.setCanIpForward(Boolean.TRUE);
    instance.setNetworkInterfaces(getNetworkInterface(context, computeResources, group, cloudStack));
    instance.setDisks(listOfDisks);
    instance.setServiceAccounts(extractServiceAccounts(cloudStack));
    Scheduling scheduling = new Scheduling();
    boolean preemptible = false;
    if (template.getParameter(PREEMPTIBLE, Boolean.class) != null) {
        preemptible = template.getParameter(PREEMPTIBLE, Boolean.class);
    }
    scheduling.setPreemptible(preemptible);
    instance.setScheduling(scheduling);

    Tags tags = new Tags();
    List<String> tagList = new ArrayList<>();
    Map<String, String> labels = new HashMap<>();
    String groupname = group.getName().toLowerCase().replaceAll("[^A-Za-z0-9 ]", "");
    tagList.add(groupname);

    tagList.add(GcpStackUtil.getClusterTag(auth.getCloudContext()));
    tagList.add(GcpStackUtil.getGroupClusterTag(auth.getCloudContext(), group));
    cloudStack.getTags().forEach((key, value) -> tagList.add(key + '-' + value));

    labels.putAll(cloudStack.getTags());
    tags.setItems(tagList);

    instance.setTags(tags);
    instance.setLabels(labels);

    Metadata metadata = new Metadata();
    metadata.setItems(new ArrayList<>());

    Items sshMetaData = new Items();
    sshMetaData.setKey("ssh-keys");
    sshMetaData.setValue(group.getInstanceAuthentication().getLoginUserName() + ':' + group.getInstanceAuthentication().getPublicKey());

    Items blockProjectWideSsh = new Items();
    blockProjectWideSsh.setKey("block-project-ssh-keys");
    blockProjectWideSsh.setValue("TRUE");

    Items startupScript = new Items();
    startupScript.setKey("startup-script");
    startupScript.setValue(cloudStack.getImage().getUserDataByType(group.getType()));

    metadata.getItems().add(sshMetaData);
    metadata.getItems().add(startupScript);
    metadata.getItems().add(blockProjectWideSsh);
    instance.setMetadata(metadata);

    Insert insert = compute.instances().insert(projectId, location.getAvailabilityZone().value(), instance);
    insert.setPrettyPrint(Boolean.TRUE);
    try {
        Operation operation = insert.execute();
        verifyOperation(operation, buildableResource);
        updateDiskSetWithInstanceName(auth, computeResources, instance);
        return singletonList(createOperationAwareCloudResource(buildableResource.get(0), operation));
    } catch (GoogleJsonResponseException e) {
        throw new GcpResourceException(checkException(e), resourceType(), buildableResource.get(0).getName());
    }
}
 
Example #22
Source File: ComputeEngineSample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static Operation startInstance(Compute compute, String instanceName) throws IOException {
  System.out.println("================== Starting New Instance ==================");

  // Create VM Instance object with the required properties.
  Instance instance = new Instance();
  instance.setName(instanceName);
  instance.setMachineType(
      String.format(
          "https://www.googleapis.com/compute/v1/projects/%s/zones/%s/machineTypes/e2-standard-1",
          PROJECT_ID, ZONE_NAME));
  // Add Network Interface to be used by VM Instance.
  NetworkInterface ifc = new NetworkInterface();
  ifc.setNetwork(
      String.format(
          "https://www.googleapis.com/compute/v1/projects/%s/global/networks/default",
          PROJECT_ID));
  List<AccessConfig> configs = new ArrayList<>();
  AccessConfig config = new AccessConfig();
  config.setType(NETWORK_INTERFACE_CONFIG);
  config.setName(NETWORK_ACCESS_CONFIG);
  configs.add(config);
  ifc.setAccessConfigs(configs);
  instance.setNetworkInterfaces(Collections.singletonList(ifc));

  // Add attached Persistent Disk to be used by VM Instance.
  AttachedDisk disk = new AttachedDisk();
  disk.setBoot(true);
  disk.setAutoDelete(true);
  disk.setType("PERSISTENT");
  AttachedDiskInitializeParams params = new AttachedDiskInitializeParams();
  // Assign the Persistent Disk the same name as the VM Instance.
  params.setDiskName(instanceName);
  // Specify the source operating system machine image to be used by the VM Instance.
  params.setSourceImage(SOURCE_IMAGE_PREFIX + SOURCE_IMAGE_PATH);
  // Specify the disk type as Standard Persistent Disk
  params.setDiskType(
      String.format(
          "https://www.googleapis.com/compute/v1/projects/%s/zones/%s/diskTypes/pd-standard",
          PROJECT_ID, ZONE_NAME));
  disk.setInitializeParams(params);
  instance.setDisks(Collections.singletonList(disk));

  // Initialize the service account to be used by the VM Instance and set the API access scopes.
  ServiceAccount account = new ServiceAccount();
  account.setEmail("default");
  List<String> scopes = new ArrayList<>();
  scopes.add("https://www.googleapis.com/auth/devstorage.full_control");
  scopes.add("https://www.googleapis.com/auth/compute");
  account.setScopes(scopes);
  instance.setServiceAccounts(Collections.singletonList(account));

  // Optional - Add a startup script to be used by the VM Instance.
  Metadata meta = new Metadata();
  Metadata.Items item = new Metadata.Items();
  item.setKey("startup-script-url");
  // If you put a script called "vm-startup.sh" in this Google Cloud Storage
  // bucket, it will execute on VM startup.  This assumes you've created a
  // bucket named the same as your PROJECT_ID.
  // For info on creating buckets see:
  // https://cloud.google.com/storage/docs/cloud-console#_creatingbuckets
  item.setValue(String.format("gs://%s/vm-startup.sh", PROJECT_ID));
  meta.setItems(Collections.singletonList(item));
  instance.setMetadata(meta);

  System.out.println(instance.toPrettyString());
  Compute.Instances.Insert insert = compute.instances().insert(PROJECT_ID, ZONE_NAME, instance);
  return insert.execute();
}