This repo demonstrates how to create a Cloud SQL DB with a private IP address only, and connect to it with Cloud SQL Proxy. The full explanation of how this works can be found in this blog post.
Terraform v1.0.0 or higher is required.
-
Set the name of your Terraform Cloud organization in
backend.tf
. -
Deploy the db and Cloud SQL Proxy
gcloud services enable \ cloudresourcemanager.googleapis.com \ compute.googleapis.com \ iam.googleapis.com \ oslogin.googleapis.com \ servicenetworking.googleapis.com \ sqladmin.googleapis.com terraform init terraform apply
-
Upload your public SSH key to Google's OS Login service
gcloud compute os-login ssh-keys add --key-file=~/.ssh/id_rsa.pub --ttl=365d
-
Connect to the private db through Cloud SQL Proxy
# get your SSH username gcloud compute os-login describe-profile | grep username # get the public IP of the instance running Cloud SQL Proxy CLOUD_SQL_PROXY_IP=$(terraform output proxy_ip) # psql into your private db ssh -t <username>@$CLOUD_SQL_PROXY_IP docker run --rm --network=host -it postgres:14-alpine psql -U postgres -h localhost