存储桶名称未附加到列表中

Bucket names not being appended to a list

我正在尝试将 BlockPublicAcls 和 BlockPublicPolicy 设置为 False 的所有存储桶名称附加到 public_buckets 列表中。为此,我使用了一个计数器,当它等于 2.

时,这意味着桶是 public
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))

我知道 filtered_buckets 列表中有几个桶的两个键值都设置为 False。但是,它们没有被附加到列表中。

当我打印 public_buckets 时列出它 returns 一个空的 [].

这是响应语法:

{
    'PublicAccessBlockConfiguration': {
        'BlockPublicAcls': True|False,
        'IgnorePublicAcls': True|False,
        'BlockPublicPolicy': True|False,
        'RestrictPublicBuckets': True|False
    }
}

我不知道这是 if 语句中的逻辑错误还是类型不匹配。

有什么想法吗?

您在这一行中的逻辑没有达到您的预期:

if key == response['PublicAccessBlockConfiguration']['BlockPublicAcls'] and value == False:

response['PublicAccessBlockConfiguration']['BlockPublicAcls'] 将 return TrueFalse - 它是 returning 该词典条目的 Value,而不是 Key.

相反,您可以使用:

if not response['PublicAccessBlockConfiguration']['BlockPublicAcls'] and not response['PublicAccessBlockConfiguration']['BlockPublicPolicy'] and bucket['Name'] not in public_buckets:
    public_buckets.append(bucket['Name'])

如果 BlockPublicAclsBlockPublicAcls 均为 False 并且该存储桶不在列表中,这将附加存储桶名称。