pythonazure-machine-learning-serviceazureml-python-sdk

AzureML Python SDK v2: How to programmatically stop a compute instance upon creation?


I'm working on a script that creates compute instances if they don't already exist. Upon creating a compute instance, it is in running state. I'd like to be able to immediately stop that compute instance, as I won't be needing it immediately.

I want to do this using Python with the "new" SDK v2. I am not interested in solutions involving the Idle shutdown time, and scheduled start/stop. I am looking to have direct control on the running state of the instance.

This code works well, but I'd really like to stop the instance as soon as it's created. I haven't found anything relating to this in the documentation.

# This code uses SDK v2    
# MC is MLClient... compute_instance is a ComputeInstance object
mc.compute.begin_create_or_update(compute_instance)
compute_instance.wait()
compute_instance = compute_instance.result()

logger.info(f"Created Compute instance: name={compute_instance.name} size={compute_instance.size}.")

if compute_instance.state == 'Running':
    # I'd like to stop the compute instance HERE!
    logger.warning(f"Compute instance {compute_instance.name} is RUNNING. This costs money.")

Thank you!


Solution

  • Finally, I ended up finding my answer on my own, This method uses the SDK 2.0. Note that it is asynchronous, so the function call returns before the stopping is done.

    # MC is MLClient... compute_instance is a ComputeInstance object    
    mc.compute.begin_stop(compute_instance.name)