首页 > 解决方案 > 如何使用 GCE Node.js 客户端从实例模板创建新的 GCE VM 实例?

问题描述

Google 计算引擎中,我可以使用实例模板从模板创建新的 VM。这使用 GCE 控制台可以正常工作,并且使用API也可以正常工作(URL 参数“sourceInstanceTemplate”)。

如何使用googleapis/nodejs-compute(Node.js GCE SDK)从实例模板创建新的 GCE-VM?

标签: google-compute-enginegoogle-api-nodejs-client

解决方案


google-auth-library-nodejs可用于直接访问GCE instances.insert API

以下示例改编自https://github.com/google/google-auth-library-nodejs,如果在 GCE 中执行(特别是在Google Cloud Function中),则可以正常工作。

const zone = 'some-zone';
const name = 'a-name';
const sourceInstanceTemplate = `some-template-name`;
createVM(zone, name, sourceInstanceTemplate)
  .then(console.log)
  .catch(console.error);

async function createVM(zone, vmName, templateName) {
  const {auth} = require('google-auth-library');
  const client = await auth.getClient({
    scopes: 'https://www.googleapis.com/auth/cloud-platform'
  });
  const projectId = await auth.getDefaultProjectId();

  const sourceInstanceTemplate = `projects/${projectId}/global/instanceTemplates/${templateName}`;
  const url = `https://www.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/instances?sourceInstanceTemplate=${sourceInstanceTemplate}`;

  return await client.request({
    url: url,
    method: 'post',
    data: {name: vmName}
  });
}

推荐阅读