How to iterate through several s3 buckets to find if all values in PublicAccessBlockConfiguration is set to TRUE

Viewed 119

So I am trying to write a python script that checks if all the values in public_access_block on s3 buckets are set to TRUE and if one of the bucket is not, then print out which bucket it is.

s3 = boto3.client('s3')
buckets = s3.get_public_access_block(Bucket = 'my-test-bucket)  #this is for one bucket
print(buckets)

My question is: how to write the If logic that it iterates through multiple buckets to check

1 Answers

Check this will work in your case,

Note: If public access block configuration was not found then the function raises an exception and that movement we also yielded the Bucket from a generator function. Customize it as your requirement.

import boto3
import botocore

s3_resource = boto3.resource('s3')
s3_client = boto3.client('s3')


def buckets_with_public_access_block_restrictions() -> Generator:
    """
    Checks for PublicAccessBlockConfiguration values and yield Bucket if any values is False,
    otherwise it will keep continue to check public_access_block.

    It may raise an exception when PublicAccessBlockConfiguration not configured.
    At that movement it will yield bucket as well.

    :return: Bucket
    :rtype: Generator
    """
    for bkt in s3_resource.buckets.all():
        try:
            # Checks bucket which have PublicAccessBlockConfiguration configured
            # else it will raise error `NoSuchPublicAccessBlockConfiguration`
            bucket_conf = s3_client.get_public_access_block(Bucket=bkt.name)
            if not all(bucket_conf.get('PublicAccessBlockConfiguration').values()):
                yield bkt
        except botocore.exceptions.ClientError:
            # Executes when the public access block configuration was not found
            yield bkt  # TODO: It depends on the requirement


def enlist_buckets() -> None:
    for bucket in buckets_with_public_access_block_restrictions():
        print(bucket.name)  # TODO: Perform some operation


enlist_buckets()
Related