Google Cloud’s utility for proxying database connections is quite nifty and makes it simple to make databases contactable from your local machine. However, the connection format for proxying TCP connections is a bit verbose.
cloud_sql_proxy -instances={project}:{region}:{instance-name}=tcp:{port}
Instead of looking up the format all the time or getting the connection string from the Web Cloud Console I made a script
which interactively allows the selection of the database instance to proxy over TCP. I added the script to my
.bash_profile
as a function gcloud_sql_proxy
. Below is an example of proxying a Postgres DB to my local port 5433.
Proxying Database Instance 1 to port 5433.
The source for the script is on GitHub. The script depends on your Google Cloud SDK to be
configured, authenticated, and the cloud_sql_proxy
component
installed, gcloud components install cloud_sql_proxy
.
#!/usr/bin/env bash | |
get_instances() { | |
local IFS=$'\n' | |
instances=($(gcloud sql instances list --format="table(name,database_version,region,STATUS, connectionName)")) | |
} | |
get_instances | |
for i in "${!instances[@]}"; do | |
[[ $i = 0 ]] && output="INDEX" || output="$i" | |
printf "%-5s\t%s\n" "$output" "${instances[$i]}"; | |
done | |
read -p "Instance Index: " instance_index | |
if [[ ${instance_index} =~ ^[0-9]+$ ]] && \ | |
[ ${instance_index} -ge 1 ] && [ ${instance_index} -le ${#instances[@]} ]; then | |
instance_line=${instances[${instance_index}]} | |
connection_name=$(awk '{print $5}' <<< ${instance_line}) | |
db_type=$(awk '{print $2}' <<< ${instance_line}) | |
if [[ ${db_type} =~ ^POSTGRES ]]; then | |
port=${1:-5432} | |
elif [[ ${db_type} =~ ^MYSQL ]]; then | |
port=${1:-3306} | |
else | |
echo "Unknown DB Type ${db_type}" && exit 1; | |
fi | |
${CLOUD_PROXY_SQL_BIN:-cloud_sql_proxy} -instances=${connection_name}=tcp:${port} | |
else | |
echo "Invalid Instance Index." >&2 && exit 1; | |
fi |
This is a simple enough wrapper to write but it’d be great if the Google Cloud SQL Proxy had this built in through an
option like --interactive
.