简体   繁体   中英

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM