Skip to content

Instantly share code, notes, and snippets.

@vinayan3
Created August 25, 2019 02:11
Show Gist options
  • Save vinayan3/ee990114bb3da38250ca172a92a324e2 to your computer and use it in GitHub Desktop.
Save vinayan3/ee990114bb3da38250ca172a92a324e2 to your computer and use it in GitHub Desktop.
Google Cloud SQL Proxy Helper
#!/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
@vinayan3
Copy link
Author

This helper to interactive select which database instance to proxy over TCP expects cloud_sql_proxy to either be on the PATH or specified in an environment variable CLOUD_PROXY_SQL_BIN.

Checkout the Cloud SQL Proxy page. for more information.

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