使用 JavaScript 客户端库

本页面演示如何配合 Google Compute Engine 使用 google-apis-javascript-client 库。在本练习中,您使用 JavaScript 客户端库来授权请求,并从虚拟机实例外部创建、列出或删除 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 Console 中,转到“凭据”页面。

    转到“凭据”页面

  2. 点击创建凭据并选择 OAuth 客户端 ID
  3. 如果这是您的第一个应用,则系统将提示您创建一个同意屏幕,当您的应用请求访问用户数据时,会显示该屏幕。点击配置同意屏幕,在表单中填写应用的相关信息。保存更改。
  4. 在“创建客户端 ID”页面上,选择网络应用,然后点击创建
  5. 键入密钥的名称,然后在已获授权的 JavaScript 来源框中,键入应用的来源 URI。例如,如果您在 myexampleapplication.com 上托管应用,则来源 URI 为 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

接下来,您通过调用接受 API 名称和 API 版本号作为参数的 gapi.client.load() 来初始化 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>

在浏览器中刷新页面,然后点击添加磁盘 (Add a Disk) 按钮以创建新磁盘。

添加实例

要添加实例,请使用 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>

在浏览器中刷新网页,然后点击插入实例 (Insert Instance) 按钮以创建新实例。点击列出实例按钮,查看新实例是否出现在实例列表中。

添加包含元数据的实例

创建实例时,您还可以传递自定义元数据。您可以定义任何类型的自定义元数据,但自定义元数据对于运行启动脚本尤为有用。要创建包含自定义元数据的实例,请将 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>

刷新页面并点击获取实例 (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>

刷新页面,然后点击删除实例按钮。

删除磁盘

要删除磁盘,请使用 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>

后续步骤

在完成本练习后,您可以:

  • 下载高级示例,并在 googlecloudplatform GitHub 页面上查看其他示例。高级示例包括一些更加复杂的调度方法,并且比此处的示例更加干净。
  • 如果要使用 Python 客户端库,请参阅使用 Python 客户端库
  • 要了解如何通过 API 执行其他任务,请查看 API 参考
  • 开始创建自己的应用!
此页内容是否有用?请给出您的反馈和评价:

发送以下问题的反馈:

此网页
Compute Engine 文档