从 Cloud Run 服务连接时,用户对 Cloud SQL 的访问被拒绝

问题描述 投票:0回答:0

我构建了一个 python flask 应用程序,它连接到云 SQL 实例并执行一些操作。我让它在本地工作,所以我将它 dockerized,并将它上传到谷歌云上的容器注册表。接下来,我从那个容器创建了一个云运行服务,我得到的错误是

**"mydb" is not defined**
。通过检查 SQL 实例的日志,我看到了以下错误:
**[Server] Access denied for user 'root'@'ACTUAL_IP_ADDRESS' (using password: YES)"**

这里只是展示实际问题的一小段代码:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    result = mydb.execute(text("SELECT * from users")).fetchall() #error line
    msg = ""
    for row in result:
        msg += str(row) + "\n"
    return msg

def createSQLConnection():
    # create SQLAlchemy connection pool
    with Connector() as connector:
        conn = connector.connect(
            "actual_region", 
            "pymysql",
            user="root",
            password="actual_password",
            db="actual_db",
            ip_type=IPTypes.PUBLIC 
        )
    pool = sqlalchemy.create_engine(
        "mysql+pymysql://",
        creator=lambda: conn,
    )
    return pool

if __name__ == "__main__":
    pool = createSQLConnection()
    mydb = pool.connect()
    app.run(debug=True)`

我按照文档进行连接。以前我使用 mysql connector for python,但我切换到 google 的 sql 库,因为它自动获得授权。

我将我的 sql 实例配置为具有公共 IP 地址并接受任何人(我知道这样做是不好的做法,但我稍后会更改它)SQL Config

我启用了 IAM admin api,并将 sql 客户端权限添加到应在此处使用的默认应用引擎帐户,以及在 sql 实例上列为服务帐户的帐户 Account permissions

而且在部署时,我添加了我的 sql 实例。 SQL Instance

令我难过的是,这段代码在本地运行,而且我可以像 sql workbench 一样毫无问题地连接到数据库,所以凭据很好。我想我的问题与云运行配置有关。如果可能的话,我想保持简单(没有 VPC,套接字)

deployment google-cloud-sql google-cloud-run access-denied
© www.soinside.com 2019 - 2024. All rights reserved.