How to automatically STOP OCI resources with Python SDK to control budget

Previously I wrote a post about automating the START/STOP of compute instances using Python SDK for OCI.

That approach assumed we could create a cron job that would STOP/START at certain times (weekend for example).

What if we want to do this based on actual consumption/spending? How to automate this?

We can setup an OCI Budget where we can define thresholds (forecast or actual spend) to a compartment (or tag) level. This service will provide us with the necessary information based on we can make the decision to STOP a service.

But let’s start from the beginning.

Install Python SDK for OCI

First we need to have both OCI and the Python SDK for OCI installed.

Have a look at the original post

Create an OCI Budget

Ok, so first thing is to go to the Budgets menu in the OCI Explorer.

There we can Create Budget. There are 2 main scopes, compartment or cost-tracking-tag.

For compartment we need to select the target compartment, assign a monthly budget and then choose if we want to track the actual spend or the forecasted spend.

This approach tracks all the consumption within that compartment.

If you need a more fine grained tracking, then use the Cost-Tracking-Tag option.

You can also define email recipients and an email body message as an alert.

And that is all. Depending on the options you choose above, it might take some time for the actual Spend/Forecast to be displayed.

Python SDK

Now lets automate all of this.

The first step is to get the data from the OCI Budget that we just created, and for that we have an API.

https://docs.oracle.com/en-us/iaas/api/#/en/budgets/20190111/Budget/GetBudget

​GET /20190111/budgets/{budgetId}

It will required the budget OCI ID so have that at hand.

The documentation offers examples for any language you need, which is fantastic.

We now have access to the actual spend, which will allow us to decide whether to STOP or not a service.

Important: If you have multiple services under the same compartment you may need all of those OCIDs, and send a STOP request to all of them. This example was meant with some of the PaaS services in mind, like OIC , OAC, ODA etc. where typically we have them running in a dedicated compartment. The goal here is not to analyze the impact of stopping these services, but purely to explain how can we automate its lifecycle.

Below we have a working script that calls the GetBudget API and then the StopOdaInstance, if the actual spend is above 1000. It does not matter if the Budget was defined with a compartment or a tag, because the code only uses the budget OCID.

Note: this is not meant to be a production ready code, far from it. It’s just a working sample 🙂

That’s all Folks!

2 Comments

  1. Do you have a link to the OCI SDK Python code for automating the START/STOP of compute instances using Python SDK for OCI.

Comments are closed.