Hello Guys, recently my boss has a requirement.He want to list all the instances of the AWS account across
the regions.So I have use boto3 library and so that we can use it any where with minimal setup.
so I wrote a boto script to get it done.Here is the procedure to use it.step by step. I am using ubuntu 16.04 as an operating system.below procedure will also work fine with
the ubuntu 14.04 as well. 1. Installation: #sudo apt-get install python-softwware-properties #sudo apt-get install python-pip #sudo pip install boto3
2. Configuring the boto3 library
Here we need to create few files like ~/.aws/credentials and ~/.aws/config
$ touch ~/.aws/credentials #Below are the contains of the file replace the foo and bar with the id and access key of your
AWS account [default]
aws_access_key_id=foo aws_secret_access_key=bar
$ touch ~/.aws/config
#add the below containts to the file
region=us-west-2
and after this copy the below script and and execute it but remember in python orientation
matters so dot change the orientation or the script will stop working.
#!/usr/bin/env python
from collections import defaultdict
"""
This script is Written by N.N.R.
on 12-09-16
"""
import boto3
"""
A tool for retrieving basic information from the running EC2 instances.
"""
client = boto3.client('ec2')
regions = client.describe_regions()['Regions']
for region in regions:
region_name=region['RegionName']
# Connect to EC2
for region in regions:
print("below are the instances running in")
region_name=region['RegionName']
print(region_name)
ec2 = boto3.resource('ec2',region_name=region['RegionName'])
# Get information for all running instances
running_instances = ec2.instances.filter(Filters=[{
'Name': 'instance-state-name',
'Values': ['running']}])
ec2info = defaultdict()
for instance in running_instances:
for tag in instance.tags:
if 'Name'in tag['Key']:
name = tag['Value']
# Add instance info to a dictionary
ec2info[instance.id] = {
'Name': name,
'Type': instance.instance_type,
'State': instance.state['Name'],
'Private IP': instance.private_ip_address,
'Public IP': instance.public_ip_address,
'Launch Time': instance.launch_time
}
attributes = ['Name', 'Type', 'State', 'Private IP', 'Public IP', 'Launch Time']
for instance_id, instance in ec2info.items():
for key in attributes:
print("{0}: {1}".format(key, instance[key]))
print("------")
and Let me know if you have any issue with the script.