How Do You Find the Instance Ids of Virtual Servers in AWS Using Python?

Problem scenario
You want to write a Python program to display the instance IDs of virtual servers in AWS.  What do you do?

Solution

Prerequisites
This assumes you have installed Boto3.  If you do not know how, see this posting.  This assumes that you are running it on a server that has access to AWS (e.g., it has access to the internet).

Procedures
As a reference, you may go here to learn more about Boto's features.  Use this program:

""" Usage instructions
  1. replace "aaa111" with the aws_access_key_id of your account
  2. replace "bbb222" with the aws_secret_access_key of your account
     If you are not sure how to find these credentials do the following:
     To find the AWS Access Key ID and AWS Secret Access Key, in the AWS console, click on your name in the upper right hand corner.
     Then click on "My Security Credentials."  Click "Create New Access Key"  Click "Show Access Key."
  3.  Replace us-west-1 with the region that you want to list Ec-2 instances for.
  4.  To run it, call it listids.py and run it with a command like this: "python listids.py"

"""

import boto3

ec2 = boto3.resource('ec2', aws_access_key_id='aaa111', aws_secret_access_key='bbb222', region_name='us-west-1')

print "Instance ID,             Instance Type"
instances = ec2.instances.filter(
    Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
for instance in instances:
    print(instance.id, instance.instance_type)

Leave a comment

Your email address will not be published. Required fields are marked *