The Zurich release has arrived! Interested in new features and functionalities? Click here for more

Ram Devanathan1
ServiceNow Employee
ServiceNow Employee

If you always wondered how to easily get count of VMs in each cloud, here's a simple script.

This script uses GlideAggregate on the cmdb_rel_ci table to get the count of 'active' VMs in all the datacenters.

The intent is to show how to use GlideAggregate and get some quick counts of the discovered virtual machines, through a simple script.

var relCiGa = new GlideAggregate('cmdb_rel_ci');

if (relCiGa.isValid()) {

    relCiGa.setGroup(true);
    relCiGa.addQuery('type','5f985e0ec0a8010e00a9714f2a172815');

    relCiGa.addQuery('parent.sys_class_name','cmdb_ci_vm_instance').addOrCondition('parent.sys_class_name','cmdb_ci_vmware_instance');
    relCiGa.addEncodedQuery('parent.ref_cmdb_ci_vm_instance.stateINon,off,paused,starting,stopping,pausing');

    relCiGa.addAggregate('COUNT', 'child.sys_class_name');

    relCiGa.query();

    while (relCiGa.next())
    gs.info('Provider: ' + relCiGa.getValue('child.sys_class_name') +', COUNT: ' + relCiGa.getAggregate('COUNT', 'child.sys_class_name'));
} else
    gs.info("Table cmdb_rel_ci not found")

The output looks like this -

*** Script: Provider: cmdb_ci_aws_datacenter, COUNT: XX
*** Script: Provider: cmdb_ci_azure_datacenter, COUNT: XX
*** Script: Provider: cmdb_ci_google_datacenter, COUNT: XX
*** Script: Provider: cmdb_ci_vcenter_datacenter, COUNT: XXX

You can try out the code snippet by running as a background script.

Ram

Version history
Last update:
‎03-07-2022 11:38 PM
Updated by: