Automate STOP/START of your Compute Instances with Python SDK for OCI

In this post I will show how easy it is to create a script that automates the STOP of all of instances within one compartment. Useful if you care about cost management and wish to STOP all resource consumption during nights or weekends!

I will make use of the Python SDK for OCI. I covered the necessary steps to install the SDK locally in this Post 🙂

Below is a sample code that performs the following:

  • Authenticates to OCI
  • Initialize service client
  • Makes use of core_client.list_instances method to get all Running instances
  • Uses core_client.instance_action method to send a SOFTSTOP request

Python Script

This script will softstop (asks the OS to gracefully shutdown) all Running Instances

There are several other parameters to use in the method list_instances:

  • availability_domain
  • display_name
  • sort_order

Full service description can be found here.

List of my running Instances

Executing the script

Final State

Even tough the code requires quite some improvement, it does work, and goes to prove that creating automation scripts is not that complicated 🙂

Things to include for version 2.0

  • try/catch blocks for the stop command
  • use functions
  • use parameters for both region and compartment

Community

There are a lot of community resources out there, but the below page consolidates a huge list of them. Worthwhile checking!