Orest Divintari
Orest Divintari

Reputation: 13

Connect google cloud function 2nd gen to mysql of another project

I have the following command to deploy a google cloud function.

I use the same command to deploy a google cloud function of gen1 ( except the flag --gen2 ) and everything works fine. In the project that has the database, i have set the role of Cloud Sql Client with the service account that is set in the command.

But when i deploy a google cloud function of gen2, i can't connect to the database of the other project. Given that gen2 cloud functions use Cloud Run i have also checked the service-account that Cloud Run uses, and it matches the service account that has the Cloud Sql Client in the project that has the database.

I get this error

SQLSTATE[HY000] [2002] No such file or directory
      gcloud functions deploy $CLOUD_FUNCTION_NAME-staging-gen2
      --gen2
      --source=./src
      --runtime=$CLOUD_FUNCTION_PHP_VERSION
      --trigger-http
      --entry-point=$CLOUD_FUNCTION_ENTRY_POINT
      --allow-unauthenticated
      --region=$GCP_ZONE
      --project=$PROJECT_ID
      --env-vars-file .env.yml
      --min-instances=$MINIMUM_NUMBER_OF_INSTANCES
      --service-account=*******@appspot.gserviceaccount.com
      ${VPC_CONNECTOR:+--vpc-connector projects/$PROJECT_ID/locations/$GCP_ZONE/connectors/$VPC_CONNECTOR}

I have also tried to not set the --service-account when i deploy and let it use the default. Then i added the default service account to the project which has the database, in the IAM section with the role of Cloud Sql Client but it still does not work.

I use unix_socket to connect to the database, because the database is hosted in another project.

"mysql:dbname=${dbname};port=${port};unix_socket=/cloudsql/${instanceConnectionName}"

Where instanceConnectionName is project_name:europe-west4:database_name

Upvotes: 0

Views: 958

Answers (1)

Reuben Juster
Reuben Juster

Reputation: 26

According to https://cloud.google.com/sql/docs/mysql/connect-functions, you have to add the connection to the cloud run service that is automatically deployed with the gen 2 cloud function. This is the case for other database types as well. Scroll to "If you're using Cloud Functions (2nd gen) and not Cloud Functions (1st gen)"

Upvotes: 1

Related Questions