Compute Engine クライアント ライブラリ

このページでは、Compute Engine API の Cloud クライアント ライブラリの使用方法を説明します。クライアント ライブラリを使用すると、サポートされている言語で Google Cloud APIs に簡単にアクセスできます。サーバーにリクエストを送信して Google Cloud APIs を直接利用することもできますが、クライアント ライブラリを使用すると、記述するコードの量を大幅に削減できます。

Cloud クライアント ライブラリと以前の Google API クライアント ライブラリの詳細については、クライアント ライブラリの説明をご覧ください。


このタスクの手順をガイドに沿って Google Cloud コンソールで直接行う場合は、[ガイドを表示] をクリックしてください。

ガイドを表示


クライアント ライブラリをインストールする

C++

Quickstart に沿って操作します。

C#

NuGet から Google.Cloud.Compute.V1 パッケージをインストールします。

詳細については、C# 開発環境の設定をご覧ください。

Go

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

詳細については、Go 開発環境の設定をご覧ください。

Java

Maven を使用している場合は、以下を pom.xml ファイルに追加します。BOM の詳細については、Google Cloud Platform ライブラリ 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>

Gradle を使用している場合は、以下を依存関係に追加します。

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

sbt を使用している場合は、以下を依存関係に追加します。

libraryDependencies += "com.google.cloud" % "google-cloud-compute" % "1.51.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 APIs の呼び出しを認証するために、クライアント ライブラリではアプリケーションのデフォルト認証情報(ADC)がサポートされています。このライブラリは、一連の定義済みのロケーションの中から認証情報を探し、その認証情報を使用して API へのリクエストを認証します。ADC を使用すると、アプリケーション コードを変更することなく、ローカルでの開発や本番環境など、さまざまな環境のアプリケーションで認証情報を使用できるようになります。

本番環境では、ADC の設定方法はサービスとコンテキストによって異なります。詳細については、アプリケーションのデフォルト認証情報を設定するをご覧ください。

ローカル開発環境では、Google アカウントに関連付けられている認証情報を使用して ADC を設定できます。

  1. gcloud CLI をインストールして初期化します

    gcloud CLI を初期化するときは、アプリケーションに必要なリソースにアクセスする権限がある Google Cloud プロジェクトを指定してください。

  2. 認証情報ファイルを作成します。

    gcloud auth application-default login

    ログイン画面が表示されます。ログインすると、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 APIs にプログラムからアクセスする場合は、このライブラリを使用することをおすすめします。

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 は、1 つに統合された API を介して複数のクラウド サービス プロバイダとやり取りするために使用する Python ライブラリです。

Apache libcloud API プロジェクトでは、2013 年 7 月から Compute Engine 向けのサポートとアップデートが実施されてきました。この API は、インスタンス、ディスク、ネットワーク、ロードバランサなど、Compute Engine の幅広い機能をサポートしています。スタートガイドのデモでは、libcloud と Compute Engine を併用するコード例を紹介します。

jclouds

jclouds は、複数のクラウド プロバイダで Java と Clojure を使えるようにするオープンソース ライブラリです。

jclouds cloud API は Compute Engine をサポートし、仮想マシン、ディスク、ネットワークなどのリソースを管理できるようにします。バージョン 1.9 より、Compute Engine は、jclouds コアに組み込まれました。

fog.io

fog.io は、1 つの API で複数のクラウド サービスとのやり取りを可能にするオープンソース Ruby ライブラリです。

fog.io クラウド API は、2013 年 5 月にリリースされたバージョン 1.11.0 より、Compute Engine をサポートしています。fog.io クラウド API は、作成、削除などのインスタンス オペレーションと、ディスク、ネットワーク、ロードバランサなどのリソースの管理オペレーションをサポートしています。