You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Boto3调用AWS Secrets Manager时遭遇NoCredentialsError报错求助

解决AWS Secrets Manager凭证定位错误

错误botocore.exceptions.NoCredentialsError: Unable to locate credentials表示boto3无法找到AWS访问凭证,以下是几种可靠的解决方式:

1. 本地配置凭证文件

在用户主目录下创建.aws文件夹,里面新建两个文件:

  • credentials文件(存储密钥):
    [default]
    aws_access_key_id = 你的AWS访问密钥ID
    aws_secret_access_key = 你的AWS私有访问密钥
    
  • config文件(设置默认区域):
    [default]
    region = us-east-1
    

配置完成后,代码无需手动设置区域和凭证,boto3会自动读取这些配置。

2. 临时设置环境变量

方式一:终端运行前设置

export AWS_ACCESS_KEY_ID="你的AWS访问密钥ID"
export AWS_SECRET_ACCESS_KEY="你的AWS私有访问密钥"
export AWS_DEFAULT_REGION="us-east-1"

再运行你的Python脚本。

方式二:代码内添加(仅限临时测试,禁止提交到代码仓库)

修改代码如下:

import boto3
import os

# 设置凭证和区域
os.environ['AWS_DEFAULT_REGION'] = "us-east-1"
os.environ['AWS_ACCESS_KEY_ID'] = "你的AWS访问密钥ID"
os.environ['AWS_SECRET_ACCESS_KEY'] = "你的AWS私有访问密钥"

def get_secret_value():
    """Gets the value of a secret."""
    secrets_client = boto3.client("secretsmanager")
    kwargs = {'SecretId': "DBName"}
    response = secrets_client.get_secret_value(**kwargs)
    print(response)
    return response

get_secret_value()

3. 为AWS服务实例绑定IAM角色(生产环境推荐)

如果代码运行在EC2、ECS、Lambda等AWS托管服务上,直接给这些资源绑定具备Secrets Manager访问权限的IAM角色:

  • 角色权限策略需包含secretsmanager:GetSecretValue动作,且资源指定为目标密钥DBName的ARN。
  • 配置完成后,boto3会自动获取角色凭证,无需手动配置任何密钥。

4. 验证凭证有效性

用AWS CLI测试凭证是否能正常访问密钥:

aws secretsmanager get-secret-value --secret-id DBName --region us-east-1

如果CLI能返回结果,说明凭证没问题,再检查代码配置是否与CLI一致。

内容的提问来源于stack exchange,提问作者Dhruvi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 06:36:32