このページでは、Google Compute Engine で google-apis-javascript-client ライブラリを使用する方法について説明します。この演習では、JavaScript クライアント ライブラリを使用してリクエストを承認し、VM インスタンスの外部から Google Compute Engine リソースの作成、一覧表示、または削除を行います。
他の Google クライアント ライブラリやサードパーティのオープンソース ライブラリを含む使用可能なすべてのクライアント ライブラリについては、クライアント ライブラリのページをご覧ください。
このチュートリアルを完了するには、HTML と JavaScript についてのある程度の知識が必要です。
始める前に
- Google Compute Engine を初めて使用する場合は、クイックスタート チュートリアルのいずれかをお試しください。
- このチュートリアルで JavaScript の例を実行するには、ウェブサーバーを設定します。ラップトップまたはデスクトップを使用している場合は、Apache または Nginx などのウェブサーバーをマシンにインストールできます。Google Compute Engine インスタンスでウェブサーバーを設定するには、基本的な Apache ウェブサーバーの実行を参照してください。
はじめに
この例では、ウェブ アプリケーションで OAuth 2.0 による承認を使用する方法と、google-api-javascript-client ライブラリを使用してインスタンスを管理する方法について説明します。この演習を完了すると、次のことができるようになります。
- Google Compute Engine API にリクエストを送信するためのアプリケーションの承認
- インスタンスの挿入
- インスタンスの一覧取得
- 他のリソース(イメージ、マシンタイプ、ゾーン、ネットワーク、ファイアウォール、オペレーション)の一覧取得
- インスタンスの削除
高度なサンプルコードについては、GitHub の GoogleCloudPlatform ページをご覧ください。
クライアント ライブラリを読み込む
アプリケーションで JavaScript クライアント ライブラリを使用するには、最初にそれを読み込む必要があります。JavaScript クライアント ライブラリは次の場所にあります。
https://apis.google.com/js/client.js
クライアント ライブラリを読み込むベースとなる HTML ファイルを作成します。
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<link rel="stylesheet" src="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js"></script>
</head>
<body>
</body>
</html>
リクエストの承認
このサンプルでは、API キーとクライアント ID によるシンプルな承認方法を使用します。まず、すべてのアプリケーションを Google Cloud Platform Console で管理します。アプリケーションをすでに登録している場合は、そのアプリケーションからクライアント ID とクライアント シークレットを使用できます。登録済みのアプリケーションがない場合や新しいアプリケーションを登録する場合、手順は次のとおりです。
- Google Cloud Platform Console で、[認証情報] ページに移動します。
- [認証情報を作成] をクリックし、[OAuth クライアント ID] を選択します。
- 初めてアプリケーションを作成する場合は、アプリケーションがユーザーのデータへのアクセスを要求したときに表示される同意画面の作成を求めるプロンプトが表示されます。[同意画面の構成] をクリックし、アプリケーションに関する情報をフォームに入力します。変更を保存します。
- [クライアント ID の作成] ページで [ウェブ アプリケーション] を選択し、[作成] をクリックします。
- キーの名前を入力し、[承認済みの JavaScript 生成元] ボックスにアプリケーションの生成元 URI を入力します。たとえば、
myexampleapplication.com
でアプリケーションをホストしている場合、生成元 URI はhttp://myexampleapplication.com
です。デスクトップまたはラップトップでアプリケーションをテストする場合は、http://localhost
を使用できます。 - キーを作成するには、[作成] をクリックします。
- クライアント ID とクライアント シークレットを保存して、アプリケーションで使用できるようにします。
アプリケーションを承認するには、gapi.auth.authorize()
メソッドを使用して、以下の情報を提供します。
- クライアント ID
API_KEY
変数内のクライアント シークレット- コールバック関数
immediate
フィールドも生成されます。immediate
を true
に設定すると、承認はバックグラウンドで実行され、ユーザーにプロンプトが表示されません。
HTML ページに次のコードを追加します。
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<link rel="stylesheet" src="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js"></script>
<script type="text/javascript">
var PROJECT_ID = 'YOUR_PROJECT_ID';
var CLIENT_ID = 'YOUR_CLIENT_ID';
var API_KEY = 'YOUR_API_KEY';
var SCOPES = 'https://www.googleapis.com/auth/compute';
/**
* Authorize Google Compute Engine API.
*/
function authorization() {
gapi.client.setApiKey(API_KEY);
gapi.auth.authorize({
client_id: CLIENT_ID,
scope: SCOPES,
immediate: false
}, function(authResult) {
if (authResult && !authResult.error) {
window.alert('Auth was successful!');
} else {
window.alert('Auth was not successful');
}
}
);
}
/**
* Driver for sample application.
*/
$(window).load(authorization);
</script>
</head>
<body>
</body>
</html>
ブラウザでページを開きます。ページが読み込まれた後、アプリケーションの承認を求めるプロンプトが表示されます。アプリケーションを正常に承認すると、アプリケーションが正常に承認されたことを通知するアラートが表示されます。
アプリケーションでの Google Compute Engine API の初期化
次に、gapi.client.load()
を呼び出して API を初期化します。このメソッドは、API の名前とバージョン番号をパラメータとして受け取ります。HTML ページで、初期化関数を追加し、アプリケーションが正常に承認された後に呼び出します。
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<link rel="stylesheet" src="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js"></script>
<script type="text/javascript">
var PROJECT_ID = 'YOUR_PROJECT_ID';
var CLIENT_ID = 'YOUR_CLIENT_ID';
var API_KEY = 'YOUR_API_KEY';
var SCOPES = 'https://www.googleapis.com/auth/compute';
var API_VERSION = 'v1';
/**
* Load the Google Compute Engine API.
*/
function initializeApi() {
gapi.client.load('compute', API_VERSION);
}
/**
* Authorize Google Compute Engine API.
*/
function authorization() {
gapi.client.setApiKey(API_KEY);
gapi.auth.authorize({
client_id: CLIENT_ID,
scope: SCOPES,
immediate: false
}, function(authResult) {
if (authResult && !authResult.error) {
initializeApi();
} else {
window.alert('Auth was not successful');
}
}
);
}
/**
* Driver for sample application.
*/
$(window).load(authorization);
</script>
</head>
<body>
</body>
</html>
これで作業は完了です。API にリクエストを送信できるようになりました。
インスタンスの一覧取得
基本オペレーションを学習するには、まず特定のリソースを一覧表示するリクエストを作成します。ページに以下を追加します。
</head>
<body>
<header>
<h1>Google Compute Engine JavaScript Client Library Application</h1>
</header>
<button onclick="listInstances()">List Instances</button>
</body>
</html>
次に、listInstances()
関数を定義します。インスタンスの一覧を取得するには、gapi.client.compute.instances.list()
メソッドを使用します。
/**
* Google Compute Engine API request to retrieve the list of instances in
* your Google Compute Engine project.
*/
function listInstances() {
var request = gapi.client.compute.instances.list({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE
});
request.execute(function(resp) {
// Code to handle response
});
}
project
フィールドと zone
フィールドに加えて、結果の最大サイズ、インスタンスのフィルタ、その他の設定のためのフィールドを追加できます。このメソッドで使用できるすべてのフィールドのリストについては、API Explorer または API ドキュメントをご覧ください。
新しい listInstances()
関数を次のようにウェブページに追加します。
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<link rel="stylesheet" src="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js"></script>
<script type="text/javascript">
var PROJECT_ID = 'YOUR_PROJECT_ID';
var CLIENT_ID = 'YOUR_CLIENT_ID';
var API_KEY = 'YOUR_API_KEY';
var SCOPES = 'https://www.googleapis.com/auth/compute';
var API_VERSION = 'v1';
var DEFAULT_PROJECT = PROJECT_ID;
var DEFAULT_ZONE = 'ZONE_NAME'; // For example, us-central1-a
/**
* Load the Google Compute Engine API.
*/
function initializeApi() {
gapi.client.load('compute', API_VERSION);
}
/**
* Authorize Google Compute Engine API.
*/
function authorization() {
gapi.client.setApiKey(API_KEY);
gapi.auth.authorize({
client_id: CLIENT_ID,
scope: SCOPES,
immediate: false
}, function(authResult) {
if (authResult && !authResult.error) {
initializeApi();
} else {
window.alert('Auth was not successful');
}
}
);
}
/**
* Google Compute Engine API request to retrieve the list of instances in
* your Google Compute Engine project.
*/
function listInstances() {
var request = gapi.client.compute.instances.list({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE
});
executeRequest(request, 'listInstances');
}
/**
* Executes your Google Compute Engine request object and, subsequently,
* prints the response.
* @param {gapi.client.request} request A Google Compute Engine request
* object issued from the Google APIs JavaScript client library.
* @param {string} apiRequestName The name of the example API request.
*/
function executeRequest(request, apiRequestName) {
request.execute(function(resp) {
newWindow = window.open(apiRequestName, '',
'width=600, height=600, scrollbars=yes');
newWindow.document.write('<h1>' + apiRequestName + '</h1> <br />' +
'<pre>' + JSON.stringify(resp.result, null, ' ') + '</pre>');
if (resp.error) {
newWindow.document.write('<h1>Error:</h1>');
newWindow.document.write('<pre>' +
JSON.stringify(resp.error, null, ' ') + '</pre>');
}
});
}
/**
* Driver for sample application.
*/
$(window).load(authorization);
</script>
</head>
<body>
<header>
<h1>Google Compute Engine JavaScript Client Library Application</h1>
</header>
<button onclick="listInstances()">List Instances</button>
</body>
</html>
ページを更新し、新しい [インスタンスの一覧取得] ボタンをクリックすると、指定したプロジェクトに属するインスタンスの一覧が表示されます。
結果の一覧をフィルタする
filter
はフィールド リソースを一覧表示する際に便利な機能で、式に基づいて結果をフィルタリングします。たとえば、次のフィルタ式を使用して、終了したインスタンスを除外できます。
/**
* Google Compute Engine API request to retrieve a filtered list
* of instances in your Google Compute Engine project.
*/
function listInstancesWithFilter() {
var request = gapi.client.compute.instances.list({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE,
'filter': 'status ne TERMINATED'
});
var apiRequestName = 'listInstancesWithFilter';
executeRequest(request, apiRequestName);
}
その他のリソースの一覧を取得する
その他のリソースを一覧表示するには、以下のメソッドを使用します。
タイプ | メソッド |
---|---|
ゾーンの一覧 | gapi.client.compute.zones.list() |
マシンタイプの一覧 | gapi.client.compute.machinetypes.list() |
グローバル オペレーションの一覧 | gapi.client.compute.globalOperations.list() |
ゾーンごとのオペレーションの一覧 | gapi.client.compute.zoneOperations.list() |
イメージの一覧 | gapi.client.compute.images.list() |
ファイアウォールの一覧 | gapi.client.compute.firewalls.list() |
オペレーションの一覧取得
次のタイプの操作を一覧表示できます。
- ゾーンごとのオペレーションは、特定のゾーンにあるリソースに対して実行するオペレーションです。たとえば、ゾーンごとのオペレーションには、ディスクとインスタンスに対して実行するオペレーションが含まれます。
- グローバル オペレーションは、マシンタイプやイメージなどのグローバル リソースに対するオペレーションです。
ゾーンごと、グローバル リソースの詳細については、リージョンとゾーンの概要を参照してください。
ゾーンごとのオペレーションの一覧を取得する
ゾーンごとのオペレーションの一覧を表示するには、gapi.client.compute.zoneOperations.list()
メソッドを使用します。
/**
* Google Compute Engine API request to retreive the list of operations
* (inserts, deletes, etc.) for your Google Compute Engine project.
*/
function listZoneOperations() {
var request = gapi.client.compute.zoneOperations.list({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE
});
executeRequest(request, 'listZoneOperations');
}
ウェブページに次の行を追加します。
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<link rel="stylesheet" src="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js"></script>
<script type="text/javascript">
[...snip...]
/**
* Google Compute Engine API request to retreive the list of operations
* (inserts, deletes, etc.) for your Google Compute Engine project.
*/
function listZoneOperations() {
var request = gapi.client.compute.zoneOperations.list({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE
});
executeRequest(request, 'listZoneOperations');
}
/**
* Driver for sample application.
*/
$(window).load(authorization);
</script>
</head>
<body>
<header>
<h1>Google Compute Engine JavaScript Client Library Application</h1>
</header>
<button onclick="listInstances()">List Instances</button>
<button onclick="listZoneOperations()">List Zone Operations</button>
</body>
</html>
グローバル オペレーションの一覧を取得する
グローバル オペレーションの一覧を表示するには、gapi.client.compute.globalOperations.list()
メソッドを使用します。
/**
* Google Compute Engine API request to retreive the list of global
* operations (inserts, deletes, etc.) for your Google Compute Engine
* project.
*/
function listGlobalOperations() {
var request = gapi.client.compute.globalOperations.list({
'project': DEFAULT_PROJECT
});
executeRequest(request, 'listGlobalOperations');
}
ウェブページに次の行を追加します。
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<link rel="stylesheet" src="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js"></script>
<script type="text/javascript">
[...snip...]
/**
* Google Compute Engine API request to retreive the list of global
* operations (inserts, deletes, etc.) for your Google Compute Engine
* project.
*/
function listGlobalOperations() {
var request = gapi.client.compute.globalOperations.list({
'project': DEFAULT_PROJECT
});
executeRequest(request, 'listGlobalOperations');
}
/**
* Driver for sample application.
*/
$(window).load(authorization);
</script>
</head>
<body>
<header>
<h1>Google Compute Engine JavaScript Client Library Application</h1>
</header>
<button onclick="listInstances()">List Instances</button>
<button onclick="listZoneOperations()">List Zone Operations</button>
<button onclick="listGlobalOperations()">List Global Operations</button>
</body>
</html>
ディスクの追加
インスタンスを作成する前に、そのインスタンス用のブート可能なルート永続ディスクを用意する必要があります。ディスクを追加するには、gapi.client.compute.disks.insert()
メソッドを使用し、リクエストで名前、サイズ、ゾーン、およびソースイメージを指定します。
/**
* Google Compute Engine API request to insert a disk into your cluster.
*/
function insertDisk() {
var request = gapi.client.compute.disks.insert({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE,
'sourceImage': DEFAULT_IMAGE_URL,
'resource': {
'name': DEFAULT_DISK_NAME
}
});
executeRequest(request, 'insertDisk');
}
ウェブページに次の行を追加します。
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<link rel="stylesheet" src="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js"></script>
<script type="text/javascript">
[...snip...]
var DEFAULT_NAME = 'test-node';
var GOOGLE_PROJECT = 'debian-cloud'; // project hosting a shared image
var DEFAULT_DISK_NAME = DEFAULT_NAME;
var DEFAULT_IMAGE_FAMILY = 'debian-9';
var BASE_URL = 'https://www.googleapis.com/compute/' + API_VERSION;
var PROJECT_URL = BASE_URL + '/projects/' + DEFAULT_PROJECT;
var GOOGLE_PROJECT_URL = BASE_URL + '/projects/' + GOOGLE_PROJECT;
var DEFAULT_DISK_URL = PROJECT_URL + '/zones/' + DEFAULT_ZONE +
'/disks/' + DEFAULT_DISK_NAME;
var DEFAULT_IMAGE_URL = GOOGLE_PROJECT_URL + '/global/images/family/' +
DEFAULT_IMAGE_FAMILY;
[...snip...]
/**
* Google Compute Engine API request to insert a disk into your cluster.
*/
function insertDisk() {
var request = gapi.client.compute.disks.insert({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE,
'sourceImage': DEFAULT_IMAGE_URL,
'resource': {
'name': DEFAULT_DISK_NAME
}
});
executeRequest(request, 'insertDisk');
}
/**
* Driver for sample application.
*/
$(window).load(authorization);
</script>
</head>
<body>
<header>
<h1>Google Compute Engine JavaScript Client Library Application</h1>
</header>
<button onclick="listInstances()">List Instances</button>
<button onclick="listZoneOperations()">List Zone Operations</button>
<button onclick="listGlobalOperations()">List Global Operations</button>
<button onclick="insertDisk()">Add a Disk</button>
</body>
</html>
ブラウザでページを更新し、[ディスクを追加] ボタンをクリックして新しいディスクを作成します。
インスタンスの追加
インスタンスを挿入するには、gapi.client.compute.instances.insert()
メソッドを使用して、リクエストでイメージ、ゾーン、マシンタイプ、ネットワーク インターフェース オブジェクトを指定します。
/**使用可能なゾーン、イメージ、マシンタイプについては、それぞれのリソースページで説明しています。特定のリソースを指定する際には、そのリソースの完全な URL を指定します。たとえば、イメージを指定するには、次の例に示すようにイメージの完全な URL を指定する必要があります。
* Google Compute Engine API request to insert your instance
*/
function insertInstance() {
resource = {
'image': DEFAULT_IMAGE_URL,
'name': DEFAULT_IMAGE_NAME,
'machineType': DEFAULT_MACHINE_URL,
'disks': [{
'source': DEFAULT_DISK_URL,
'type': 'PERSISTENT',
'boot': true
}],
'networkInterfaces': [{
'network': DEFAULT_NETWORK
}]
};
var request = gapi.client.compute.instances.insert({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE,
'resource': resource
});
request.execute(function(resp) {
// Code to handle response
});
}
https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/<image-name>
他のリソースの URL は次のとおりです。
リソース | URL |
---|---|
マシンタイプ | https://www. |
ゾーン | https://www. |
ネットワーク | https://www. |
ウェブページに次の行を追加します。
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<link rel="stylesheet" src="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js"></script>
<script type="text/javascript">
[...snip...]
var DEFAULT_IMAGE_NAME = DEFAULT_NAME;
var DEFAULT_MACHINE_TYPE = 'n1-standard-1';
var DEFAULT_MACHINE_URL = PROJECT_URL + '/zones/' + DEFAULT_ZONE +
'/machineTypes/' + DEFAULT_MACHINE_TYPE;
var DEFAULT_NETWORK = PROJECT_URL + '/global/networks/default';
[...snip...]
/**
* Google Compute Engine API request to insert your instance
*/
function insertInstance() {
resource = {
'image': DEFAULT_IMAGE_URL,
'name': DEFAULT_IMAGE_NAME,
'machineType': DEFAULT_MACHINE_URL,
'disks': [{
'source': DEFAULT_DISK_URL,
'type': 'PERSISTENT',
'boot': true
}],
'networkInterfaces': [{
'network': DEFAULT_NETWORK
}]
};
var request = gapi.client.compute.instances.insert({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE,
'resource': resource
});
executeRequest(request, 'insertInstance');
}
/**
* Driver for sample application.
*/
$(window).load(authorization);
</script>
</head>
<body>
<header>
<h1>Google Compute Engine JavaScript Client Library Application</h1>
</header>
<button onclick="listInstances()">List Instances</button>
<button onclick="listZoneOperations()">List Zone Operations</button>
<button onclick="listGlobalOperations()">List Global Operations</button>
<button onclick="insertDisk()">Add a Disk</button>
<button onclick="insertInstance()">Add an Instance</button>
</body>
</html>
ブラウザでウェブページを更新し、[Insert an Instance] ボタンをクリックすると、新しいインスタンスが作成されます。[List Instances] ボタンをクリックすると、インスタンスの一覧に新しいインスタンスが表示されます。
メタデータを含むインスタンスの追加
インスタンスを作成するときに、カスタム メタデータを渡すこともできます。あらゆる種類のカスタム メタデータを定義できますが、起動スクリプトを実行するカスタム メタデータが特に便利です。カスタム メタデータを使用してインスタンスを作成するには、以下に示すように metadata
フィールドをコードに追加します。
/**
* Google Compute Engine API request to insert your instance with metadata
*/
function insertInstanceWithMetadata() {
resource = {
'image': DEFAULT_IMAGE_URL,
'name': 'node-with-metadata',
'machineType': DEFAULT_MACHINE_URL,
'disks': [{
'source': DEFAULT_DISK_URL,
'type': 'PERSISTENT',
'boot': true
}],
'networkInterfaces': [{
'network': DEFAULT_NETWORK
}],
'metadata': {
'items': [{
'value': 'apt-get install apache2',
'key': 'startup-script'
}]
}
};
var request = gapi.client.compute.instances.insert({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE,
'resource': resource
});
executeRequest(request, 'insertInstance');
}
このインスタンスのメタデータでは、apache2 をインストールする起動スクリプトを定義しています。
インスタンスを取得する
インスタンスに関する情報を取得するには、gapi.client.compute.instances.get()
メソッドを使用し、instance
フィールドと project
フィールドを指定します。
/**
* Google Compute Engine API request to get your instance
*/
function getInstance() {
var request = gapi.client.compute.instances.get({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE,
'instance': DEFAULT_IMAGE_NAME
});
request.execute(function(resp) {
// Code to handle response
});
}
ウェブページに次の行を追加します。
<!DOCTYPE html>
<head>
<meta charset='utf-8' />
<link rel="stylesheet" src="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js"></script>
<script type="text/javascript">
[...snip...]
/**
* Google Compute Engine API request to get your instance
*/
function getInstance() {
var request = gapi.client.compute.instances.get({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE,
'instance': DEFAULT_IMAGE_NAME
});
executeRequest(request, 'getInstance');
}
/**
* Driver for sample application.
*/
$(window).load(authorization);
</script>
</head>
<body>
<header>
<h1>Google Compute Engine JavaScript Client Library Application</h1>
</header>
<button onclick="listInstances()">List Instances</button>
<button onclick="listZoneOperations()">List Zone Operations</button>
<button onclick="listGlobalOperations()">List Global Operations</button>
<button onclick="insertDisk()">Insert a Disk</button>
<button onclick="insertInstance()">Insert an Instance</button>
<button onclick="getInstance()">Get an Instance</button>
</body>
</html>
ページを更新し、[Get an Instance] ボタンをクリックします。
インスタンスの削除
インスタンスを削除するには、gapi.client.compute.instances.delete()
メソッドを使用し、インスタンス名とプロジェクト ID を指定します。
/**
* Google Compute Engine API request to delete your instance
*/
function deleteInstance() {
var request = gapi.client.compute.instances.delete({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE,
'instance': DEFAULT_IMAGE_NAME
});
request.execute(function(resp) {
// Code to handle response
});
}
ウェブページに次の行を追加します。
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<link rel="stylesheet" src="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js"></script>
<script type="text/javascript">
[...snip...]
/**
* Google Compute Engine API request to delete your instance
*/
function deleteInstance() {
var request = gapi.client.compute.instances.delete({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE,
'instance': DEFAULT_IMAGE_NAME
});
executeRequest(request, 'deleteInstance');
}
/**
* Driver for sample application.
*/
$(window).load(authorization);
</script>
</head>
<body>
<header>
<h1>Google Compute Engine JavaScript Client Library Application</h1>
</header>
<button onclick="listInstances()">List Instances</button>
<button onclick="listZoneOperations()">List Zone Operations</button>
<button onclick="listGlobalOperations()">List Global Operations</button>
<button onclick="insertDisk()">Insert a Disk</button>
<button onclick="insertInstance()">Insert an Instance</button>
<button onclick="getInstance()">Get an Instance</button>
<button onclick="deleteInstance()">Delete an Instance</button>
</body>
</html>
ページを更新し、[Delete an Instance] ボタンをクリックします。
ディスクの削除
ディスクを削除するには、gapi.client.compute.disks.delete()
メソッドを使用して、ディスク名、プロジェクト ID、ゾーンを指定します。
/**
* Google Compute Engine API request to delete your disk
*/
function deleteDisk() {
var request = gapi.client.compute.disks.delete({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE,
'disk': DEFAULT_DISK_NAME
});
executeRequest(request, 'deleteDisk');
}
ページに次のコードを追加します。
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<link rel="stylesheet" src="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js"></script>
<script type="text/javascript">
[...snip...]
/**
* Google Compute Engine API request to delete your disk
*/
function deleteDisk() {
var request = gapi.client.compute.disks.delete({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE,
'disk': DEFAULT_DISK_NAME
});
executeRequest(request, 'deleteDisk');
}
/**
* Driver for sample application.
*/
$(window).load(authorization);
</script>
</head>
<body>
<header>
<h1>Google Compute Engine JavaScript Client Library Application</h1>
</header>
<button onclick="listInstances()">List Instances</button>
<button onclick="listZoneOperations()">List Zone Operations</button>
<button onclick="listGlobalOperations()">List Global Operations</button>
<button onclick="insertDisk()">Insert a Disk</button>
<button onclick="insertInstance()">Insert an Instance</button>
<button onclick="getInstance()">Get an Instance</button>
<button onclick="deleteInstance()">Delete an Instance</button>
<button onclick="deleteDisk()">Delete a disk</button>
</body>
</html>
ページを更新し、[Delete a Disk] ボタンをクリックします。
完全なサンプル
この演習のサンプルコード全体を次に示します。
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<link rel="stylesheet" src="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js"></script>
<script type="text/javascript">
var PROJECT_ID = 'YOUR_PROJECT_ID';
var CLIENT_ID = 'YOUR_CLIENT_ID';
var API_KEY = 'YOUR_API_KEY';
var SCOPES = 'https://www.googleapis.com/auth/compute';
var API_VERSION = 'v1';
var DEFAULT_PROJECT = PROJECT_ID;
var DEFAULT_ZONE = 'ZONE_NAME'; // For example, us-central1-a
var DEFAULT_NAME = 'test-node';
var GOOGLE_PROJECT = 'debian-cloud'; // project hosting a shared image
var DEFAULT_DISK_NAME = DEFAULT_NAME;
var DEFAULT_IMAGE_FAMILY = 'debian-9';
var BASE_URL = 'https://www.googleapis.com/compute/' + API_VERSION;
var PROJECT_URL = BASE_URL + '/projects/' + DEFAULT_PROJECT;
var GOOGLE_PROJECT_URL = BASE_URL + '/projects/' + GOOGLE_PROJECT;
var DEFAULT_DISK_URL = PROJECT_URL + '/zones/' + DEFAULT_ZONE +
'/disks/' + DEFAULT_DISK_NAME;
var DEFAULT_IMAGE_URL = GOOGLE_PROJECT_URL + '/global/images/family/' +
DEFAULT_IMAGE_FAMILY;
var DEFAULT_IMAGE_NAME = DEFAULT_NAME;
var DEFAULT_MACHINE_TYPE = 'n1-standard-1';
var DEFAULT_MACHINE_URL = PROJECT_URL + '/zones/' + DEFAULT_ZONE +
'/machineTypes/' + DEFAULT_MACHINE_TYPE;
var DEFAULT_NETWORK = PROJECT_URL + '/global/networks/default';
/**
* Authorize Google Compute Engine API.
*/
function authorization() {
gapi.client.setApiKey(API_KEY);
gapi.auth.authorize({
client_id: CLIENT_ID,
scope: SCOPES,
immediate: false
}, function(authResult) {
if (authResult && !authResult.error) {
initializeApi();
} else {
window.alert('Auth was not successful');
}
}
);
}
/**
* Load the Google Compute Engine API.
*/
function initializeApi() {
gapi.client.load('compute', API_VERSION);
}
/**
* Executes your Google Compute Engine request object and, subsequently,
* prints the response.
* @param {gapi.client.request} request A Google Compute Engine request
* object issued from the Google APIs JavaScript client library.
* @param {string} apiRequestName The name of the example API request.
*/
function executeRequest(request, apiRequestName) {
request.execute(function(resp) {
newWindow = window.open(apiRequestName, '',
'width=600, height=600, scrollbars=yes');
newWindow.document.write('<h1>' + apiRequestName + '</h1> <br />' +
'<pre>' + JSON.stringify(resp.result, null, ' ') + '</pre>');
if (resp.error) {
newWindow.document.write('<h1>Error:</h1>');
newWindow.document.write('<pre>' +
JSON.stringify(resp.error, null, ' ') + '</pre>');
}
});
}
/**
* Google Compute Engine API request to delete your instance
*/
function deleteInstance() {
var request = gapi.client.compute.instances.delete({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE,
'instance': DEFAULT_IMAGE_NAME
});
executeRequest(request, 'deleteInstance');
}
/**
* Google Compute Engine API request to delete your disk
*/
function deleteDisk() {
var request = gapi.client.compute.disks.delete({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE,
'disk': DEFAULT_DISK_NAME
});
executeRequest(request, 'deleteDisk');
}
/**
* Google Compute Engine API request to get your instance
*/
function getInstance() {
var request = gapi.client.compute.instances.get({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE,
'instance': DEFAULT_IMAGE_NAME
});
executeRequest(request, 'getInstance');
}
/**
* Google Compute Engine API request to insert a disk into your cluster.
*/
function insertDisk() {
var request = gapi.client.compute.disks.insert({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE,
'sourceImage': DEFAULT_IMAGE_URL,
'resource': {
'name': DEFAULT_DISK_NAME
}
});
executeRequest(request, 'insertDisk');
}
/**
* Google Compute Engine API request to insert your instance with metadata
*/
function insertInstanceWithMetadata() {
resource = {
'image': DEFAULT_IMAGE_URL,
'name': 'node-with-metadata',
'machineType': DEFAULT_MACHINE_URL,
'disks': [{
'source': DEFAULT_DISK_URL,
'type': 'PERSISTENT',
'boot': true
}],
'networkInterfaces': [{
'network': DEFAULT_NETWORK
}],
'metadata': {
'items': [{
'value': 'apt-get install apache2',
'key': 'startup-script'
}]
}
};
var request = gapi.client.compute.instances.insert({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE,
'resource': resource
});
executeRequest(request, 'insertInstance');
}
/**
* Google Compute Engine API request to insert your instance
*/
function insertInstance() {
resource = {
'image': DEFAULT_IMAGE_URL,
'name': DEFAULT_IMAGE_NAME,
'machineType': DEFAULT_MACHINE_URL,
'disks': [{
'source': DEFAULT_DISK_URL,
'type': 'PERSISTENT',
'boot': true
}],
'networkInterfaces': [{
'network': DEFAULT_NETWORK
}]
};
var request = gapi.client.compute.instances.insert({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE,
'resource': resource
});
executeRequest(request, 'insertInstance');
}
/**
* Google Compute Engine API request to retreive the list of global
* operations (inserts, deletes, etc.) for your Google Compute Engine
* project.
*/
function listGlobalOperations() {
var request = gapi.client.compute.globalOperations.list({
'project': DEFAULT_PROJECT
});
executeRequest(request, 'listGlobalOperations');
}
/**
* Google Compute Engine API request to retreive the list of operations
* (inserts, deletes, etc.) for your Google Compute Engine project.
*/
function listZoneOperations() {
var request = gapi.client.compute.zoneOperations.list({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE
});
executeRequest(request, 'listZoneOperations');
}
/**
* Google Compute Engine API request to retrieve a filtered list
* of instances in your Google Compute Engine project.
*/
function listInstancesWithFilter() {
var request = gapi.client.compute.instances.list({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE,
'filter': 'status ne TERMINATED'
});
var apiRequestName = 'listInstancesWithFilter';
executeRequest(request, apiRequestName);
}
/**
* Google Compute Engine API request to retrieve the list of instances in
* your Google Compute Engine project.
*/
function listInstances() {
var request = gapi.client.compute.instances.list({
'project': DEFAULT_PROJECT,
'zone': DEFAULT_ZONE
});
executeRequest(request, 'listInstances');
}
/**
* Driver for sample application.
*/
$(window).load(authorization);
</script>
</head>
<body>
<header>
<h1>Google Compute Engine JavaScript Client Library Application</h1>
</header>
<button onclick="listInstances()">List Instances</button>
<button onclick="listInstancesWithFilter()">List Instances with Filter</button>
<button onclick="listZoneOperations()">List Zone Operations</button>
<button onclick="listGlobalOperations()">List Global Operations</button>
<button onclick="insertDisk()">Insert a Disk</button>
<button onclick="insertInstance()">Insert an Instance</button>
<button onclick="insertInstanceWithMetadata()">Insert Instance with Metadata</button>
<button onclick="getInstance()">Get an Instance</button>
<button onclick="deleteInstance()">Delete an Instance</button>
<button onclick="deleteDisk()">Delete a disk</button>
</body>
</html>
次のステップ
この演習を完了したので、次のことができます。
- GitHub の googlecloudplatform のページから他のサンプルをダウンロードして確認する。より複雑なディスパッチ メソッドやもっとわかりやすいサンプルなど、高度なサンプルが用意されています。
- Python クライアント ライブラリを使用する場合は、Python クライアント ライブラリの使用を参照してください。
- API でその他のタスクを実行する方法については、API リファレンスを参照してください。
- 独自のアプリケーションを作成する。