Boto3-S3存储桶策略更新

时间:2020-11-04 08:56:40

标签: python amazon-web-services amazon-s3

我正在尝试使用boto3修改其中一个存储桶的存储桶策略。请参考以下初始/现有存储桶策略:

{
    "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*"
            ]
        }
    ]
}

我正在尝试使用以下代码来修改以上策略,我正在尝试将另一个角色附加到存储桶策略中:

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)

上面的代码工作正常,但是当我尝试将策略放入存储桶时,我遇到了MalformedPolicy异常。当我尝试调试并查找使用上述代码创建的策略时,可以看到以下策略:

{
    '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/*']
    }]
}

问题:我不知道随机字符串AROAVCQ6H5MBRCO7T5NKB的来源以及如何处理?

1 个答案:

答案 0 :(得分:1)

AROA开头的标识符是IAM角色的唯一ID,就像访问密钥始终以AKIA开头一样。

请参阅:IAM identifiers - AWS Identity and Access Management