1
votes

I am trying to connect google cloud sql instance with cloud function written in python.

global pg_pool, pg_pool_db_name
pg_config = {
    'user': CONNECTION_DATA[dbname]['DB_USER'],
    'password': CONNECTION_DATA[dbname]['DB_PASSWORD'],
    'host': host,
    'dbname': dbname
}

pg_pool = ThreadedConnectionPool(1, 1, **pg_config)

This function test call failed and it outputs error message:

Error: function terminated. Recommended action: inspect logs for termination reason. Details:could not connect to server: Connection refused
Is the server running locally and accepting
connections on Unix domain socket "/cloudsql/my_instance_name/.s.PGSQL.5432"?

Anybody experienced on this kind of situation.

1
Hi, you don't specify which runtime are you using or which documentation are you following to perform the connection. I can sugest you to follow the official Cloud SQL documentationChris32
I am using python3.7 runtime. And on the document I am not sure with this part, "sure the service account used has the correct permissions"James Willian
Can you share how did you deploy your Cloud Function?guillaume blaquiere
I deployed the python function to source repository.James Willian

1 Answers

2
votes

I wrote a tutorial about Connect from google cloud functions to Cloud SQL

9.Create a service account for your cloud function. Ensure that the service account for your service has the following IAM roles: Cloud SQL Client, and for connecting from Cloud Functions to Cloud Sql on internal ip we need also the role Compute Network User.

    gcloud iam service-accounts create cloud-function-to-sql
    gcloud projects add-iam-policy-binding gcf-to-sql --member serviceAccount:[email protected]   --role roles/cloudsql.client
    gcloud projects add-iam-policy-binding gcf-to-sql --member serviceAccount:[email protected]  --role roles/compute.networkUser

Then deploy the function using the service account you just created:

2.Deploy the cloud function:

    gcloud beta functions deploy gcf_to_sql --runtime python37 --region europe-west2 --service-account cloud-function-to-sql  --trigger-http
 

EDIT

Please read this documentation:

1.Creating a service account

2.Granting roles to service accounts

3.Deploying Cloud function from Cloud Console

Click More to display advanced options, such as setting a region, specifying a timeout, or adding environment variables

On Advanced options, choose the service account you just created.