如何使用 boto3 访问存储桶

How to access buckets with boto3

这是我的权限:

此外,我将此作为存储桶策略:

{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::manga-learn-data",
                "arn:aws:s3:::manga-learn-data/*"
            ]
        }
    ]
}

我的 ~/.aws/config 文件中有这个:

[default]
region=us-west-2

这在我的 ~/.aws/credentials 文件中:

[default]
aws_access_key_id = <access-key>
aws_secret_access_key = <secret-key>

现在我这样做了:

>>> import boto3
>>> s3 = boto3.resource('s3')
>>> s3.buckets.all()
s3.bucketsCollection(s3.ServiceResource(), s3.Bucket)
>>> for bucket in s3.buckets.all():
...         print(bucket.name)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/alex/anaconda2/lib/python2.7/site-packages/boto3/resources/collection.py", line 83, in __iter__
    for page in self.pages():
  File "/Users/alex/anaconda2/lib/python2.7/site-packages/boto3/resources/collection.py", line 161, in pages
    pages = [getattr(client, self._py_operation_name)(**params)]
  File "/Users/alex/anaconda2/lib/python2.7/site-packages/botocore/client.py", line 262, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/Users/alex/anaconda2/lib/python2.7/site-packages/botocore/client.py", line 552, in _make_api_call
    raise ClientError(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the ListBuckets operation: Access Denied

你会在那里看到回溯。我按照这里的步骤操作:https://github.com/boto/boto3

有什么建议吗?

您的代码当前尝试列出所有存储桶,但 IAM 用户没有这样做的权限。

您要么必须向您的 IAM 用户授予 ListAllMyBuckets 访问权限,例如:

    {
      "Effect": "Allow",
      "Action": "s3:ListAllMyBuckets",
      "Resource": "arn:aws:s3:::*"
    },

或者您需要更改代码以仅访问您感兴趣的存储桶:

bucket = s3.Bucket('manga-learn-data')
for object in bucket:
    # do whatever you need to do here