Raj Chaudhary
Raj Chaudhary

Reputation: 1762

Create a new VM by attaching an existing disk using Node.js client library for Google Compute Engine APIs

I am using Node.js client library for Google Compute Engine APIs to create a new VM by attaching an existing disk to it. But I get the Invalid value for field 'resource.disks[0].source': ''. Source url of disk is missing. error when running below code. Can someone help? Thanks in advance!

const createVM = () => {

    const Compute = require('@google-cloud/compute');
    const compute = new Compute();
    const zone = compute.zone('us-central1-f');
    let disk;
    const diskName = 'debian-http-disk';
    const vmName = 'debian-http'
    let vm;

    disk = zone.disk(diskName);

    zone
    .createVM(vmName, {
        disks: [disk], 
        http: true, 
        machineType: 'f1-micro'
    })
    .then((data) => {
        vm = data[0];
        const operation = data[1];
        return operation.promise();
    })
    .then(() => {
        console.log('vm created successfully');        
    })
    .catch((e) => {
        console.error(e);
    });    

};

Upvotes: 1

Views: 570

Answers (2)

Raj Chaudhary
Raj Chaudhary

Reputation: 1762

The helpful folks managing the Node.js client library for GCE APIs acknowledged that the documentation at https://cloud.google.com/nodejs/docs/reference/compute/0.10.x/Zone#createVM is incorrect. I've made this work by passing raw JSON to the zone.createVM method as below:

zone.createVM('debian-http', {
    disks: [{
        boot: true,
        source: 'https://www.googleapis.com/compute/v1/projects/[project-id]/zones/us-central1-f/disks/debian-http'
    }], 
    http: true, 
    machineType: 'f1-micro'
})

More config options for the disks property can be found at https://cloud.google.com/compute/docs/reference/rest/v1/instances/insert. More info on the bug can be found at https://github.com/googleapis/nodejs-compute/issues/107. Hope this helps others!

Upvotes: 3

Vincent
Vincent

Reputation: 1651

I know you requested the nodejs library solution, but this will work in the meantime.

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

var create_vm = (zone, vmname, diskname) => {
  const cmd =  `gcloud compute instances create ${vmname} ` +
      `--zone=${zone} ` +
      `--disk=name=${diskname}`
  return exec(cmd);
};

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

Of course you can also create boot disks this way and add as many options as you want. For the options on creating instances, look here.

Upvotes: 2

Related Questions