简体   繁体   中英

Boto3 - S3 Bucket Policy Update

I am trying to modify the bucket policy of one of my buckets using boto3 . Please refer to the following inital/existing bucket policy of the bucket:

{
    "Version": "2012-10-17",
    "Id": "Policy1604310539665",
    "Statement": [
        {
            "Sid": "Stmt1604310537860",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::xxx:root"
            },
            "Action": [
                "s3:ListBucket",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::bucket",
                "arn:aws:s3:::bucket*"
            ]
        }
    ]
}

I am trying to modify the above policy using the following piece of code, I am trying to attach one more role to the bucket policy :

import boto3
import json

s3 = boto3.client('s3')
result = s3.get_bucket_policy(Bucket=bucket_name)   
policy_statement=json.loads(result['Policy'])

store = policy_statement['Statement'][0]['Principal']['AWS']
del policy_statement['Statement'][0]['Principal']['AWS']


if(isinstance(store, str)):
    role_arn_list = [role_arn] + [store]
    policy_statement['Statement'][0]['Principal'].update({"AWS": role_arn_list})
else:
    role_arn_list = [role_arn] + store
    policy_statement['Statement'][0]['Principal'].update({"AWS": role_arn_list})
    
    
# Convert the policy from JSON dict to string
policy_new = json.dumps(policy_statement)
# Update the policy of the given bucket
s3 = boto3.client('s3')
s3.put_bucket_policy(Bucket=bucket_name, Policy=policy_new)

The above code works fine, but when I try to put the policy to the bucket I am getting a MalformedPolicy exception. when I tried to debug and find the policy that is created using the above code, I can see the following policy:

{
    'Version': '2012-10-17',
    'Id': 'Policy1604310539665',
    'Statement': [{
        'Sid': 'Stmt1604310537860',
        'Effect': 'Allow',
        'Principal': {
            'AWS': ['arn:aws:iam::xxx:role/xx-xx-xx', 'arn:aws:iam::xx:root', 
            'AROAVCQ6H5MBRCO7T5NKB'
            ]
        },
        'Action': ['s3:ListBucket', 's3:PutObject'],
        'Resource': ['arn:aws:s3:::bucket', 'arn:aws:s3:::bucket/*']
    }]
}

Problem: I am not able to understand from where the random string AROAVCQ6H5MBRCO7T5NKB is coming and how to handle this?

An identifier starting with AROA is a unique ID for an IAM Role, much like an Access Key always starts with AKIA .

See: IAM identifiers - AWS Identity and Access Management

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