List all the running instance on amazon VPC

In my test environment, I have amazon VPC, which I am accessing using Linux server.

For performing all the activities on amazon vpc, I have used python script.For automation in amazon VPC, aws provides module boto3, which need to be installed using python pip. Using this module we list all the running instances.In below script I am creating a config file and then reading that config file.Following script perform all these steps:

  • Create a config file, which is required to connect aws vpc.
  • Read the config file, and list all the instance following details:
    • ‘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

 

</script>

import ConfigParser,boto3,os,sys,paramiko
from collections import defaultdict
config = ConfigParser.RawConfigParser()
#When adding sections or items, add them in reverse order
config.add_section('EC2')
config.add_section('USER')
config.set('EC2','SSHKey','<keyname>')
config.set('EC2','VPC_IP','<vpcname>')
config.set('EC2','Security_Group','<securitygroupname>')
config.set('EC2','DisableAPI_Termination','False')
config.set('USER','Username','<ec2user>')
config.set('USER','AWS_Profile','<aws user to login>')
config.set('EC2','Region','<aws region>')
config.set('USER','Private_Key','<path_to_privatekey>')

#Writing configruation to config file
name = raw_input("Enter the config file name::: ")
with open(name, 'wb') as configfile:
config.write(configfile)
#Reading the config file
config1 = ConfigParser.ConfigParser()
config1.read(name)
ses = boto3.Session(profile_name = config1.get("USER", "AWS_Profile"))
ec2 = ses.resource('ec2')
key = paramiko.rsakey.RSAKey.from_private_key_file(filename=config1.get("USER","Private_Key")) 
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']
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("------")

 

output of the script :

——
Name:testinstance
Type:m4.xlarge
State:running
Private IP:10.140.30.209
Public IP:None
Launch Time:2016-08-26 23:09:17+00:00
——

 

 

amit
Working as an Architect, Infra designer. If any query related to Infra Design [related to cloud,vmware,openstack], please write: amit@openwriteup.com