Querying EC2

Connect to EC2
To create an EC2 resource object

import boto3

ec2 = boto3.resource('ec2')

instances = ec2.instances.all()


# Print raw list of instances
for instance in instances:

  print( instance )


# Print list of instances by name tag
for instance in instances:

  print( [tag['Value'] for tag in instance.tags if tag.get('Key') == 'Name'] )


# Print list of instances by state
states = (

  { 'Code' : 0, 'state' : 'pending' },

  { 'Code' : 16, 'state' : 'running' },

  { 'Code' : 32, 'state' : 'shutting-down' },

  { 'Code' : 48, 'state' : 'terminated' },

  { 'Code' : 64, 'state' : 'stopping' },

  { 'Code' : 80, 'state' : 'stopped' },

)

instance_states = {

  'pending': [],

  'running': [],

  'shuttingdown' : [],

  'terminated' : [],

  'stopping' : [],

  'stopped' : [],

}

for instance in instances:

  instance_name=[tag['Value'] for tag in instance.tags if tag.get('Key') == 'Name']

  instance_states[instance.state['Name']].append( instance_name[0] )

for i in instance_states:

  instance_states[i].sort()

  print(i + ' instances\n--')

  for name in instance_states[i]: print( name )

  print('')
Comments