如何使用 GCE Node.js 客户端从实例模板创建新的 GCE VM 实例?

How do I create a new GCE VM instance from an instance template using GCE Node.js client?

Google compute engine I can use an instance template to create a new VM from the template. This works fine using the GCE-console, and works fine, using the API中也是如此(URL参数"sourceInstanceTemplate")。

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

我在节点客户端的文档中找不到解决方案。希望我的 alternate 解决方案对某人有所帮助。

const exec = require('child-process-promise').exec;

var create_vm = (zone, vmname, templatename) => {
  const cmd =  `gcloud compute instances create ${vmname} ` +
      `--zone=${zone} ` +
      `--source-instance-template=${templatename} `;
  return exec(cmd);
};

create_vm('us-central1-c', 'my-instance', 'whatever')
    .then(console.log)
    .catch(console.error);

您可以在 gcloud 允许的范围内对其进行自定义。创建实例的 docs/options 是 here.

google-auth-library-nodejs can be used for accessing the GCE instances.insert API直接

以下例子改编自https://github.com/google/google-auth-library-nodejs and works fine, if executed within GCE (in special, in a 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}
  });
}