Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In 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, too (URL parameter "sourceInstanceTemplate").

How can I create a new GCE-VM from an instance template using googleapis/nodejs-compute (the Node.js GCE SDK)?

like image 623
Markus Schulte Avatar asked Jul 22 '26 10:07

Markus Schulte


1 Answers

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

The following example is adapted from 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}
  });
}
like image 75
Markus Schulte Avatar answered Jul 24 '26 00:07

Markus Schulte