LoginSignup
3
2

More than 3 years have passed since last update.

内部で一時的に cloud_sql_proxy を立ち上げてコマンドを実行できるラッパースクリプト

Last updated at Posted at 2019-11-19

内部で一時的に cloud_sql_proxy を立ち上げて mysql コマンドを実行したらすぐ落とすラッパースクリプトを書いた

背景

gcloud sql connect でも Cloud SQL インスタンスには接続できるが、接続されるまで 1min ~ 5min ほどかかる。cloud_sql_proxy コマンドを使ってみたらこっちの方が早かった。

すぐ立ち上がるので、必要なときに立ち上げて mysql コマンドを打って、終わったら終了するコマンドがあればそっちの方が便利そうと思った次第

スクリプト

cloud_sql_proxy_wrapper.sh
#!/usr/bin/env bash
# USAGE
#
# ./cloud_sql_proxy_wrapper.sh [cloud_sql_proxy options] -- [command]

CLOUD_SQL_PROXY_OPTS=()
ARGS=()
for arg in "$@"; do
    case "$arg" in
        '--' )
            shift
            ARGS+=( "$@" )
            break
            ;;
        * )
            CLOUD_SQL_PROXY_OPTS+=( "$1" ); shift
            ;;
    esac
done

echo "cloud_sql_proxy ${CLOUD_SQL_PROXY_OPTS[@]}"
cloud_sql_proxy ${CLOUD_SQL_PROXY_OPTS[@]} &
pid=$!
trap "kill $pid" EXIT
sleep 3

echo "${ARGS[@]}"
${ARGS[@]}

使い方

./cloud_sql_proxy_wrapper.sh [cloud_sql_proxyのオプション] -- [mysqlコマンド]

標準出力は mysql コマンドしか受け取らないのでパイプも渡せる

echo 'select 1' | ./cloud_sql_proxy_wrapper.sh [cloud_sql_proxyのオプション] -- [mysqlコマンド]
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2