Script to stop/start OCI DB Node

Karthic
2 min readNov 4, 2024

--

If you are a Oracle Cloud Infrastructure Database user and have Oracle Base Database in non production environment you might want to stop when its not in use to save cost.

Stopping a node stops billing for all OCPUs associated with that node. https://docs.oracle.com/en-us/iaas/base-database/doc/stop-db-system.html

You can use the oci cli command in cloud shell manually or run it as a script via cron

oci db node start — db-node-id <db node ocid>

oci db node stop — db-node-id <db node ocid>

Also this can be achieved using OCI python SDK and we can run a scheduled function.

import oci
import io
from oci.database import DatabaseClient

def start_stop_db_node(db_node_id=None,
action='STOP'):
"""
Starts or stops a Database VM node in OCI.
:param db_node_id: OCID of the Database VM node to start or stop.
:param action: Action to perform on the Database VM node. Can be 'START' or 'STOP'.
"""
signer = oci.auth.signers.get_resource_principals_signer()
db_client = DatabaseClient({}, signer = signer)
get_db_node_response = db_client.get_db_node(db_node_id=db_node_id)
db_node_state = get_db_node_response.data.lifecycle_state


if action.upper() not in ['START', 'STOP']:
raise ValueError("Invalid action. It should be either 'START' or 'STOP'.")


try:
if action.upper() == 'START' and db_node_state == 'STOPPED':
# Start the Database VM node
start_response = db_client.db_node_action(db_node_id,action="START")
print(f"Database VM node {db_node_id} is starting...")
print(start_response.data)
elif action.upper() == 'STOP' and db_node_state == 'AVAILABLE':
# Stop the Database VM node
stop_response = db_client.db_node_action(db_node_id,action="STOP")
print(f"Database VM node {db_node_id} is stopping...")
print(stop_response.data)
else:
print('No action to be done')
except Exception as e:
print(f"Failed to {action.lower()} the Database VM node: {e}")

def handler(ctx,data: io.BytesIO = None):
try:
cfg = ctx.Config()
db_node_id = cfg['db_node_ocid']
action = cfg['action']
start_stop_db_node(db_node_id=db_node_id, action=action)

except Exception as ex:
print('ERROR: Missing key in payload', ex, flush=True)

Please refer the oracle documentation to deploy OCI functions. Set the below configuration parameters for the deployed function.

We can schedule the function daily using OCI Resource scheduler. The below screenshot shows one example to stop DBCS VM Node every day at 7.50AM UTC.

You can schedule it hourly ,daily ,weekly or monthly

NOTE : As always please test the provided script before use.

--

--

No responses yet