DEV Community

Bodo Schönfeld
Bodo Schönfeld

Posted on

Start your AWS EC2 instance using Python

Amazon EC2 (Elastic Compute Cloud) is a cloud service that allows you to bring up virtual machines (instances) online. To do so you can use the AWS Dashboard. But there is another way: Python (or another programming language supported by Amazon Web Services). You can find an overview on this website.

If you never used Amazon Web Services with Python before, you have to install two additional modules first:

pip install boto3 botocore (Windows)
pip3 install boto3 botocore (macOS/Linux)
Enter fullscreen mode Exit fullscreen mode

In the next step save your AWS Credentials in a folder named ".aws" located in your home (Linux)/Users (macOS)/%UserProfile% (Windows) folder. You can do so manually as explained in this AWS documentation or you make it the easy way by using the AWS Command Line Interface (AWS CLI). For more information see the AWS documentation "Installing the AWS CLI version 2". The installer files (for Linux, Windows and macOS) are also provided on that website.

After you've installed the AWS CLI open the PowerShell (or the Command Prompt) on Windows. On UNIX-like systems open a Shell. Then enter the following command:

aws configure
Enter fullscreen mode Exit fullscreen mode

You will be asked for the AWS Access Key ID and the AWS Secret Access Key. As default region name enter your Availability Zone (AZ). And finally the default output format should be "json". As you can imagine, your credentials will be saved in the ".aws" folder.

Now you can use a Python script to start and stop an EC2 instance. As starting point you can use the script from my Github repository:

git clone
Enter fullscreen mode Exit fullscreen mode

This script needs a txt file named "instance_id.txt". Create such a file and save it in your home directory:

/home/[username]/instance_id.txt (Linux)
/Users/[username]/instance_id.txt (macOS/Windows)
Enter fullscreen mode Exit fullscreen mode

As the name indicates, this text file should contain the ID of your EC2 instance (Check your EC2 dashboard for the available IDs.)

You're done! Now start your EC2 instance with the following command:

python3 -u
Enter fullscreen mode Exit fullscreen mode

And to stop the instance run:

python3 -d
Enter fullscreen mode Exit fullscreen mode

After an instance is up and running, the public IP address will be shown. Use this address to establish a remote connection via a Shell or Microsoft Remote Desktop.

Top comments (2)

evgenijrenke profile image
Evgenij Renke

Try Aws cdk with python, it is a better choice 👍

niftycode profile image
Bodo Schönfeld

Thank you for your tip! I will try it.