Python3 Boto创建S3存储桶已存在错误

时间:2019-02-25 18:54:16

标签: python-3.x amazon-s3 boto3

当我尝试在python3中创建S3存储桶时,出现“存储桶已存在”错误。即使我尝试使用一个肯定不存在的古怪的存储桶名称。

这是代码:

import boto3
# Create an S3 client
s3 = boto3.client('s3')
bucket_name = input("Enter a bucket name: ")
s3.create_bucket(Bucket='bucket_name')

但是不管我给它起什么名字,我都会得到一个存储桶名称已经存在的错误

   PS C:\Users\tdunphy\Desktop\important_folders\git\aws_scripts\python\virtualenvs3\boto3> python3 .\aws_s3_create_bucket.py
Enter a bucket name: company-timd-test-3
Traceback (most recent call last):
  File ".\aws_s3_create_bucket.py", line 9, in <module>
    s3.create_bucket(Bucket='bucket_name')
  File "C:\Users\tdunphy\AppData\Local\Programs\Python\Python37-32\lib\site-packages\botocore\client.py", line 357, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "C:\Users\tdunphy\AppData\Local\Programs\Python\Python37-32\lib\site-packages\botocore\client.py", line 661, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.errorfactory.BucketAlreadyExists: An error occurred 

(BucketAlreadyExists) when calling the CreateBucket operation: The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again

我尝试过的存储桶名称是:company-timd-test3

但是,如果我像这样在程序中对s3存储桶的名称进行硬编码:

import boto3
# Create an S3 client

s3 = boto3.client('s3')

#bucket_name = input("Enter a bucket name: ")
s3.create_bucket(Bucket='company-timd-test3')

它有效并且创建了存储桶:

aws s3 ls --profile=nonprod | findstr "company*"
2019-02-25 14:00:16 company-timd-test3

真正的问题是什么,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您的代码存在以下问题:

s3.create_bucket(Bucket='bucket_name')

您在此处显式传递存储桶名称“ bucket_name”,而不是变量。我可以保证名称“ bucket_name”已经被使用。您的代码应如下所示(无单引号):

s3.create_bucket(Bucket=bucket_name)