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

The following examples show how to use com.google.api.services.compute.model.Metadata. 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: GoogleDistributedService.java    From halyard with Apache License 2.0 4 votes vote down vote up
default List<Metadata.Items> getMetadata(
    AccountDeploymentDetails<GoogleAccount> details,
    SpinnakerRuntimeSettings runtimeSettings,
    List<ConfigSource> configSources,
    Integer version) {
  List<Metadata.Items> metadataItems = new ArrayList<>();
  String deploymentName = details.getDeploymentName();

  Metadata.Items items =
      new Metadata.Items().setKey("startup-script").setValue(getStartupScript());
  metadataItems.add(items);

  items = new Metadata.Items().setKey("ssh-keys").setValue(GoogleProviderUtils.getSshPublicKey());
  metadataItems.add(items);

  if (!configSources.isEmpty()) {
    DaemonTaskHandler.message("Mounting config in vault server");
    GoogleVaultServerService vaultService = getVaultServerService();
    VaultServerService.Vault vault =
        vaultService.connectToPrimaryService(details, runtimeSettings);

    String secretName = secretName("config-mounts", version);
    VaultConfigMountSet mountSet = VaultConfigMountSet.fromConfigSources(configSources);
    secretName =
        vaultService.writeVaultConfigMountSet(deploymentName, vault, secretName, mountSet);

    VaultConnectionDetails connectionDetails =
        buildConnectionDetails(details, runtimeSettings, secretName);

    DaemonTaskHandler.message("Placing vault connection details into instance metadata");
    items = new Metadata.Items().setKey("vault_address").setValue(connectionDetails.getAddress());
    metadataItems.add(items);

    items = new Metadata.Items().setKey("vault_token").setValue(connectionDetails.getToken());
    metadataItems.add(items);

    items = new Metadata.Items().setKey("vault_secret").setValue(connectionDetails.getSecret());
    metadataItems.add(items);
  }

  GoogleConsulServerService consulServerService = getConsulServerService();
  RunningServiceDetails consulServerDetails =
      consulServerService.getRunningServiceDetails(details, runtimeSettings);
  Integer latestConsulVersion = consulServerDetails.getLatestEnabledVersion();
  if (latestConsulVersion != null) {
    List<RunningServiceDetails.Instance> instances =
        consulServerDetails.getInstances().get(latestConsulVersion);
    String instancesValue =
        String.join(
            " ",
            instances.stream()
                .map(RunningServiceDetails.Instance::getId)
                .collect(Collectors.toList()));

    items =
        new Metadata.Items()
            .setKey("consul-members") // TODO(lwander) change to consul_members for consistency w/
            // vault
            .setValue(instancesValue);

    DaemonTaskHandler.message("Placing consul connection details into instance metadata");
    metadataItems.add(items);
  }

  return metadataItems;
}
 
Example #2
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();
}
 
Example #3
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());
    }
}