当我简单地运行下面的代码时,我总是得到这个错误。

s3 = boto3.resource('s3')
bucket_name = "python-sdk-sample-%s" % uuid.uuid4()
print("Creating new bucket with name:", bucket_name)
s3.create_bucket(Bucket=bucket_name)

我已将我的证书文件保存在

C:\Users\myname\.aws\证书,从那里Boto应该读我的证书。

我的设置错了吗?

下面是boto3的输出。set_stream_logger (botocore,级别=“调试”)。

2015-10-24 14:22:28,761 botocore.credentials [DEBUG] Skipping environment variable credential check because profile name was explicitly set.
2015-10-24 14:22:28,761 botocore.credentials [DEBUG] Looking for credentials via: env
2015-10-24 14:22:28,773 botocore.credentials [DEBUG] Looking for credentials via: shared-credentials-file
2015-10-24 14:22:28,774 botocore.credentials [DEBUG] Looking for credentials via: config-file
2015-10-24 14:22:28,774 botocore.credentials [DEBUG] Looking for credentials via: ec2-credentials-file
2015-10-24 14:22:28,774 botocore.credentials [DEBUG] Looking for credentials via: boto-config
2015-10-24 14:22:28,774 botocore.credentials [DEBUG] Looking for credentials via: iam-role

当前回答

这些指令适用于具有AWS单一用户配置文件的windows机器。确保你的~/。Aws /凭证文件如下所示

[profile_name]
aws_access_key_id = yourAccessId
aws_secret_access_key = yourSecretKey

我必须将AWS_DEFAULT_PROFILEenvironment变量设置为在凭据中找到的profile_name。 然后我的蟒蛇就能连接了。从这里开始

import boto3

# Let's use Amazon S3
s3 = boto3.resource('s3')

# Print out bucket names
for bucket in s3.buckets.all():
    print(bucket.name)

其他回答

这些指令适用于具有AWS单一用户配置文件的windows机器。确保你的~/。Aws /凭证文件如下所示

[profile_name]
aws_access_key_id = yourAccessId
aws_secret_access_key = yourSecretKey

我必须将AWS_DEFAULT_PROFILEenvironment变量设置为在凭据中找到的profile_name。 然后我的蟒蛇就能连接了。从这里开始

import boto3

# Let's use Amazon S3
s3 = boto3.resource('s3')

# Print out bucket names
for bucket in s3.buckets.all():
    print(bucket.name)

如果使用AWS

在我的情况下,我必须在IAM角色中添加以下策略,以允许ec2实例读取ec2标记。这将消除“无法定位凭据”错误 :

{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "VisualEditor0",
        "Effect": "Allow",
        "Action": "ec2:DescribeTags",
        "Resource": "*"
    }
  ]
}

我在一家大公司工作,遇到过同样的错误,但我需要一个不同的工作方式。我的问题与代理设置有关。我已经设置了代理,所以在我能够让一切正常工作之前,我需要将我的no_proxy设置为AWS白名单。你也可以在bash脚本中设置它,如果你不想用操作系统设置混淆你的Python代码。

Python:

import os
os.environ["NO_PROXY"] = "s3.amazonaws.com"

Bash:

export no_proxy = "s3.amazonaws.com"

编辑:以上假设美国东部S3地区。对于其他区域:使用s3.[region].amazonaws.com,其中区域类似于us-east-1或us-west-2

尝试手动指定键

    s3 = boto3.resource('s3',
         aws_access_key_id=ACCESS_ID,
         aws_secret_access_key= ACCESS_KEY)

出于安全考虑,请确保您没有在代码中直接包含ACCESS_ID和ACCESS_KEY。 考虑使用环境配置,并按照@Tiger_Mike的建议将它们注入到代码中。

对于Prod环境,可以考虑使用旋转访问键: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html#Using_RotateAccessKey

如果您确定正确配置了aws,只需确保项目的用户可以从./aws读取数据,或者只是以根用户身份运行项目