Skip to content

Using Cloud SQL

Automatic configuration of a Cloud SQL connection to servces is still in the works. In the meantime, service maintainers can configure a connection themselves. The following procedure uses IAM database authentication for passwordless logins:

  • Locate the Cloud Run service account name:
Terminal window
gcloud run services describe $SERVICE_NAME --project=$GCP_PROJECT --region=$GCP_REGION --format=json | jq -r .spec.template.spec.serviceAccountName
  • Assign to the service account the IAM roles Cloud SQL Client and Cloud SQL Instance User in the project in which the Cloud SQL instance resides
  • Enable IAM authentication in your Cloud SQL instance:
gcloud sql instances patch $CLOUD_SQL_INSTANCE --database-flags=cloudsql.iam_authentication=on --project=GCP_PROJECT
  • Create a database user in your Cloud SQL instance associated with the service account name. Note that due to Postgres usernames length limit, the user name does not include the .gserviceaccount.com suffix:
Terminal window
gcloud sql users create $SA_SHORT_NAME --instance=$CLOUD_SQL_INSTANCE --project $GCP_PROJECT --type=cloud_iam_service_account
  • Grant permissions to the user in Postgres:
GRANT cloudsqlsuperuser to $SA_SHORT_NAME;
  • Substitute your service’s Dockerfile CMD command with a startup script that starts the Cloud SQL Auth Proxy in the background, specifying your Cloud SQL instance connection name, and with the --auto-iam-authn option (see an example script here)
  • Configure your application to connect to host 127.0.0.1, port 5432, and use the database username created in the previous steps. You can use .runway/env-staging.yml to configure these values (see an example MR here)

For an example of the entire process, see this issue.