In this blog, we will look at how to execute Python script to get the AWS EC2 details like Name tag valie of the instance, Instance ID, Platform, Instance Type, State and its private IPv4 address. You will require Python 3.8 or above to run the the script successfully.
Setting up Boto3 Session and client
import boto3
# setup profile and region
profile = "default"
region = "us-east-1"
session = boto3.Session(profile_name=profile, region_name=region)
ec2_client = session.client('ec2')
response = ec2_client.describe_instances()
ec2_list = response['Reservations'] # Gather information about EC2
ec2_name = session.resource('ec2')
instances = ec2_name.instances.all() # This will help to retrieve Tags information
Now, let's print the header row.
# print header
print('Name, Instance ID, Platform, Instance Type, State, Private IPv4')
Following code will run and collect the information about EC2.
for ec2 in ec2_list:
ec2_describe = ec2['Instances']
for ec2_details in ec2_describe:
# Saving instance ID to the variable
ec2_id = ec2_details['InstanceId']
# Setting up EC2 platform type: windows or Linux
ec2_platform = ec2_details['PlatformDetails']
# Saving EC2 instance type to the variable
ec2_type = ec2_details['InstanceType']
# Saving EC2 state (Running/Stoped) to the variable
ec2_state = ec2_details['State']
# Saving EC2 private IPv4 address to the variable
ec2_privateip = ec2_details['PrivateIpAddress']
instances = ec2_name.instances.filter(
InstanceIds=[
ec2_details['InstanceId']
],
)
# Fetching the Name tag value of the Instance ID
for instance in instances:
for tag in instance.tags:
if tag["Key"] == 'Name':
instance_name = tag["Value"]
print(instance_name,', ', ec2_id,', ',ec2_platform,', ',ec2_type ,', ',ec2_state['Name'], ec2_privateip)
You can also include the other EC2 details such as Public IPv4, AMI ID, Keypair and launch time etc....
You can also use Tabulate module to format your output to table or HTML format. To use to Tabulate module, please ensure that you have installed the module first. You can install the Tabulate module by running pip install tabulate command.
Hope you find it useful.
Disclaimer: www.TechieTalks.co.uk does not conceal the possibility of error and shortcomings due to human or technical factors. www.TechieTalks.co.uk does not bear responsibility upon any loss or damage arising from conduct or activities related to the use of data and information contained in this blog.
Comments
Post a Comment