Search code examples
amazon-web-servicesamazon-s3boto3

enabling s3 bucket logging via python code


i'm trying to enable logging on all s3 buckets in my account but getting error while executing the code

def s3_log():
    s3 = boto3.client('s3')
    response = s3.list_buckets()
    for i in response['Buckets']:
        #bucketacl = s3.put_bucket_acl(Bucket=i['Name'],AccessControlPolicy={'Grants': [{'Grantee': {'Type': 'Group','URI': 'http://acs.amazonaws.com/groups/s3/LogDelivery'},'Permission': 'FULL_CONTROL'}]})
        response = s3.put_bucket_logging(
        Bucket=i['Name'],
        BucketLoggingStatus={
            'LoggingEnabled': {
                'TargetBucket': i['Name'],
                'TargetGrants': [
                {
                    'Grantee': {
                        'Type': 'Group',
                        'URI': 'http://acs.amazonaws.com/groups/s3/LogDelivery'
                    },
                    'Permission': 'READ' },
                {
                    'Grantee': {
                        'Type': 'Group',
                        'URI': 'http://acs.amazonaws.com/groups/s3/LogDelivery'
                    },
                    'Permission': 'WRITE'

                },
                ],
                'TargetPrefix': i['Name'] + '/'

            }
        }

    )
Error :
"errorMessage": "An error occurred (InvalidTargetBucketForLogging) when calling the PutBucketLogging operation: You must give the log-delivery group WRITE and READ_ACP permissions to the target bucket"

I have added target grants to add permission to log-delivery group but it seems something is missing in my code.So i went ahead and tried to add bucket acl but then it gives me some malformed xml error so the acl code is commented at the moment


Solution

  • You must give the permission READ_ACP, You can do as follows:

    s3c.put_bucket_acl(
        AccessControlPolicy = {
            "Owner": {
                "ID": "canonical_user_id_sdakfjldsakjf" # see https://docs.aws.amazon.com/general/latest/gr/acct-identifiers.html
            },
            'Grants': [
                {
                    'Grantee': {
                        'Type': 'Group',
                        'URI': 'http://acs.amazonaws.com/groups/s3/LogDelivery'
                    },
                    'Permission': 'WRITE'
                },
                {
                    'Grantee': {
                        'Type': 'Group',
                        'URI': 'http://acs.amazonaws.com/groups/s3/LogDelivery'
                    },
                    'Permission': 'READ_ACP'
                }
            ]
        },
        Bucket=bucket
    )
    

    more on that here