I'm very new to the boto3
package, and I'm trying to test out a simple try/except
block that I found here to identify whether the s3 bucket exists. So far I have:
s3 = boto3.resource(
"s3",
aws_access_key_id=self.settings['CREDENTIALS']['aws_access_key_id'],
aws_secret_access_key=self.settings['CREDENTIALS']['aws_secret_access_key'],
)
bucket = s3.Bucket(self.settings['S3']['bucket_test'])
for bucket_in_all in boto3.resource('s3').buckets.all():
if bucket_in_all.name == self.settings['S3']['bucket_test']:
print ("Bucket {} verified".format(self.settings['S3']['bucket_test'])) # This is triggered!
try:
s3.meta.client.head_bucket(Bucket=self.settings['S3']['bucket_test'])
print("Bucket Exists!")
return True
except botocore.exceptions.ClientError as e:
# If a client error is thrown, then check that it was a 404 error.
# If it was a 404 error, then the bucket does not exist.
error_code = int(e.response['Error']['Code'])
if error_code == 403:
print("Private Bucket. Forbidden Access!")
return True
elif error_code == 404:
print("Bucket Does Not Exist!")
return False
The bucket is found when I loop through buckets.all()
, but somehow fails for s3.meta.client.head_bucket
, throwing back error 403. Why? My end aim is to be able to look into an s3 bucket, and identify what files are there. I'm connecting from outside the cluster i.e. the script is currently not being run within the AWS 'cloud', but from my MBP connecting to the relevant cluster.