Library klien Compute Engine

Halaman ini menunjukkan cara memulai Library Klien Cloud untuk Compute Engine API. Library klien mempermudah akses Google Cloud API dari bahasa yang didukung. Meskipun Anda dapat langsung menggunakan Google Cloud API dengan membuat permintaan mentah ke server, library klien memberikan penyederhanaan yang secara signifikan mengurangi jumlah kode yang perlu Anda tulis.

Baca lebih lanjut tentang Library Klien Cloud dan Library Klien Google API lama di Penjelasan library klien.


Jika ingin mengikuti panduan langkah demi langkah untuk tugas ini langsung di Konsol Google Cloud, klik Pandu saya:

Pandu saya


Menginstal library klien

C++

Ikuti Quickstart.

C#

Instal Google.Cloud.Compute.V1 paket dari NuGet.

Untuk informasi selengkapnya, lihat Menyiapkan Lingkungan Pengembangan C#.

Go

go get cloud.google.com/go/compute/apiv1

Untuk informasi selengkapnya, lihat Menyiapkan Lingkungan Pengembangan Go.

Java

If you are using Maven, add the following to your pom.xml file. For more information about BOMs, see The Google Cloud Platform Libraries BOM.

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.37.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-compute</artifactId>
  </dependency>

If you are using Gradle, add the following to your dependencies:

implementation 'com.google.cloud:google-cloud-compute:1.51.0'

If you are using sbt, add the following to your dependencies:

libraryDependencies += "com.google.cloud" % "google-cloud-compute" % "1.51.0"

Library Klien Cloud versi lama untuk Java untuk Compute Engine tersedia sebagai versi 0.120.x atau yang lebih lama di artefak Maven. Versi 0.120.x dan versi sebelumnya dari library ini tidak kompatibel dengan versi yang lebih baru.

Untuk informasi selengkapnya, lihat Menyiapkan Lingkungan Pengembangan Java.

Node.js

npm install @google-cloud/compute

Library Klien Cloud versi lama untuk Node.js untuk Compute Engine tersedia sebagai versi 2.5.x atau yang lebih lama di paket npm. Versi 2.5.x dan versi sebelumnya dari library ini tidak kompatibel dengan versi yang lebih baru.

Untuk informasi selengkapnya, lihat Menyiapkan Lingkungan Pengembangan Node.js.

PHP

composer require google/cloud-compute

Untuk informasi selengkapnya, lihat Menggunakan PHP di Google Cloud.

Python

pip install --upgrade google-cloud-compute

Untuk informasi selengkapnya, lihat Menyiapkan Lingkungan Pengembangan Python.

Ruby

gem install google-cloud-compute-v1

Untuk informasi selengkapnya, lihat Menyiapkan Lingkungan Pengembangan Ruby.

Menyiapkan autentikasi

Untuk mengautentikasi panggilan ke Google Cloud API, library klien mendukung Kredensial Default Aplikasi (ADC); library akan mencari kredensial di sekumpulan lokasi yang ditentukan dan menggunakan kredensial tersebut untuk mengautentikasi permintaan ke API. Dengan ADC, Anda dapat membuat kredensial tersedia untuk aplikasi di berbagai lingkungan, seperti produksi atau pengembangan lokal, tanpa perlu mengubah kode aplikasi.

Untuk lingkungan produksi, cara Anda menyiapkan ADC bergantung pada layanan dan konteks. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan Kredensial Default Aplikasi.

Untuk lingkungan pengembangan lokal, Anda dapat menyiapkan ADC dengan kredensial yang terkait dengan Akun Google Anda:

  1. Instal dan lakukan inisialisasi gcloud CLI.

    Saat melakukan inisialisasi gcloud CLI, pastikan untuk menentukan project Google Cloud yang izinnya Anda miliki untuk mengakses resource yang dibutuhkan aplikasi Anda.

  2. Buat file kredensial Anda:

    gcloud auth application-default login

    Layar login akan muncul. Setelah Anda login, kredensial Anda akan disimpan di file kredensial lokal yang digunakan oleh ADC.

Menggunakan library klien

Contoh berikut menunjukkan cara menggunakan library klien untuk mencantumkan instance di zona tertentu. Untuk melihat contoh lainnya, lihat Menggunakan library klien.

C#


using Google.Cloud.Compute.V1;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

public class ListZoneInstancesAsyncSample
{
    public async Task<IList<Instance>> ListZoneInstancesAsync(
        // TODO(developer): Set your own default values for these parameters or pass different values when calling this method.
        string projectId = "your-project-id",
        string zone = "us-central1-a")
    {
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        InstancesClient client = await InstancesClient.CreateAsync();
        IList<Instance> allInstances = new List<Instance>();

        // Make the request to list all VM instances in the given zone in the specified project.
        await foreach(var instance in client.ListAsync(projectId, zone))
        {
            // The result is an Instance collection.
            Console.WriteLine($"Instance: {instance.Name}");
            allInstances.Add(instance);
        }

        return allInstances;
    }
}

Go

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "cloud.google.com/go/compute/apiv1/computepb"
	"google.golang.org/api/iterator"
)

// listInstances prints a list of instances created in given project in given zone.
func listInstances(w io.Writer, projectID, zone string) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	ctx := context.Background()
	instancesClient, err := compute.NewInstancesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewInstancesRESTClient: %w", err)
	}
	defer instancesClient.Close()

	req := &computepb.ListInstancesRequest{
		Project: projectID,
		Zone:    zone,
	}

	it := instancesClient.List(ctx, req)
	fmt.Fprintf(w, "Instances found in zone %s:\n", zone)
	for {
		instance, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return err
		}
		fmt.Fprintf(w, "- %s %s\n", instance.GetName(), instance.GetMachineType())
	}
	return nil
}

Java


import com.google.cloud.compute.v1.Instance;
import com.google.cloud.compute.v1.InstancesClient;
import java.io.IOException;

public class ListInstance {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample
    String project = "your-project-id";
    String zone = "zone-name";
    listInstances(project, zone);
  }

  // List all instances in the given zone in the specified project ID.
  public static void listInstances(String project, String zone) throws IOException {
    // 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()) {
      // Set the project and zone to retrieve instances present in the zone.
      System.out.printf("Listing instances from %s in %s:", project, zone);
      for (Instance zoneInstance : instancesClient.list(project, zone).iterateAll()) {
        System.out.println(zoneInstance.getName());
      }
      System.out.println("####### Listing instances complete #######");
    }
  }
}

Node.js

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const zone = 'europe-central2-b'

const compute = require('@google-cloud/compute');

// List all instances in the given zone in the specified project.
async function listInstances() {
  const instancesClient = new compute.InstancesClient();

  const [instanceList] = await instancesClient.list({
    project: projectId,
    zone,
  });

  console.log(`Instances found in zone ${zone}:`);

  for (const instance of instanceList) {
    console.log(` - ${instance.name} (${instance.machineType})`);
  }
}

listInstances();

PHP

use Google\Cloud\Compute\V1\Client\InstancesClient;
use Google\Cloud\Compute\V1\ListInstancesRequest;

/**
 * List all instances for a particular Cloud project and zone.
 *
 * @param string $projectId Your Google Cloud project ID.
 * @param string $zone Zone to list instances for (like "us-central1-a").
 *
 * @throws \Google\ApiCore\ApiException if the remote call fails.
 */
function list_instances(string $projectId, string $zone)
{
    // List Compute Engine instances using InstancesClient.
    $instancesClient = new InstancesClient();
    $request = (new ListInstancesRequest())
        ->setProject($projectId)
        ->setZone($zone);
    $instancesList = $instancesClient->list($request);

    printf('Instances for %s (%s)' . PHP_EOL, $projectId, $zone);
    foreach ($instancesList as $instance) {
        printf(' - %s' . PHP_EOL, $instance->getName());
    }
}

Python

from __future__ import annotations

from collections.abc import Iterable

from google.cloud import compute_v1

def list_instances(project_id: str, zone: str) -> Iterable[compute_v1.Instance]:
    """
    List all instances in the given zone in the specified project.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        zone: name of the zone you want to use. For example: “us-west3-b”
    Returns:
        An iterable collection of Instance objects.
    """
    instance_client = compute_v1.InstancesClient()
    instance_list = instance_client.list(project=project_id, zone=zone)

    print(f"Instances found in zone {zone}:")
    for instance in instance_list:
        print(f" - {instance.name} ({instance.machine_type})")

    return instance_list

Ruby


require "google/cloud/compute/v1"

# Lists all instances in the given zone in the specified project.
#
# @param [String] project project ID or project number of the Cloud project you want to use.
# @param [String] zone name of the zone you want to use. For example: "us-west3-b"
# @return [Array<::Google::Cloud::Compute::V1::Instance>] Array of instances.
def list_instances project:, zone:
  # Initialize client that will be used to send requests. This client only needs to be created
  # once, and can be reused for multiple requests.
  client = ::Google::Cloud::Compute::V1::Instances::Rest::Client.new

  # Send the request to list all VM instances in the given zone in the specified project.
  instance_list = client.list project: project, zone: zone

  puts "Instances found in zone #{zone}:"
  instances = []
  instance_list.each do |instance|
    puts " - #{instance.name} (#{instance.machine_type})"
    instances << instance
  end
  instances
end

Referensi tambahan

C++

Daftar berikut berisi link ke resource lainnya terkait library klien untuk C++:

C#

Daftar berikut berisi link ke resource lainnya yang terkait dengan library klien untuk C#:

Go

Daftar berikut berisi link ke resource lainnya terkait library klien untuk Go:

Java

Daftar berikut berisi link ke resource lainnya terkait library klien untuk Java:

Node.js

Daftar berikut berisi link ke resource lainnya yang terkait dengan library klien untuk Node.js:

PHP

Daftar berikut berisi link ke resource lainnya terkait library klien untuk PHP:

Python

Daftar berikut berisi link ke lebih banyak referensi terkait library klien untuk Python:

Ruby

Daftar berikut berisi link ke resource lainnya yang terkait dengan library klien untuk Ruby:

Library klien lama

Library Klien Cloud menggunakan model library klien terbaru kami dan merupakan opsi yang direkomendasikan untuk mengakses Cloud API secara terprogram.

Jika Anda tidak dapat menggunakan Library Klien Cloud, tersedia Library Klien Google API berikut:

Language Library Referensi
Go Library Klien Go Google API Dokumentasi
Java Library Klien Java Google API Dokumentasi
JavaScript Library Klien JavaScript Google API Dokumentasi
.NET Library Klien .NET Google API Dokumentasi
Node.js Library Klien Node.js Google API Dokumentasi
Objective-C Library Klien Objective-C Google API Dokumentasi
PHP Library Klien PHP Google API Dokumentasi
Python Library Klien Python Google API Dokumentasi
Ruby Library Klien Ruby Google API Dokumentasi
Dart Library Klien Dart Google API Dokumentasi

Library klien Compute Engine API pihak ketiga

libcloud

libcloud adalah library Python yang digunakan untuk berinteraksi dengan beberapa penyedia layanan cloud melalui satu API terpadu.

Project Apache libcloud API telah menerima dukungan dan update untuk Compute Engine sejak Juli 2013. Platform ini mendukung berbagai fitur Compute Engine termasuk instance, disk, jaringan, dan load balancer. Demo cara memulai memberikan contoh kode tentang cara menggunakan libcloud dan Compute Engine secara bersamaan.

jclouds

jclouds adalah library open source yang memungkinkan Anda menggunakan Java dan Clojure di beberapa penyedia Cloud.

cloud API jclouds mendukung Compute Engine dan memungkinkan Anda mengelola resource seperti virtual machine, disk, dan jaringan. Mulai versi 1.9, Compute Engine dipromosikan ke inti jclouds.

fog.io

fog.io adalah library Ruby open source yang memungkinkan Anda berinteraksi dengan beberapa layanan cloud melalui satu API.

API cloud fog.io telah mendukung Compute Engine sejak versi 1.11.0 pada Mei 2013. Platform ini mendukung operasi instance seperti buat dan hapus, serta operasi pengelolaan untuk resource lain seperti disk, jaringan, dan load balancer.