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

使用RDS Proxy连接PostgreSQL:psycopg2可用SQLAlchemy失败求助

问题:RDS Proxy + SQLAlchemy IAM认证失败,psycopg2连接正常

我通过RDS Proxy连接运行PostgreSQL的RDS实例,使用psycopg2代码可以正常连接:

creds = read_config(config_file_location)
rds_client = boto3.client('rds')

auth_token = rds_client.generate_db_auth_token( 
    DBHostname=creds['host'], 
    Port=creds['port'], 
    DBUsername=creds['user'],
    Region=creds['region']
)

return psycopg2.connect(user=creds['user'],
                        password=auth_token,
                        host=creds['host'],
                        port=creds['port'],
                        database=creds['db'],
                        sslmode='require')

但使用SQLAlchemy尝试连接时出现IAM认证失败错误:

config = read_config(config_file_location)
rds_client = boto3.client('rds')

auth_token = rds_client.generate_db_auth_token( 
    DBHostname=config['host'], 
    Port=config['port'], 
    DBUsername=config['user'],
    Region=config['region']
)

config['password'] = auth_token
sqlalchemy_url = "postgresql://{user}:{password}@{host}:{port}/{db}".format(**config)
engine = create_engine(sqlalchemy_url(), connect_args={"sslmode": "require"})

错误信息:

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server 
at "<<PROXY HOST>>" (<< IP >>), port 5432 failed: 
FATAL:  The IAM authentication failed for the role << USER >>. 
Check the IAM token for this role and try again.

直接用密码连接时SQLAlchemy可以正常工作,不清楚为何仅RDS Proxy+SQLAlchemy组合失败,求解决建议。


解决建议
  • 避免在URL中直接传递IAM认证令牌:IAM令牌包含/、+、=等特殊字符,直接拼接进SQLAlchemy URL会被自动URL编码,导致RDS Proxy无法正确解析令牌。改用create_engine的connect_args传递密码,而非拼接进URL:

    config = read_config(config_file_location)
    rds_client = boto3.client('rds')
    
    auth_token = rds_client.generate_db_auth_token( 
        DBHostname=config['host'], 
        Port=config['port'], 
        DBUsername=config['user'],
        Region=config['region']
    )
    
    # 构建不带密码的URL
    sqlalchemy_url = "postgresql://{user}@{host}:{port}/{db}".format(**config)
    # 通过connect_args传递密码和sslmode
    engine = create_engine(
        sqlalchemy_url,
        connect_args={
            "password": auth_token,
            "sslmode": "require"
        }
    )
    
  • 验证RDS Proxy的IAM认证配置:确保RDS Proxy已启用IAM认证,关联的IAM角色拥有rds-db:connect权限,且目标RDS实例的IAM认证也处于启用状态。

  • 检查令牌生成参数的正确性:确认生成令牌时使用的DBHostname是RDS Proxy的端点(而非RDS实例端点),端口号与Proxy的端口一致(通常为5432)。

  • 明确指定SQLAlchemy驱动:尝试使用postgresql+psycopg2://格式明确指定驱动,避免潜在的兼容性问题:

    sqlalchemy_url = "postgresql+psycopg2://{user}@{host}:{port}/{db}".format(**config)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 21:27:04