2 years ago
#345785
WJA
Connecting to Cloud SQL with Private IP gives timeout when trying to connect in Cloud Functions despite successful connectivity test
I am trying to connect to a Cloud SQL instance with Private IP through a Cloud Function which runs all egress traffic through a VPC connector.
I did a connectivity test which gave the following results:
Then, I deployed a Cloud Function following the docs and run the following code:
import sqlalchemy
import os
from google.cloud import storage
# SQLAlchemy==1.4.28
# psycopg2-binary==2.9.2
# google-cloud-storage==2.2.1
def hello_world(request):
    # Remember - storing secrets in plaintext is potentially unsafe. Consider using
    # something like https://cloud.google.com/secret-manager/docs/overview to help keep
    # secrets secret.
    db_user = '<DB-USER>'
    db_pass = '<DB-PASSWORD>'
    db_name = 'postgres'
    db_host = '172.16.0.5:5432'
    # Extract port from db_host if present,
    # otherwise use DB_PORT environment variable.
    host_args = db_host.split(":")
    if len(host_args) == 1:
        db_hostname = db_host
        db_port = os.environ["DB_PORT"]
    elif len(host_args) == 2:
        db_hostname, db_port = host_args[0], int(host_args[1])
    print(f"{db_hostname}, {db_port}")
    pool = sqlalchemy.create_engine(
        # Equivalent URL:
        # mysql+pymysql://<db_user>:<db_pass>@<db_host>:<db_port>/<db_name>
        sqlalchemy.engine.url.URL.create(
            drivername="postgresql+psycopg2",
            username=db_user,  # e.g. "my-database-user"
            password=db_pass,  # e.g. "my-database-password"
            host=db_hostname,  # e.g. "127.0.0.1"
            port=db_port,  # e.g. 5432
            database=db_name,  # e.g. "my-database-name"
        )
    )
    print(f'Created engine : {pool}')
    pool.connect()
    print(f'Done engine : {pool}')
    return 'Ended well', 200
However, it is unable to connect to the instance, and the function times out at pool.connect():
I confirm that the source IP is in line with the expectation of the connectivity test (11.0.0.11).
What could be the reason, or what could I do to find out the actual cause?
python
google-cloud-functions
google-cloud-sql
vpc
0 Answers
Your Answer

