Mike D
Mike D

Reputation: 365

How to get a total count of S3 Buckets with Python Boto3

I'm attempting to get a list of total amount of S3 Buckets on a given AWS account.

Using boto3 and Python 2.7, I have done the following:

import boto3

s3 = boto3.resource('s3')
for bucket in s3.buckets.all():
  bucket_names = (bucket.name)
  print bucket_names.count('\n')

However, this results in a 0 output for each line in bucket_names. Essentially, I'm trying to get the 'wc -l' equivalent if I were to do this in a nix shell.

Upvotes: 0

Views: 2262

Answers (2)

Lamanus
Lamanus

Reputation: 13551

You can also obtain the number of buckets by using boto3 resource such a way,

import boto3

buckets = [bucket.name for bucket in boto3.resource('s3').buckets.all()]
print(len(buckets))
print('\n'.join(buckets))

where it will also prints the bucket names.

Upvotes: 0

Vikyol
Vikyol

Reputation: 5625

You can use s3 client.

import boto3

client = boto3.client('s3')

response = client.list_buckets()

print(len(response['Buckets']))

Upvotes: 1

Related Questions