Automate stopping compute instances in OCI πŸ›‘

I currently have a few VMs (compute instances) running in OCI and it’s getting annoying having to manually use the console to stop these when I no longer need them, I put together the Python script below which uses the OCI Python SDK to stop all running instances within a specific compartment.

If you haven’t used the OCI Python SDK before, I put together a quick guide on getting started here.

import oci
import json

# Read the config
config = oci.config.from_file()

# Create client with the default config file (\.oci\config)
computeclient = oci.core.ComputeClient(config)

# List all of the compute instances within the compartment
list_instances_response = computeclient.list_instances(
   compartment_id="SPECIFY THE COMPARTMENT ID")

# Convert to JSON
instances = json.loads(str(list_instances_response.data))

# Print the state of each VM and stop any that are running
for instance in instances:
 print(instance["display_name"] + " - status: " + instance["lifecycle_state"])
 if instance["lifecycle_state"] == "RUNNING":
   print("Stopping :" + instance["display_name"])
   computeclient.instance_action(instance["id"],"SOFTSTOP")

This uses the SOFTSTOP action which does the following:

Gracefully shuts down the instance by sending a shutdown command to the operating system. After waiting 15 minutes for the OS to shut down, the instance is powered off. If the applications that run on the instance take more than 15 minutes to shut down, they could be improperly stopped, resulting in data corruption. To avoid this, manually shut down the instance using the commands available in the OS before you softstop the instance.

Taken from – https://docs.oracle.com/en-us/iaas/tools/oci-cli/3.37.1/oci_cli_docs/cmdref/compute/instance/action.html

Here is the script in action:

Comments

Leave a comment