Hello Boto – An Introduction to AWS SDK for Python (Boto3)

More to explore

AWS SDK for Python (Boto3)

In this blog post we will do the following:

  • Define AWS SDK for Python (Boto3)
  • Setup AWS SDK for Python (Boto3)
  • Create Some Simple Scripts

What is the AWS SDK for Python (Boto3)?

Boto3 is the Amazon Web Services (AWS) Software Development Kit (SDK) for Python. This allow people to use Python to write code that makes use of AWS services like EC2, S3, VPC etc. 

You’re probably wondering where the name Boto3 comes from. Boto (pronounced boh-toh) in the name of a fresh water dolphin native to the Amazon river which it gets it’s namesake from. Mitch Garnaat is the original author but it is currently published and maintained by Amazon Web Services.

Throughout the rest of the blog post we will refer to it as Boto3. I am in no way an expert in Boto3 or Python but I have been using it quite frequently recently and this will be from a new user perspective.

Boto3 has the following features:

  • Configuration – This is where you can store your configuration data such as the AWS region or your access credentials. It goes through the following lookup order when pulling config data.
    • A Config object that’s created and passed as the config parameter when creating a client
    • Environment variables
    • The ~/.aws/config file
  • Credentials – This is how you configure your Boto3 credentials for AWS, we will discuss this further later.
  • Low-level clients – This is the low-level interface to AWS service APIs. This is our meat and potatoes for working with AWS.
  • Resources – This represents their object oriented interface to AWS. The AWS Python SDK team is no longer planning to support the resources interface in boto3. My guess is they want to push folks to the CDK.
  • Session – The session manages the state of a particular configuration. This is handled as needed but it is possible to manage your own sessions.
  • Collections – This provides an iterable interface to a group of resources.
  • Paginators – This is the process of sending subsequent requests to continue where a previous request left off.
  • Error Handling – This refers to how exceptions are handling and how to parse errors with AWS services.
  • Retries – This shows how to configure your retry method and number of retries.
  • Extensibility Guide – This is how to extend the functionality of classes through Boto3’s event system.

Why use Boto3?

If you have familiarity with Python already this will give you a great start in manipulating AWS with code. The same skills you already have with Python allows you to create, describe and destroy AWS services. It’s especially useful for serverless with services like Lambda.
 

Setup Boto3

You can get the latest up to date information on their GitHub repository here:

https://github.com/boto/boto3#readme

As of the time of this blog post supported versions of Python are 3.7, 3.8, 3.9, 3.10, 3.11

Install Boto3 as follows:

python -m pip install boto3

The next step is to configure your AWS credentials, I prefer the following command if you have AWS CLI installed however there other options include credentials parameters that you can read about here:

https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html

aws configure

The first line we need in any of our Python scripts to get Boto3 to function is to get it imported as follows:

import boto3

Sample Boto3 Scripts

The first simple script will query all AWS S3 buckets.

import boto3
s3 = boto3.client('s3')
response = s3.list_buckets()
for bucket in response['Buckets']:
    print(bucket['Name'])

This script will list all running AWS EC2 instances.

import boto3
client = boto3.client('ec2')
response = client.describe_instances(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
instances = response["Reservations"]
for instance in instances:
    for tag in instance["Instances"][0]["Tags"]:
        if tag["Key"] == "Name":
            print(tag["Value"])

This last script will enable AWS CloudTrail.

import boto3

cloudtrail = boto3.client('cloudtrail')

response = cloudtrail.create_trail(
    Name='my-cloudtrail',
    S3BucketName='my-s3bucket8675309',
    IsMultiRegionTrail=True
)

if response['ResponseMetadata']['HTTPStatusCode'] == 200:
    print("The CloudTrail trail has been created successfully.")

response = cloudtrail.start_logging(Name='my-cloudtrail')

if response['ResponseMetadata']['HTTPStatusCode'] == 200:
    print("Logging for CloudTrail has been started successfully.")

Conclusion

Boto3 is a great little tool to allow you to use your Python coding skills to manage AWS services. This is especially useful when you’re looking to run code within Lambda. I would recommend jumping before diving into something like the CDK.

Leave a Reply

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