I had an interesting conversation with my colleagues recently about how we could track the spend on our OCI test tenant on a per-user basis.
There are several people within my team who have access to this shared tenant and we needed a way to quickly and easily see the spend per-user.
I looked into this and created a script using the Python SDK for OCI, which does the following:
- Connects to a tenant specified by the tenant_id variable
- Calculates the date range of the previous month, for example it’s currently February 2024, the script calculates a date range of 1st January 2024 (datefrom) to 1st February 2024 (dateto)- this is used as the reporting period for the usage query.
- Calls the RequestSummarizedUsageDetails usage API and requests the usage for a given date range (the previous month in this case), returning the cost and grouping this by who created the resource – this uses the inbuilt CreatedBy tag, more details on this can be found here.
- For each of the users (CreatedBy) in the response from the usage API, print to the console along with the cost attributed to each.
Here is an example of the script output, which shows cost per user for the previous calendar month (in this case January 2024):

The script can be found on GitHub and below, the request can be updated to meet your specific needs, using the documentation as a reference:
import oci
import datetime
# Authenticate to OCI
config = oci.config.from_file()
# Initialize the usageapi client service client with the default config file
usage_api_client = oci.usage_api.UsageapiClient(config)
# Create the from and to dates for the usage query - using the previous calendar month
dateto = datetime.date.today().replace(day=1) # Get the first day of the current month
month, year = (dateto.month-1, dateto.year) if dateto.month != 1 else (12, dateto.year-1)
datefrom = dateto.replace(day=1, month=month, year=year) # Get the first day of the previous month
# Build request
request_summarized_usages_response = usage_api_client.request_summarized_usages(
request_summarized_usages_details=oci.usage_api.models.RequestSummarizedUsagesDetails(
tenant_id="Tenant OCID", # Update with the tenant OCID
time_usage_started=(datefrom.strftime('%Y-%m-%dT%H:%M:%SZ')),
time_usage_ended=(dateto.strftime('%Y-%m-%dT%H:%M:%SZ')),
granularity="MONTHLY",
is_aggregate_by_time=False,
query_type="COST",
group_by_tag=[
oci.usage_api.models.Tag( # Return results by the CreatedBy tag, which will indicate the user who created the resource (who the usage cost will be attributed to)
namespace="Oracle-Tags",
key="CreatedBy")],
compartment_depth=6))
# Store the output of the request
output = request_summarized_usages_response.data
# Loop through the output and print the usage cost per user
i = 0
while i < len(output.items):
print("-" + output.items[i].tags[0].value + " Cost: " + "£" + str(output.items[i].computed_amount))
i += 1

Leave a comment