In this blog, I want to show you a way to extract every resource in a compartment along with their status using a Python script and OCI APIs.
There are several pre-reqs that you need to fulfil in order to be able to connect using APIs to OCI. Follow the same pre-reqs as in my previous blog about Metric Extensions.
Step 1 – Prerequisites
Once you have created an OCI user, setup API Keys and setup your Python host; then, go ahead and create a Python script similar to the one below.
#!/usr/bin/python3
# This is a sample python script that searches resources in a compartment
# Run this script on the client that you want to monitor.
# Command: python script_name.py
import oci,subprocess,os,datetime,json
from pytz import timezone
# using default configuration file (~/.oci/config)
from oci.config import from_file
config = from_file()
# initialize service client with default config file
search_client = oci.resource_search.ResourceSearchClient(config)
query = f"query all resources where compartmentId = '<compartment OCID>' && lifeCycleState != 'AVAILABLE' && lifeCycleState != 'ACTIVE' && lifeCycleState != 'Assigned' && lifeCycleState != 'Running' && lifeCycleState != 'Succeeded' && lifeCycleState != 'Deleted'"
search_response = search_client.search_resources(
search_details=oci.resource_search.models.StructuredSearchDetails(
type="Structured",
query=query,
),
limit=1000,
)
print(f"Compartment has {len(search_response.data.items)} resources")
json_format = json.loads(str(search_response.data.items))
# Iterate through the JSON array
for item in json_format:
print(item["display_name"], item["lifecycle_state"])
As you can see from the script. We are using OCI Search in order to get all resources in a compartment (<compartment OCID>) and also we all filtering the search to only show resources that are either down, terminated or failed.
Once you get the list of resources in your compartment you can create a text/csv file and share the list with all the interested parties.
Another option is the ability to combine this with the Monitoring Service and create a Metric Extension (ME). The metric extension will hold the list of resources that have that specific lifecycle_state. Once the date is contained in the ME you can send notifications or create a dashboard showing these resources.
Thanks,
Alfredo