使用 boto3 访问其他 aws 用户 s3 存储桶

Kas*_*hav 2 amazon-s3 amazon-web-services boto3

我正在制作一个 Django Web 应用程序,它可以列出用户 s3 存储桶,还可以让我访问 s3 存储桶中的其他用户文件。有什么方法可以使用 boto3 访问其他用户帐户,例如某些临时凭据?

tkw*_*rgs 6

boto3 具有返回角色的临时凭证的假设角色方法。

为使其工作,您正在访问的账户必须具有一个允许访问 S3 存储桶的策略的角色,并且该角色本身必须与您从中调用的账户具有信任关系。

此外,运行 django 应用程序的实例应该有一个允许AssumeRole权限的实例角色。

代码看起来像

import boto3

sts = boto3.client('sts')
response = sts.assume_role(
    RoleArn='aws:arn:iam::OTHERACCOUNTID:role/role-that-allows-s3-access',
    RoleSessionName='my-random-session-name',
    DurationSeconds=900 # how many seconds these credentials will work
)

s3 = boto3.client(
    's3',
    aws_access_key_id=response['Credentials']['AccessKeyId'],
    aws_secret_access_key=response['Credentials']['SecretAccessKey'],
    aws_session_token=response['Credentials']['SessionToken']
)

response = s3.list_objects(
    Bucket='bucket-in-other-account'
)
Run Code Online (Sandbox Code Playgroud)