Boto3 — Getting Started
Boto3 is the Python SDK for AWS which allows to directly create, update, and delete AWS resources from Python scripts.
Here we will hands-on creating an s3 bucket using boto3 and random possibilities for the same.
Pr-requisites:
- Install python3 and boto3
brew install python3
pip3 install boto3
2. Install aws-cli and configure the same, follow the steps here
Before jumping to the code lets discuss the difference between Client and Resource
Client: low-level service access
Boto3 generates the client from a service definition file which is JSON file. The client’s methods support all types of interaction with the AWS services
Resource: higher-level object-oriented service access
Boto3 generates the resource from JSON resource definition files
Since resource and client both are generated from different files, sometimes it may happen that the options you are getting with client are not available with resource.
Creating S3 bucket
import boto3 #to use boto3 for s3 bucket creation
import uuid # to generate unique s3 bucket name
# to eastablish connection with s3 service using client , this is a low level connection
s3_client = boto3.client('s3')
# use below to establish a high level connection with s3 service
#s3_resource = boto3.resource('s3')
# generating unique bucket name
def creat_bucket_name(bucket_prefix):
return ''.join([bucket_prefix, str(uuid.uuid4())])
bucket_prefix = '<your_bucket_name>'
# You can use this or the below function to create the bucket
#s3_resource.create_bucket(Bucket=creat_bucket_name(bucket_prefix),CreateBucketConfiguration={'LocationConstraint' : 'ap-south-1'})
# function to create s3 bucket, we are doing this to avoid hardcoding of aws region
def create_bucket(bucket_prefix, s3_connection):
session = boto3.session.Session()
current_region = session.region_name
print(bucket_prefix)
bucket_name = creat_bucket_name(bucket_prefix)
print(bucket_name)
bucket_response = s3_connection.create_bucket(Bucket=bucket_name,CreateBucketConfiguration={'LocationConstraint' : current_region})
print(bucket_name, current_region)
return bucket_name, bucket_response
# Storing bucket name and response of bucket creation the below variable
bucket_name, bucket_response = create_bucket('<your_bucket_name>', s3_client) # creating bucket
print(f"Bucket Name: {bucket_name}")››
print(f"Bucket Response: {bucket_response}")
Hope this was helpful
Happy Learning!
Shivani S