【发布时间】:2020-04-14 04:49:07
【问题描述】:
首先我知道这些问题:
- Grant EC2 instance access to S3 Bucket
- Can't access s3 bucket using IAM-role from an ec2-instance
- Getting Access Denied when calling the PutObject operation with bucket-level permission
但解决方案对我不起作用。
我创建了一个角色“sample_role”,将AmazonS3FullAccess-policy 附加到它,并将该角色分配给了ec2-instance。
我的bucket-policy如下:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::My-Account-ID:role/sample_role"
},
"Action": "s3:*",
"Resource": "arn:aws:s3:::my_bucket/*"
}
]
}
在我的 ec2 实例上,从命令行 (aws s3 ls) 和 python 脚本列出我的存储桶都可以正常工作。
但是当我尝试上传文件 test.txt 到我的存储桶时,我得到了AccessDenied:
import boto3
s3_client = boto3.client('s3')
s3_resource = boto3.resource('s3')
bucket = s3_resource.Bucket('my_bucket')
with open('test.txt', "rb") as f:
s3_client.upload_fileobj(f, bucket.name, 'text.txt')
错误信息:
botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied
当我尝试列出存储桶中的对象时也会发生同样的情况。命令行aws s3api list-objects --my_bucket或python脚本:
import boto3
s3_resource = boto3.resource('s3')
bucket = s3_resource.Bucket('my_bucket')
for my_bucket_object in bucket.objects.all():
print(my_bucket_object)
错误信息:
botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the ListObjects operation: Access Denied
当我在我的存储桶设置中关闭“阻止所有公共访问”并在我的访问控制列表中启用公共访问时,它显然有效。但我需要限制对指定角色的访问。
我错过了什么? 感谢您的帮助!
【问题讨论】:
-
s3:ListBucket 是存储桶级别的操作。它需要
arn:aws:s3:::my_bucket的资源(而不是与对象有关的arn:aws:s3:::my_bucket/*)。 -
谢谢。所以我将
my_bucket/*添加到我的资源中,例如:"Resource": [ "arn:aws:s3:::my_bucket", "arn:aws:s3:::my_bucket/*" ],但列出对象仍然失败。这也不能解释为什么上传失败,对吧? -
退后一步,您想通过 S3 存储桶上的策略来实现什么目标?如果您授予 IAM 角色访问存储桶的权限,那么您也不需要在 S3 存储桶策略中允许它(通常您没有存储桶策略)。您是否尝试将对该存储桶的访问限制为特定 IAM 角色?
-
是的,我想将存储桶的访问权限限制为在我的存储桶策略中指定的 IAM 角色,例如
"Principal": { "AWS": "arn:aws:iam::My-Account-ID:role/sample_role" } -
aws.amazon.com/blogs/security/…有一篇关于这个话题的文章
标签: amazon-web-services amazon-s3 amazon-ec2