LoginSignup
0
0

gcloud コマンドに独自サブコマンドを定義する

Last updated at Posted at 2023-02-22

前書き

gcloud コマンドでよく使う長い処理を、 gcloud <独自コマンド> のワンコマンドで起動できればいいと思った。

gcloud コマンドを拡張する方法は探してもなかったので、 .bashrc を利用して拡張することにした。

.bashrc を用いて wrapper を噛ます

.bashrc に以下定義。

gcloud-wrapper () {
    if [ "$1" = "switch" ]; then
        gcloud config set project "$2"
    elif [ "$1" = "list" ]; then
        if [ "$2" = "instances" ]; then
            gcloud compute instances list
        elif [ "$2" = "ip" ]; then
            gcloud compute instances list --format="table(NAME,EXTERNAL_IP)" --filter="EXTERNAL_IP:*"
        fi
    elif [ "$1" = "start" -o "$1" = "up" ]; then
        gcloud compute instances start $2
    elif [ "$1" = "stop" ]; then
        gcloud comupte instances stop $2
    else
        gcloud "$@"
    fi
}

alias gcloud="gcloud-wrapper"

elif [ "$1" = "list" ]; then の部分を増やしていけば拡張していくことができる。

また、パターンに一致しなかった場合は gcloud コマンドが実行されるので、公式のコマンドは普通に使える。

dotfiles への組み込み

dotfiles に組み込むなら、以下のような形になる。

他の手段

こちらも便利そうだった。

gcloud 対話型シェルの使用 | Google Cloud CLI のドキュメント

0
0
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
0
0