Connecting to GCP CloudSQL

We will use CloudSQL Proxy to securely access your database on CloudSQL from Reploy instances.

To get started, we will need to populate the following three environment variables as secrets on our repository in Reploy.

CLOUDSQL_SERVICE_ACCOUNT

This is the base64 encoding of JSON key for the service account that is needed to access our CloudSQL instance. To elaborate, we will first need to create a service account and give it the appropriate permissions (often CloudSQL Admin) to access our database. In order to create a service account, head over to https://console.cloud.google.com/iam-admin/serviceaccounts/create and here's a screenshot of what you'll need to do.

Next, grant the appropriate permissions to the service account. Most Reploy users often provide CloudSQL Admin to enable reads/writes/modifications to their database.

That's it! Once you've created the service account and given it the appropriate permissions, we will now download the Key for that service account. Head over to https://console.cloud.google.com/iam-admin/serviceaccounts and click on the three dots for your service account and click on "Create key".

The final step in this process is to encode the key JSON file that was just downloaded to a base64 string that we will store as a secret on Reploy.

base64 -i <key.json>

Go ahead and store the value as a secret on Reploy where the key is CLOUDSQL_SERVICE_ACCOUNT and the value is the base64 string we just generated.

CLOUDSQL_PORT

This is just the port number you want the proxy to run on for database access. Most common for PostgresSQL is 5432.

CLOUDSQL_INSTANCE

This is the CloudSQL instance name that you want the proxy to point to. To find that out for your instance, head over to https://console.cloud.google.com/sql/instances and click on your instance detail page.

Use the field in the Connection name as the value for this secret.

Integration into Reploy

We have a custom script that will get the proxy set up and running once you have the required secrets as described above.

curl https://getreploy.com/cloudsql.sh | bash

You can execute this command in the serve step of your service and the CloudSQL proxy will run in the background at localhost:<CLOUDSQL_PORT> where the port is derived from the secret. You can now connect to your database in code using this address.

Here's a sample usage for a Reploy service:

services:
backend:
port: 5000
runtime: go
build:
- go build .
serve:
- curl https://getreploy.com/cloudsql.sh | bash
- go run .