Search code examples
javascriptnode.jsgoogle-cloud-platformgoogle-cloud-functionsinstance

How can I check how many CPUs and memory my vm instance uses in google-cloud using node.js function


I can't find how to see the number of CPUs and memory used in a VM instance of google-cloud. I'm trying to write a function that checks all of my running VM instances and stop every instance that uses more CPUs or memory than limited (depends)

I've created an instance on google-cloud-platform and I want to create a function that runs manually by me that will check if any of the instances is over the limit. How can I check a specific VMs' details?


Solution

  • Try this code

    'use strict';
    const Compute = require('@google-cloud/compute');
    const compute = new Compute();
    
    async function getVms() {
      const vms = await compute.getVMs();
      return vms;
    }
    exports.main = async () => {
      const vms = await getVms().catch(console.error);
      if (vms) console.log(JSON.stringify(vms, null, 2));
      return vms;
    };
    if (module === require.main) {
      exports.main(console.log);
    }
    

    Don't forget to install npm install @google-cloud/compute.

    In the response, you have all the properties of your VMs. Look at the machine_type:

    "machineType": "https://www.googleapis.com/compute/v1/projects/<PROJECT>/zones/<ZONE>/machineTypes/n1-standard-1",
    

    You can also check the custom VM

    "machineType": "https://www.googleapis.com/compute/v1/projects/<PROJECT>/zones/<ZONE>/machineTypes/custom-4-5120",
    

    custom-4-5120 means 4vCPU and 5Gb of memory