This article will cover how to install and set up Python, Boto3, and the AWS CLI on your computer. It’ll also touch on some basic concepts like remote access with SSH.
The “create ec2 instance using python boto3” is a tutorial that explains how to create an EC2 instance with Python Boto 3.
So you need to build or manage some Amazon Web Service (AWS) EC2 instances, but scrolling about in the Management Console all the time isn’t practical. We’ve got you covered. You’ll be generating, labeling, starting, and terminating EC2 instances in no time with the Boto3 EC2 Python SDK!
Using an example-driven approach, you will learn how to utilize the Boto3 EC2 Python SDK to manage AWS EC2 instances in this tutorial.
Let’s get started.
Prerequisites
This article will be a step-by-step guide. If you want to join in, make sure you have the following items:
- Install Python 3.6 or later on your local PC. On a Windows 10 system, Python v3.9.2 will be used in this course.
How Do You Install Python 3.6? Related:
- An editor for coding. Even though you can work with Python files in any text editor. Visual Studio (VS) Code will be used in this lesson.
Make that the IAM user is set up for programmatic access and is assigned to the AmazonEC2FullAccess policy.
Boto3 for EC2 Instance Creation
When it comes to AWS EC2 instances, Boto3 can accomplish almost everything. To guarantee that you have at least one EC2 instance to deal with, let’s first create one using Boto3.
1. Launch your preferred code editor.
2. Open your code editor and paste the following Python script into it, saving it as ec2 create.py. The file will be saved as ec2 create.py by the tutorial.
The Python script below generates a single (MinCount and MaxCount) AWS EC2 instance using the image ID “ami-013f17f36f8b1fefb” (ImageId) and t2.micro as the instance type (InstanceType).
All of the possible instance types may be found here, and image IDs can be found using the Launch Instance Wizard, as illustrated below. This lesson assumes you’re in the United States of America (US-east-1).
Identifying an AMI ID
Because the default region in the AWS profile is set to us-east-1, the instance is located in AWS Region US East-1.
# Importing boto3 library to enable functionality import boto3 library # Establishing a connection with the AWS EC2 resource ec2 = boto3.resource(‘ec2′) # ec2.create instances(ImageId=’ami-013f17f36f8b1fefb’, MinCount=1, MaxCount=1, InstanceType=’t2.micro’,) print (“EC2 Launched succesfully”)
Boto3 supports two kinds of AWS interactions: resource and client. The resource API is used in the script above (resource(‘ec2’)). The client level gives you low-level service access, while the resource level gives you higher-level, abstracted access.
3. Run the ec2 create script from your preferred command-line (Bash, cmd.exe, PowerShell, etc.). If everything went well, you should see the message EC2 Launched successfully.
4. Open your preferred web browser and go to the AWS Management Console to log in.
5. Type ‘EC2’ into the search box at the top of the console, then choose the EC2 menu option.
Looking for the EC2 service
You should now see your freshly created instance on the EC2 page, as seen below.
A new EC2 instance was created.
Using Boto3 to tag an EC2 instance
An company may have hundreds or thousands of resources to manage in an AWS cloud environment. AWS includes a tool called tagging that enables you to label resources based on environment, department, or any other organization-specific criteria to make resource management easier.
Let’s look at how to add a sample tag to the newly generated EC2 instance.
Copy and paste the following Python code into your code editor and save it as tag ec2.py with your code editor open. Using the create tags() function, the Python script below tags the instance ID of i-03e3d79d5def39c75 produced above with the Name of Boto3.
# Importing boto3 library to enable functionality import boto3 library # Establishing a connection with the AWS EC2 resource ec2 = boto3.resource(‘ec2’) # Using the instance ID response = ec2.create tags(Resources=[‘i-03e3d79d5def39c75’,], Tags=[‘Key’: ‘Name,’Value’: ‘Boto3’,]) to add the Tag Boto3 to AWS EC2.
A tag is made up of two parts: a tag key and a tag value. Both the Tag keys and tag values are needed to tag a resource.
After you’ve saved the script, run it to test whether your instance has been tagged with the boto3 name in your account.
The instance is labeled.
Using Boto3 to describe an EC2 instance
You may “describe” instances to identify EC2 instances that match a given architecture, image ID, instance type, or tags if you need to search all EC2 instances with specified properties. You may create a Python script to query EC2 instances by tag, for example, using the describe API and Boto3.
Copy and paste the following Python code into your code editor and save it as ec2 my instance.py with your code editor open. This script utilizes the describe instances() function to retrieve all attributes associated with all EC2 instances that have a tag named Name (tag:Name) and a value of Boto3 (‘Values’: [‘Boto3’]).
# Importing boto3 library to enable functionality import boto3 library # Setting up an AWS EC2 client connection ec2 = boto3.client(‘ec2’) # myinstance = ec2.describe instances(Filters=[‘Name’: ‘tag:Name’,’Values’: [‘Boto3’]]) print (myinstance)
The Resource() API offers a higher-level abstraction than service clients’ raw, low-level calls. You must connect to resources directly rather than utilizing the Service (Client) API at times, such as when using the generate presigned url() API and need to access an S3 bucket momentarily, which is not available with the resource API.
You won’t need to go to the AWS Management console this time. The JSON output from the script provides all of the data about your instance, including the instance type, public/private IP address, and more, as seen below.
AWS EC2 instance information
Boto3 allows you to start, stop, and terminate EC2 instances.
Perhaps an EC2 instance is no longer required. Because you’ll be charged if an instance is operating, it’s preferable to control its setup, shutdown, and termination procedure.
Charges are not applied to stopped instances, but they are applied to elastic IP addresses and EBS volumes associated to such instances. In any case, charges are not applied to terminated instances.
Because the Python code for starting, stopping, and terminating EC2 instances with Boto3 is essentially similar, let’s create a simple Python script that can do all three tasks.
Copy and paste the following Python code into your code editor and save it as ec2 manage my instance.py with your code editor open.
Stop stop instance(), start start instance(), or terminate the instance terminate instance() with the ID of i-03e3d79d5def39c75 using the Python script below.
# Setting up an AWS EC2 client connection ec2 = boto3.client(‘ec2’) # If you need to start the machine, use response = ec2.start instances If you need to end the Machine, use response = ec2.terminate instances. # Stopping the instance with stop instances(InstanceIds=[‘i-03e3d79d5def39c75’,],)
Execute the script above, and the EC2 instance will be in a different state based on the option you choose.
ec2 manage my instance.py in Python
The EC2 instance has been started.
The EC2 instance has been terminated.
The EC2 instance has been terminated.
Finding Information about Multiple EC2 Instances at the Same Time
Let’s end up this lesson with a final Python script that shows how to use the describe instance() function to retrieve particular properties on several EC2 instances at once.
Copy and paste the following Python code into your code editor and save it as ec2 all instances.py with your code editor open.
The Python script that follows first establishes an AWS client connection. It then utilizes the describe instances() function to query different properties of all running EC2 instances, as seen before. By filtering on one of the available properties, instance-state-name, with the value of running, it’s restricting the results to just running instances.
The AWS documentation lists all of the possible characteristics to filter on.
If you expect the describe instances() function to produce several instances, use the get() method with the Reservations parameter to receive all instances. The script then utilizes a for loop to traverse through each reservation and each instance inside each reservation to print out the InstanceID, InstanceType, and PrivateIPAddress of each instance identified in order to only return particular information.
# Importing the boto3 library to enable functionality boto3 import # Setting up an AWS EC2 client connection ec2 = boto3.client(‘ec2’) # Get a list of currently running instances using the Describe Instance Method and filters. When you need to interact with several instances, use get(“Reservations”). Because each instance only has one reservation. reservations = ec2 client.describe instances(Filters=[“Name”: “instance-state-name”, “Values”: [“running”], ]), ec2 client.describe instances(Filters=[“Name”: ” get(“Reservations”) # Iterating through reservations using for loop() to create instance id, instance type, and private IP address of running instances for reservations: for instance in reservation[“Instances”]: # # Every reservation has an embedded Instances array that holds all of the reservation’s EC2 instances. instance[“InstanceId”] = instance id instance[“InstanceType”] = instance type instance[“PrivateIpAddress”] = private ip print(f”instance id, instance type, private ip”, “private ip”)
Open a terminal window and run the script. If all goes according to plan, each of your EC2 instances should be returned with its own instance ID, instance type, and private IP address.
ec2 all instances.py in Python
Each instance’s specifics
How to Use EBS Snapshots to Backup AWS EC2 Instances
Conclusion
You should now be able to use the Boto3 EC2 Python SDK to manage Amazon EC2 instances. Using the Management Console to do operations like creating, tagging, listing, and describing instances should be obsolete!
What do you intend to handle now that you’ve set up AWS EC2 with Boto3?
The “boto3.resource(‘ec2’) example” is the first step to getting started with managing AWS EC2 instances. The example uses boto 3, which is a Python library for Amazon Web Services (AWS).
Related Tags
- python script to get ec2 instance details
- boto3 ec2
- boto3 ec2 filter by tag
- boto3 create_instances
- boto3 ec2 resource