Compute Engine 用戶端程式庫

本頁面說明如何開始使用 Compute Engine API 適用的 Cloud 用戶端程式庫。用戶端程式庫可讓您更輕鬆地透過支援的語言存取Google Cloud API。雖然您可以直接向伺服器發出原始要求來使用Google Cloud API,但用戶端程式庫提供簡化功能,可大幅減少您需要編寫的程式碼數量。

如要進一步瞭解 Cloud 用戶端程式庫和舊版 Google API 用戶端程式庫,請參閱「用戶端程式庫說明」。


如要直接在 Google Cloud 控制台中按照逐步指南操作,請按一下「Guide me」(逐步引導)

逐步引導


安裝用戶端程式庫

C++

請按照 Quickstart 操作。

C#

從 NuGet 安裝 Google.Cloud.Compute.V1 套件。

詳情請參閱「設定 C# 開發環境」。

Go

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

詳情請參閱「設定 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.59.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

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

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

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

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

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

舊版 Compute Engine 適用的 Java 適用 Cloud 用戶端程式庫可在 Maven 構件中取得,版本為 0.120.x 或更早版本。此程式庫的 0.120.x 以下版本與後續版本不相容。

詳情請參閱「設定 Java 開發環境」一文。

Node.js

npm install @google-cloud/compute

適用於 Compute Engine 的 Node.js 適用 Cloud 用戶端程式庫舊版可在 npm 套件中取得,版本為 2.5.x 或更早版本。此程式庫的 2.5.x 以下版本與後續版本不相容。

詳情請參閱「設定 Node.js 開發環境」一文。

PHP

composer require google/cloud-compute

詳情請參閱「在 Google Cloud 上使用 PHP」。

Python

pip install --upgrade google-cloud-compute

詳情請參閱「設定 Python 開發環境」一文。

Ruby

gem install google-cloud-compute-v1

詳情請參閱「設定 Ruby 開發環境」一文。

設定驗證方法

為了驗證對 Google Cloud API 的呼叫,用戶端程式庫支援應用程式預設憑證 (ADC);這些程式庫會在一系列定義的位置尋找憑證,然後使用這些憑證驗證對 API 的要求。有了 ADC,您就能在各種環境 (例如本機開發或正式版) 中為應用程式提供憑證,而無需修改應用程式程式碼。

在實際工作環境中,您設定 ADC 的方式取決於服務和情境。詳情請參閱「設定應用程式預設憑證」。

如果是本機開發環境,您可以使用與 Google 帳戶相關聯的憑證設定 ADC:

  1. After installing the Google Cloud CLI, initialize it by running the following command:

    gcloud init

    If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  2. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    系統隨即會顯示登入畫面。登入後,憑證會儲存在 ADC 使用的本機憑證檔案中。

使用用戶端程式庫

以下範例說明如何使用用戶端程式庫列出特定區域中的執行個體。如需更多範例,請參閱「使用用戶端程式庫」。

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

其他資源

C++

以下清單列出與 C++ 用戶端程式庫相關的更多資源連結:

C#

以下列表包含與 C# 用戶端程式庫相關的更多資源連結:

Go

以下清單包含與 Go 用戶端程式庫相關的更多資源連結:

Java

下列清單包含適用於 Java 用戶端程式庫的更多資源連結:

Node.js

以下清單列出與 Node.js 用戶端程式庫相關的更多資源連結:

PHP

下列清單包含與 PHP 用戶端程式庫相關的更多資源連結:

Python

以下清單包含與 Python 用戶端程式庫相關的更多資源連結:

Ruby

以下清單包含與 Ruby 用戶端程式庫相關的更多資源連結:

舊版用戶端程式庫

Cloud 用戶端程式庫採用我們最新的用戶端程式庫模型,且在可用的情況下,建議您使用這個選項,以程式輔助的方式存取 Cloud API。

如果您無法使用 Cloud 用戶端程式庫,可以使用下列 Google API 用戶端程式庫

語言 程式庫 資源
Go Google API Go 用戶端程式庫 說明文件
Java Google API Java 用戶端程式庫 說明文件
JavaScript Google API JavaScript 用戶端程式庫 說明文件
.NET Google API .NET 用戶端程式庫 說明文件
Node.js Google API Node.js 用戶端程式庫 說明文件
Objective-C Google API Objective-C 用戶端程式庫 說明文件
PHP Google API PHP 用戶端程式庫 說明文件
Python Google API Python 用戶端程式庫 說明文件
Ruby Google API Ruby 用戶端程式庫 說明文件
Dart Google API Dart 用戶端程式庫 說明文件

第三方 Compute Engine API 用戶端程式庫

libcloud

libcloud 是 Python 程式庫,可透過單一統一 API 與多個雲端服務供應商互動。

自 2013 年 7 月起,Apache libcloud API 專案已開始支援 Compute Engine 並提供更新。它支援多項 Compute Engine 功能,包括執行個體、磁碟、網路和負載平衡器。這項入門示範提供程式碼範例,說明如何同時使用 libcloud 和 Compute Engine。

jclouds

jclouds 是一個開放原始碼程式庫,可讓您透過多個 Cloud 供應商使用 Java 和 Clojure。

jclouds cloud API 支援 Compute Engine,可讓您管理虛擬機器、磁碟和網路等資源。自 1.9 版起,Compute Engine 已升級至 jclouds 核心。

fog.io

fog.io 是一個開放原始碼 Ruby 程式庫,可讓您透過單一 API 與多種雲端服務互動。

自 2013 年 5 月的 1.11.0 版起,fog.io cloud API 已開始支援 Compute Engine。它支援建立和刪除等執行個體作業,以及磁碟、網路和負載平衡器等其他資源的管理作業。