2

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)?

Markus Schulte
  • 4,171
  • 3
  • 47
  • 58

2 Answers2

8

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}
  });
}
Markus Schulte
  • 4,171
  • 3
  • 47
  • 58
2

I can't find the solution in the documentation for the node client. Hopefully my alternate solution helps someone.

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);

You can customize this as far as gcloud lets you. The docs/options for creating an instance are here.

Vincent
  • 1,553
  • 1
  • 11
  • 21
  • Excellent workaround, thanks for the inspiration! Unfortunately, I cannot use it. I am within a https://cloud.google.com/functions/ , where gcloud-tool is not available (I tested it 'stderr: '/bin/sh: 1: gcloud: not found\n' }' ). – Markus Schulte Jul 24 '18 at 09:49