Start/Stop AWS EC2 with Python Boto3

and display the public IP address after started

vITraining Admin

Here's an example of how you can use the AWS EC2 SDK for Python (Boto3) to start and stop an EC2 instance, wait for the instance state to started, and display the public IP address:

import boto3
import sys
import time

args = sys.argv

start = args[1]=='start'

# Initialize the EC2 client
ec2_client = boto3.client('ec2', region_name='YOUR_REGION', aws_access_key_id='YOUR_ACCESS_KEY', aws_secret_access_key='YOUR_SECRET_KEY')

# Specify the instance ID of the instance you want to start/stop
instance_id = 'YOUR_INSTANCE_ID'

if start:
# Start the EC2 instance
print('starting instance...')
print(f'Starting EC2 instance with ID: {instance_id}')

# ec2_client.wait_until_running(InstanceIds=[instance_id])
while True:
response = ec2_client.describe_instances(InstanceIds=[instance_id])
state = response['Reservations'][0]['Instances'][0]['State']['Name']
if state == 'running':
print(f"Instance state: {state}. Waiting for instance to reach running state...")

response = ec2_client.describe_instances(InstanceIds=[instance_id])
public_ip = response['Reservations'][0]['Instances'][0]['PublicIpAddress']
print("Started. Public IP address:", public_ip)

print('stoping instance...')
print(f'Stopping EC2 instance with ID: {instance_id}')

Save it to a python file, for example:

Make sure to replace 'your_region_name', 'YOUR_ACCESS_KEY', 'YOUR_SECRET_KEY', and 'YOUR_INSTANCE_ID' with your actual AWS region name, access key, secret access key, and EC2 instance ID respectively.

Note: You need to have the Boto3 library installed in your Python environment to use this code. If you haven't installed it already, you can install it using pip by running pip install boto3.

pip3 install boto3

The AWS Regions

The AWS region name refers to the geographical location where your EC2 instance is deployed. It determines the physical location of the data centers where your EC2 instance runs, and it can affect factors such as data transfer speed and compliance requirements.

AWS provides multiple regions around the world, and each region has its own unique name. Here are some examples of region names:

us-east-1: US East (North Virginia)
us-west-2: US West (Oregon)
eu-west-1: EU (Ireland)
ap-northeast-1: Asia Pacific (Tokyo)
ap-southeast-2: Asia Pacific (Sydney)
sa-east-1: South America (São Paulo)

You can find the full list of AWS regions and their corresponding region names in the AWS documentation:

To start your instance, simply type :

python start

To stop it:

python2 stop

The User Access 

In AWS, you do not typically use an API key and secret to authenticate with the AWS services like EC2. Instead, you would use AWS Identity and Access Management (IAM) roles and permissions to grant access to AWS resources.

Here's an overview of the steps to get started with IAM and obtain the necessary credentials:

  1. Sign in to the AWS Management Console: Go to the AWS Management Console at and sign in with your AWS account credentials.

  2. Open the IAM service: Once you are signed in, navigate to the IAM (Identity and Access Management) service in the AWS Management Console.

  3. Create an IAM user: In the IAM console, you can create an IAM user, which is an identity with specific permissions to access AWS resources. You can create an IAM user by going to "Users" in the IAM console navigation menu and clicking on "Add user".

  4. Follow the prompts to set a username

  5. On the Permission Options, select "Add user to group"

  6. Create a new group and add the permission "AmazonEC2FullAccess"

  7. Add the user to the new group

  8. Obtain the Access Key ID and Secret Access Key: After you create the IAM user, AWS will provide you with an Access Key ID and Secret Access Key. These are the credentials that you can use to authenticate your API requests to AWS services, including EC2. Make sure to save these credentials securely, as they provide access to your AWS resources. Click the "Security Credentials" tab, and click "Create Access Key" button.

  9. Use the Access Key ID and Secret Access Key in your code: You can use the Access Key ID and Secret Access Key in your code when making API requests to AWS services like EC2 using the appropriate AWS SDKs, such as Boto3 for Python. For example, you can set the Access Key ID and Secret Access Key when initializing the EC2 client as shown in the example code in the previous response.

It's important to follow AWS best practices for securing your credentials, such as not embedding them in your code, rotating them regularly, and applying the principle of least privilege by granting only the necessary permissions to IAM users or roles.