OCI Python API – Print VMStandard OCPU Totals

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

     RUNNING VM.Standard2.2 vm1
     RUNNING VM.Standard2.1 vm2
     RUNNING VM.Standard2.1 vm3

compartment1 Total: 4.0

     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
        # call apis

    def generate_signer_from_instance_principals(self):
            # 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
        for compartment in compartments:
            if compartment.lifecycle_state == "ACTIVE":
                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(compartment.name+" Total: "+str(compartment_ocpus))
                print(" ")
        print("Total OCPUs: "+str(total_ocpus))
        print("Total Running OCPUs: "+str(total_running_ocpus))
# Initiate process

Leave a Reply

Your email address will not be published. Required fields are marked *

I accept that my given data and my IP address is sent to a server in the USA only for the purpose of spam prevention through the Akismet program.More information on Akismet and GDPR.