Start, Stop, Reboot EC2 instances using Python - boto3

Sreenath Girikanyadas
2 min readDec 9, 2020
Technology vector created by stories — www.freepik.com

In this article i’ll demonstrate how to start, stop and reboot your AWS EC2 instances using boto3 SDK in pyhton.

Boto3 is the AWS SDK for python using this librarywe can easily control and monitor AWS EC2 instances and other resources by writing a simple python scripts, complex automation procedures can be acheived using this library.

Before getting into the code you should have set up the credentilas, there are multiple wasy to set this up, the way i prefer is to set up via the awscli.

#run the command as below.ubuntu@dell-machine-001:~$ aws configure
AWS Access Key ID []:********************
AWS Secret Access Key []:********************
Default region name []: <region>
Default output format []:json

You can get your AWS Acces Key and AWS Secret Key from your AWS IAM dashboard or contact your account manager.

Once the setup is complete. Let’s get into the code.

Fristly, create virtualenv or this step can also be skipped — i’d recommend to do this inside a virutalenv.

cd <your-project-directory>
virtualenv pyenv
source pyenv/bin/activate

Second step, is to install boto3 sdk itself.

pip install boto3

Third step, now you can start writing the code.

The above code simple snippet shows how to start, stop and reboot an instance or a list of instances.

Config object explained:

config = Config( 
region_name = regionMap[region],
signature_version = 'v4',
retries = {
'max_attempts': 10,
'mode': 'standard'
}
)

the config object is used to declare few important parameters based on which boto3 behaves.

region_name — AWS region of the instance is given here.

signature_version — this specifies the signature version used to sign the urls, the version usually used is 4 but there are other versions too.

retries — this object specifies the retry mode and max_attempts, the modes available are legacy, standard and adaptive. The max_attempts key limits the number of times the api is called till it get’s a response from the server.

Better version of the code can be found on my Git repo.

Thank you :)

--

--

Sreenath Girikanyadas

Hi, I write my experiments and explorations in technology here.