BOTO3 is AWS SDK for Python. It allows developers to interact with AWS services such as ec2, DynamoDB, s3, sqs, sns, rds and many other services. In this article we go through two basic services (EC2 & S3) along with advanced packages.
Step 1: Install boto3. This is one of the extended library and may need to install on top of python. Here is the code for reference.
# on windows
py -m pip install boto3
py -m pip install requests
py -m pip install beautifulsoup4 # used for html or xml parsing.
# on linux based
pip install boto3
pip install requests
pip install beautifulsoup4 #
Step 2: Configure AWS using access and secret keys. Ensure to use "aws configure" to setup AWS credentials and enable python to access AWS account. In case you have installed AWS CLI, refer this link.
Step 3: Writing Python Script using boto3. This is a simple query page to extract all the ec2 instances configured for a particular account/region. Extract all stopped instances (can be used for running instances by changing the value) and loads in a dictionary collection, parse through the data to extract basic information about VMs and saves in a list. Finally list is printed.
Note, instance name is stored in Tags as a key value pair in AWS.
import boto3
from collections import defaultdict
ec2 = boto3.resource('ec2')
# Get information for all running instances
running_instances = ec2.instances.filter(Filters=[{
'Name': 'instance-state-name',
'Values': ['stopped']}]) # Filter instances by state
ec2info = defaultdict()
for instance in running_instances: # Iterate through instances
if instance.tags is not None:
for tag in instance.tags:
if 'Name' in tag['Key']:
instance_name = tag['Value']
#print (instance_name)
ec2info[instance.id] = {
'Name': instance_name,
'Type': instance.instance_type,
'ID': instance.id,
'Private IP': instance.private_ip_address,
'Public IP': instance.public_ip_address,
'State': instance.state['Name'],
'Launch Time': instance.launch_time
}
attributes = ['Name', 'Type', 'ID', 'Private IP', 'Public IP', 'State', 'Launch Time']
for instance_id, instance in ec2info.items():
for key in attributes:
print("{0}: {1}".format(key, instance[key]))
print("------")
A similar output can be generated using AWS CLI using below command which seems to be little complicated. Python boto3 gives flexibility to format.
aws ec2 describe-instances --query 'Reservations[].Instances[].[Tags[?Key==Name].Value | [0], PublicIpAddress, ImageId]' --output table
Overall, Boto3 simplifies the process of developing, deploying, and managing applications on AWS by providing a powerful, Python-based interface for working with AWS services and resources.