使用Python调用AWS STS AssumeRole访问S3遇凭证定位错误求助
解决STS AssumeRole脚本的NoCredentialsError问题
你每日通过Python访问S3存储桶时会话频繁过期,采用STS AssumeRole方式重建连接,但运行脚本时触发以下错误:
botocore.exceptions.NoCredentialsError: Unable to locate credentials
备注:已在.aws目录放置凭证文件,使用的代码如下:
import boto3 # The calls to AWS STS AssumeRole must be signed with the access key ID # and secret access key of an existing IAM user or by using existing temporary # credentials such as those from another role. (You cannot call AssumeRole # with the access key for the root account.) The credentials can be in # environment variables or in a configuration file and will be discovered # automatically by the boto3.client() function. For more information, see the # Python SDK documentation: # http://boto3.readthedocs.io/en/latest/reference/services/sts.html#client # create an STS client object that represents a live connection to the # STS service sts_client = boto3.client('sts') # Call the assume_role method of the STSConnection object and pass the role # ARN and a role session name. assumed_role_object=sts_client.assume_role( RoleArn="ARNGOESHERE", RoleSessionName="AssumeRoleSession1" ) # From the response that contains the assumed role, get the temporary # credentials that can be used to make subsequent API calls credentials=assumed_role_object['Credentials'] # Use the temporary credentials that AssumeRole returns to make a # connection to Amazon S3 s3_resource=boto3.resource( 's3', aws_access_key_id=credentials['AccessKeyId'], aws_secret_access_key=credentials['SecretAccessKey'], aws_session_token=credentials['SessionToken'], ) # Use the Amazon S3 resource object that is now configured with the # credentials to access your S3 buckets. for bucket in s3_resource.buckets.all(): print(bucket.name)
以下是具体排查和解决步骤:
检查
.aws目录的位置与权限- 确认
.aws目录位于当前用户主目录下:Linux/macOS为~/.aws,Windows为C:\Users\<你的用户名>\.aws - 目录下必须有名为
credentials的文件,且权限设置为仅当前用户可读(Linux/macOS执行chmod 600 ~/.aws/credentials) credentials文件格式需符合规范,示例如下:[default] aws_access_key_id = 你的访问密钥ID aws_secret_access_key = 你的秘密访问密钥
- 确认
验证boto3是否能读取到凭证
- 在代码开头添加测试代码,确认凭证是否被正确加载:
import boto3 session = boto3.Session() creds = session.get_credentials() print("当前加载的凭证密钥:", creds.access_key if creds else "未找到凭证") - 运行后若输出“未找到凭证”,说明boto3未识别到凭证文件,需再次检查路径和格式
- 在代码开头添加测试代码,确认凭证是否被正确加载:
指定配置文件(若使用非default配置)
- 如果你的凭证在
credentials文件的其他配置段(比如[s3-access-profile]),创建STS客户端时需显式指定profile:sts_client = boto3.client('sts', profile_name='s3-access-profile')
- 如果你的凭证在
排除环境变量干扰
- 检查是否存在
AWS_ACCESS_KEY_ID、AWS_SECRET_ACCESS_KEY等环境变量,这些变量会覆盖凭证文件配置。Linux/macOS可通过echo $AWS_ACCESS_KEY_ID,Windows通过echo %AWS_ACCESS_KEY_ID%查看,若有设置可临时取消
- 检查是否存在
确认IAM用户权限
- 确保你的IAM用户拥有
sts:AssumeRole权限,否则即使凭证正确,后续也会触发权限错误(先解决当前凭证问题后再验证此项)
- 确保你的IAM用户拥有
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

