Automatically resize AWS ec2 via script

amazon-web-services

I'm using a t2.micro instance on aws which is enough for daily use of running a website and a mongodb.

But sometimes I want to use a remote interpreter to train a neural network, and for that I would use a fast machine for around 1h.

Is there a quick way to change the instance type over a script? All it needs to do is the shut the server down, change the instance type and restart it. And then in the end revert to the small instance size again.

What would be the best way to handle this over a script. Ideally over python.

Best Answer

This Stack Overflow answer by @John Rotenstein provides a Python script to change the instance type.

However, given that you only pay for EC2 instances when they are running plus storage cost when shutdown, I would create a new instance of the correct type for your other work. You can then start and stop that instance as required. No risk then to your website or MongoDB.

Resizing an EC2 instance using boto3

import boto3

client = boto3.client('ec2')

# Insert your Instance ID here
my_instance = 'i-xxxxxxxx'

# Stop the instance
client.stop_instances(InstanceIds=[my_instance])
waiter=client.get_waiter('instance_stopped')
waiter.wait(InstanceIds=[my_instance])

# Change the instance type
client.modify_instance_attribute(InstanceId=my_instance, Attribute='instanceType', Value='m3.xlarge')

# Start the instance
client.start_instances(InstanceIds=[my_instance])
Related Topic