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

boto3提示Environment无凭证但环境变量与AWS配置均正常如何解决

报错根因
  • AWS CLI 与 boto3 的凭证链解析逻辑存在差异:执行aws s3 ls时默认优先读取全局环境变量的AK/SK,不受profile配置的限制;但boto3显式指定profile_name初始化Session时,会严格遵循对应profile的配置规则加载凭证,不会优先读取全局环境变量。
  • 当profile中同时配置role_arn和credential_source = Environment时,boto3会尝试读取带当前profile前缀的环境变量(比如PROFILE_A_AWS_ACCESS_KEY_ID)来获取基础凭证用于assume role,找不到对应变量就会抛出你遇到的报错,不会主动复用全局的AWS_ACCESS_KEY_ID、AWS_SECRET_ACCESS_KEY。
  • 你后续将credential_source放到default块的修改无效,boto3默认不会将default块的credential_source配置继承给其他自定义profile,子profile加载时还是找不到对应凭证源配置。
解决方案

方案1:调整boto3初始化逻辑(推荐)

不需要显式绑定profile,直接用全局环境变量的凭证手动assume对应role,改后代码如下:

class Boto3AwsClient(object):
    def __init__(self, localhost, profile):
        self.running_localhost = localhost
        self.profile = profile
        # 优先用全局环境变量创建基础session
        self.session = boto3.Session()
        if self.profile:
            # 读取config中对应profile的role配置
            import configparser
            aws_config = configparser.ConfigParser()
            aws_config.read("/home/airflow/.aws/config")
            profile_conf = aws_config[f"profile {self.profile}"]
            # 手动调用sts完成assume role
            sts_client = self.session.client("sts")
            assumed_role = sts_client.assume_role(
                RoleArn=profile_conf["role_arn"],
                RoleSessionName=f"aws-session-{self.profile}"
            )
            # 用assume返回的凭证生成新session
            self.session = boto3.Session(
                aws_access_key_id=assumed_role["Credentials"]["AccessKeyId"],
                aws_secret_access_key=assumed_role["Credentials"]["SecretAccessKey"],
                aws_session_token=assumed_role["Credentials"]["SessionToken"],
                region_name=profile_conf["region"]
            )

    def aws_client_connect(self, service=None):
        if service is None:
            raise ValueError('Service is not defined in new boto3 session.')
        return self.session.client(service)

方案2:修改AWS配置文件

用source_profile替代credential_source,指定自定义profile复用default块的凭证,config配置修改为:

[default]
region=eu-west-1
output=json

[profile a]
source_profile = default
region=eu-west-1
role_arn=替换为你实际的role arn

[profile b]
source_profile = default
region=eu-west-1
role_arn=替换为你实际的role arn

[profile c]
source_profile = default
region=eu-west-1
role_arn=替换为你实际的role arn

该配置下boto3加载自定义profile时,会先读取source_profile(default)的凭证,default会自动读取全局环境变量的AK/SK,即可解决报错。

方案3:升级boto3版本

1.24.0以下版本的boto3对credential_source = Environment的支持存在兼容bug,将requirements中boto3升级到最新稳定版也可以解决该问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 23:24:03