Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save skeptrunedev/80cfc5edd87c19a3957733ab89ca94d5 to your computer and use it in GitHub Desktop.
Save skeptrunedev/80cfc5edd87c19a3957733ab89ca94d5 to your computer and use it in GitHub Desktop.
Access a gcloud SQL instance locally through port forwarding

First step is to list the available db's to figure out which one to describe and then copy the connectionName for.

gcloud sql instances list

Assuming the db you want is called foo you would then copy the connectionName as follows.

gcloud sql instances describe foo | grep connectionName | awk '{print $2}' | xclip -selection clipboard

Download cloud-sql-proxy here.

Optionally move cloud-sql-proxy to your bin such that it's path accessible with the following command.

sudo mv cloud-sql-proxy /usr/local/bin

Setup application default credentials using this gcloud guide linked here.

Finally use the cloud-sql-proxy to forward a local port such that the db can be accessed locally.

cloud-sql-proxy --port 6432 {replace with the copied connectionName}

@cdxker
Copy link

cdxker commented Jun 3, 2024

For something a bit more automatic. This uses fzf to select the instance name. Useful if you're a maniac and have multiple SQL instances.

instance_name=$(gcloud sql instances list | tail -n +2 | fzf | awk '{print $1}')
connection_name=$(gcloud sql instances describe $instance_name | grep connectionName | awk '{print $2}')

cloud-sql-proxy --port 6432 $connection_name

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment