All Articles

Wrapper Script for Google Cloud SQL Proxy

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.

Demo 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)"))
for i in "${!instances[@]}"; do
[[ $i = 0 ]] && output="INDEX" || output="$i"
printf "%-5s\t%s\n" "$output" "${instances[$i]}";
read -p "Instance Index: " instance_index
if [[ ${instance_index} =~ ^[0-9]+$ ]] && \
[ ${instance_index} -ge 1 ] && [ ${instance_index} -le ${#instances[@]} ]; then
connection_name=$(awk '{print $5}' <<< ${instance_line})
db_type=$(awk '{print $2}' <<< ${instance_line})
if [[ ${db_type} =~ ^POSTGRES ]]; then
elif [[ ${db_type} =~ ^MYSQL ]]; then
echo "Unknown DB Type ${db_type}" && exit 1;
${CLOUD_PROXY_SQL_BIN:-cloud_sql_proxy} -instances=${connection_name}=tcp:${port}
echo "Invalid Instance Index." >&2 && exit 1;

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.