Reading Time: < 1 minute
How to get AWS EC2 instances using python boto3
This tutorial will guide you on How to describe AWS EC2 instances using python. We consider you already have an AWS account however if you do not have please follow the below tutorial to create an AWS account. Once you have an AWS account, You may proceed to create EC2 using Python. You should also create/grant AWS CLI access.
Table of Contents
If you have not created an AWS EC2 instance yet you can create one & complete steps are mentioned here.
Steps to follow
- import boto3
- connect to EC2 resource
- Filter Running instances
- Get instance_id
- Get instance_type
- Get private_ip
- Get , {image_id},
- Get public_ip
How to describe AWS EC2 instances using python
Python Code
import boto3
ec2 = boto3.client('ec2')
reservations = ec2.describe_instances(Filters=[
{
"Name": "instance-state-name",
"Values": ["running"],
}
]).get("Reservations")
for reservation in reservations:
for instance in reservation["Instances"]: ## Each reservation has an embedded Instances array that contains all EC2 instances in the reservation
instance_id = instance["InstanceId"]
instance_type = instance["InstanceType"]
private_ip = instance["PrivateIpAddress"]
image_id = instance["ImageId"]
public_ip = instance["PublicIpAddress"]
print(f" {instance_id}, {instance_type}, {private_ip}, {image_id}, {public_ip} ")
More details on EC2 can be found here