I'm trying to append to the public_buckets list all the bucket names of buckets that have BlockPublicAcls and BlockPublicPolicy set to False. For this, I'm using a counter that means the bucket is public when it is equal to 2.
filtered_buckets = list(filter(lambda item: not list_in_list(exceptions, item['Name']), buckets))
public_buckets = []
def check_bucket_access_block():
for bucket in filtered_buckets:
try:
response = s3client.get_public_access_block(Bucket=bucket['Name'])
for key, value in response['PublicAccessBlockConfiguration'].items():
logger.info('Bucket: {}, {}: {}'.format(bucket['Name'], key, value))
count = 0
if key == response['PublicAccessBlockConfiguration']['BlockPublicAcls'] and value == False:
count += 1
if key == response['PublicAccessBlockConfiguration']['BlockPublicPolicy'] and value == False:
count += 1
if count == 2 and bucket['Name'] not in public_buckets:
public_buckets.append(bucket['Name'])
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'NoSuchPublicAccessBlockConfiguration':
print("Bucket: {} has no Public Access Block Configuration".format(bucket['Name']))
else:
print("unexpected error: %s" % (e.response))
I know there are a few buckets in the filtered_buckets list with both key values set to False. However, they are not being appended to the list.
When I print the public_buckets list it returns an empty [].
This is the response syntax:
{
'PublicAccessBlockConfiguration': {
'BlockPublicAcls': True|False,
'IgnorePublicAcls': True|False,
'BlockPublicPolicy': True|False,
'RestrictPublicBuckets': True|False
}
}
I don't know if that's a logical mistake - in the if statements - or maybe a type mismatch.
Any idea?
Your logic in this line isn't doing what you expect:
if key == response['PublicAccessBlockConfiguration']['BlockPublicAcls'] and value == False:
response['PublicAccessBlockConfiguration']['BlockPublicAcls']
will return True
or False
-- it's returning the Value
for that dictionary entry, not the Key
.
Instead, you could use:
if not response['PublicAccessBlockConfiguration']['BlockPublicAcls'] and not response['PublicAccessBlockConfiguration']['BlockPublicPolicy'] and bucket['Name'] not in public_buckets:
public_buckets.append(bucket['Name'])
This will append the bucket name if BlockPublicAcls
and BlockPublicAcls
are both False and the bucket is not already in the list.