使用 JavaScript 用戶端程式庫

本頁資訊將說明如何搭配使用 google-apis-javascript-client 程式庫與 Google Compute Engine。在本練習中,您需要使用 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 提出要求
  • 插入執行個體
  • 列出執行個體
  • 列出其他資源 (映像檔、機器類型、區域、網路、防火牆和作業)
  • 刪除執行個體

如要瞭解進階程式碼範例,請造訪 GoogleCloudPlatform GitHub 頁面。

載入用戶端程式庫

如要在應用程式中使用 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 用戶端密碼。如果沒有或想要註冊新應用程式,請按照以下步驟操作:

  1. 在 Google Cloud Platform 主控台中前往「Credentials」(憑證) 頁面。

    前往「憑證」頁面

  2. 按一下 [建立憑證],然後選取 [OAuth 用戶端 ID]。
  3. 如果這是您的第一個應用程式,系統會提示您建立同意聲明畫面;這個畫面會在應用程式要求存取使用者資料時顯示。請按一下 [設定同意畫面],接著在表單中填入應用程式相關資訊,然後儲存變更。
  4. 在「Create client ID」(建立用戶端 ID) 頁面中選取 [Web application] (網路應用程式),然後按一下 [Create] (建立)
  5. 輸入金鑰名稱,然後在 [已授權的 JavaScript 來源] 方塊中輸入應用程式來源網址。舉例來說,如果您在 myexampleapplication.com 中代管應用程式,來源網址便是 http://myexampleapplication.com。而要是您正在使用桌上型電腦或筆記型電腦測試應用程式,則可以使用 http://localhost
  6. 按一下 [建立] 以建立金鑰。
  7. 儲存用戶端 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
  });
}

除了 projectzone 欄位之外,您還可以新增結果大小上限、篩選執行個體及其他設定的欄位。如要查看這個方法的所有可能欄位清單,請參閱 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 retrieve 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 retrieve 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 retrieve 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 retrieve 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() 方法,並透過要求指定映像檔、區域、機器類型和網路介面物件:

/**
 * 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>

其他資源的網址如下:

資源 網址
機器類型 https://www.googleapis.com/compute/v1/projects/<project-id>/global/machineTypes/<machine-name>
區域 https://www.googleapis.com/compute/v1/projects/<project-id>/zones/<zone-name>
網路 https://www.googleapis.com/compute/v1/projects/<project-id>/global/networks/<network-name>

在網頁中加入以下指令列:

<!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>

重新整理瀏覽器頁面,然後按一下 [插入執行個體] 按鈕以建立新執行個體。建立後,按一下 [列出執行個體] 即可在執行個體清單中看到您新增的執行個體。

新增含有中繼資料的執行個體

建立執行個體時,您也可以傳遞自訂中繼資料。您可定義任何類型的自訂中繼資料,不過執行開機指令碼專用的自訂中繼資料特別實用。如要建立含有自訂中繼資料的執行個體,請在程式碼中新增 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() 方法並提供 instanceproject 欄位資料:

/**
 * 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>

重新整理頁面,然後按一下 [取得執行個體] 按鈕。

刪除執行個體

如要刪除執行個體,請使用 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>

重新整理頁面,然後按一下 [刪除執行個體] 按鈕。

刪除磁碟

如要刪除磁碟,請使用 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>

重新整理頁面,然後按一下 [刪除磁碟] 按鈕。

完整範例

以下是本練習的完整程式碼範例:

<!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 retrieve 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 retrieve 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>

後續步驟

完成本練習後:

本頁內容對您是否有任何幫助?請提供意見:

傳送您對下列選項的寶貴意見...

這個網頁
Compute Engine 說明文件