Geddon
Geddon

Reputation: 1306

How to write S3 bucket policy to file?

I want to pull out the s3 bucket policies from all the s3 buckets I have and store them in their individual .json file. This should be formatted in json. However in my attempted solution it stores the policy in the file with the Response metadata and it not in jSOn format.

"ResponseMetadata": {"HTTPStatusCode": 200, ...... "content-type": "application/json"}}}

Can this be done in python/boto3? Here is my code.

try:
    s3client = get_s3Client('us-east-1')
    response = s3client.list_buckets()
    if response and response['Buckets']:
        for bucket in response['Buckets']:
            bucketName = bucket['Name']
            print (bucketName)
            policyname = policy_output + '\\' + bucketName + '.json'
            print (policyname)

            response = s3client.get_bucket_policy(
                Bucket=bucketName
            )
            print (response)
            with open(policyname, 'w') as f:
                json.dump(response, f)
                #f.write(response)

Upvotes: 0

Views: 554

Answers (1)

jarmod
jarmod

Reputation: 78603

The response from boto3 get_bucket_policy() is a dict. You need to retrieve the 'Policy' element.

Try something like this:

import json
import boto3
from botocore.exceptions import ClientError

s3client = boto3.client('s3')
response = s3client.list_buckets()

if response and response['Buckets']:
    for bucket in response['Buckets']:
        bucketName = bucket['Name']
        print(bucketName)
        policyname = bucketName + '.json'
        print(policyname)

        try:
            response = s3client.get_bucket_policy(
                Bucket=bucketName
            )
            p = response['Policy']
            s = json.dumps(json.loads(p), indent=4)
            with open(policyname, 'w') as f:
                f.write(s)
        except ClientError as e:
            if e.response['Error']['Code'] == 'NoSuchBucketPolicy':
                pass
            else:
                print(e)

Upvotes: 3

Related Questions