Get list of all compartments in OCI Tenancy

3.3k Views Asked by At

I am trying to get the list of all compartments (including child compartments) in OCI Tenancy using Python SDK.

But the below OCI API does not give the root compartment details.

Is there a way to get root compartment details via any API directly?

Below is my code:

import oci
from oci.config import from_file
from oci.signer import Signer

config = from_file()

COMPARTMENT_ID="ocid1.tenancy.oc1..a"

identity_client = oci.identity.IdentityClient(config)

list_compartments_response = identity_client.list_compartments(
    compartment_id=COMPARTMENT_ID,
    compartment_id_in_subtree=True)

compartmentlist = list_compartments_response.data

compartmentlist dict does not contain the root compartment details.

Please help.

Edit 1:

COMPARTMENT_ID given above in the code is the root compartment ID. I need the details of even this root compartment in the final response of API.

1

There are 1 best solutions below

0
On BEST ANSWER

list_compartments gives details of all the sub-compartments under a particular compartment OCID provided to the API.

If you are providing root compartment OCID to this API then it will give all the compartment details under root compartment excluding the root.

For appending the root compartment details, below API can be used. I am not aware of any other OCI API to accomplish this task.

Hope this helps you.

import oci
from oci.config import from_file

config = from_file()  # Config file is read from user's home location i.e., ~/.oci/config

COMPARTMENT_ID="ocid1.tenancy.oc1..a" # root compartment OCID

identity_client = oci.identity.IdentityClient(config)

list_compartments_response = identity_client.list_compartments(
    compartment_id=COMPARTMENT_ID,
    compartment_id_in_subtree=True)

# Get the list of compartments including child compartments except root compartment
compartmentlist = list_compartments_response.data

# Get the details of root compartment & append to the compartment list so that we have the full list of compartments in the given tenancy

root_compartment = identity_client.get_compartment(
    compartment_id=COMPARTMENT_ID).data
compartmentlist.append(root_compartment)