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)
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
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 https://github.com/niftycode/aws-ec2-start-stop.git
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)
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 start_stop_ec2.py -u
And to stop the instance run:
python3 start_stop_ec2.py -d
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)
Try Aws cdk with python, it is a better choice 👍
Thank you for your tip! I will try it.