aws instance listing using python sdk

This blog is for those, who are very new to aws and python. They want to start both of them together. Assuming they have setup boto3 environment in their test lab.

In lab setup type python: python

It will give python prompt, we can explore boto3.

>>> import boto3
>>> dir(boto3)
[‘DEFAULT_SESSION’, ‘NullHandler’, ‘Session’, ‘__author__’, ‘__builtins__’, ‘__doc__’, ‘__file__’, ‘__name__’, ‘__package__’, ‘__path__’, ‘__version__’, ‘_get_default_session’, ‘client’, ‘docs’, ‘exceptions’, ‘logging’, ‘resource’, ‘resources’, ‘session’, ‘set_stream_logger’, ‘setup_default_session’, ‘utils’]

Perform help (boto3) ,It will show the package content with this package..

PACKAGE CONTENTS
compat
docs (package)
dynamodb (package)
ec2 (package)
exceptions
resources (package)
s3 (package)
session
utils

Lets import the resources : from boto3 import resources

>>> dir (boto3.resources)
[‘__builtins__’, ‘__doc__’, ‘__file__’, ‘__name__’, ‘__package__’, ‘__path__’, ‘action’, ‘base’, ‘collection’, ‘factory’, ‘model’, ‘params’, ‘response’]
>>>

PACKAGE CONTENTS
action
base
collection
factory
model
params
response

 

/*perform following on your python console or write a .py script
import boto3
ec2=boto3.resource(ec2)
#help(ec2) /*it will list all the available option with ec2*/
#help(ec2.instances) /*search for filter*/
#help(ec2.instances.filter /*list the filter option and list syntax
/* instance_iterator = ec2.instances.filter(
 | DryRun=True|False,
 | InstanceIds=[
 | 'string',
 | ],
 | Filters=[
 | {
 | 'Name': 'string',
 | 'Values': [
 | 'string',
 | ]
 | },
 | ]
*/


import boto3
ec2=boto3.resource('ec2')
instances = ec2.instances.filter(
    Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
for instance in instances:
    print(instance.id, instance.instance_type)
amit
Working as an Architect, Infra designer. If any query related to Infra Design [related to cloud,vmware,openstack], please write: amit@openwriteup.com