1

Can i use python boto to change the shutdown behavior of my instance:

Basically, the same thing that we change from the the web interface:

enter image description here

The code i use to run the instance is:

   # Create and run a instance based on our predefined image
    reservation= conn.run_instances(
            'ami-0072ee30',
            key_name='rajat',
            instance_type=instance_requested_type)

spot instance request:

 reservs = conn.request_spot_instances(
            float(max_bid),
            'ami-0072ee30',
            count=1,
            type='one-time',
            instance_type=instance_requested_type)

1 Answer 1

6

Yes, you can. There is an optional parameter to the run_instances method called instance_initiated_shutdown_behavior that can have a value of "stop" or "terminate". So, to extend your example above to specify that you want the instance stopped if it is terminated by the user, you would do:

import boto3
ec2_client = boto3.client('ec2')
reservation = ec2_client.run_instances(
                     ImageId='ami-0072ee30',
                     MinCount=1,
                     MaxCount=1, 
                     KeyName='rajat', 
                     InstanceType='t2.micro',
                     InstanceInitiatedShutdownBehavior='terminate'
               )

Reference: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html

Sign up to request clarification or add additional context in comments.

5 Comments

This is great, i can't find something like this for spot instance requests. Here is my code until now: <br/> ' reservs = conn.request_spot_instances( float(max_bid), 'ami-0072ee30', count=1, type='one-time', instance_type=instance_requested_type)
I can't format the code in comment, so i have added it in the question.
I don't think you can specify the shutdown behavior of a spot instance. The API docs (docs.aws.amazon.com/AWSEC2/latest/APIReference/…) don't list that as a request parameter and I'm not sure it really makes sense in the context of a spot instance.
why doesn't it make sense? i want to shut down my instance when the task is complete and i don't want to incur the cost of my storage.
Because spot instances can't be stopped. They can only be terminated. If you want to make sure the EBS storage associated with the spot instance goes away when you terminate it, you can use the delete_on_termination field in the block device mapping although the default value is True so you shouldn't have to do anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.