The example loops though all the active compartments. It totals all ocpus in each compartment and provides the total of all ocpus running.
Example Output compartment1 RUNNING VM.Standard2.2 vm1 RUNNING VM.Standard2.1 vm2 RUNNING VM.Standard2.1 vm3 compartment1 Total: 4.0 compartment2 RUNNING VM.Standard2.2 vm1 RUNNING VM.Standard2.2 vm2 RUNNING VM.Standard2.2 vm3 compartment2 Total: 6.0 Total OCPUs: 10.0 Total Running OCPUs: 10.0
The login uses instance principals. To run, you need the python SDK configured with instance principals.
Example Code
class TenancyVMStandardCounts(object): def __init__(self): # generate signer self.generate_signer_from_instance_principals() # call apis self.get_compute_list() def generate_signer_from_instance_principals(self): try: # get signer from instance principals token self.signer = oci.auth.signers.InstancePrincipalsSecurityTokenSigner() except Exception: print("There was an error while trying to get the Signer") raise SystemExit # generate config info from signer self.config = {'region': self.signer.region, 'tenancy': self.signer.tenancy_id} def get_compute_list(self): # initialize the IdentityClient with an empty config and only a signer identity_client = oci.identity.IdentityClient(config = {}, signer=self.signer ) # initialize the ComputeClient with an empty config and only a signer compute_client = oci.core.ComputeClient(config = {}, signer=self.signer) # get the list of all compartments in my tenancy compartments = identity_client.list_compartments(self.config["tenancy"], compartment_id_in_subtree=True, access_level="ACCESSIBLE").data # find my compartment total_ocpus=0 total_running_ocpus=0 for compartment in compartments: compartment_ocpus=0 if compartment.lifecycle_state == "ACTIVE": print(compartment.name) instances = compute_client.list_instances(compartment.id).data for instance in instances: print(" "+instance.lifecycle_state+ " "+instance.shape+" "+instance.display_name) if instance.lifecycle_state != "TERMINATED": total_ocpus = total_ocpus + instance.shape_config.ocpus compartment_ocpus = compartment_ocpus + instance.shape_config.ocpus if instance.lifecycle_state == 'RUNNING': total_running_ocpus = total_running_ocpus + instance.shape_config.ocpus #print(instance.shape_config.ocpus) print(compartment.name+" Total: "+str(compartment_ocpus)) print(" ") print("Total OCPUs: "+str(total_ocpus)) print("Total Running OCPUs: "+str(total_running_ocpus)) # Initiate process TenancyVMStandardCounts()