LoginSignup
11

More than 5 years have passed since last update.

Google Compute Engineへのsshをpecoで効率化する

Last updated at Posted at 2015-09-02

Google Compute Engineへのsshをpecoで効率化する

概要

GCP(Google Cloud Platform)上にあるGCEへsshする際、Developer Consoleからsshしたりsshコマンドをコピペしたりの運用を不便に感じていました。もっと効率よく出来ないか試してみました。

前提

  • pecoがインストールされている
    brew install pecoもしくはbrew tap peco/peco && brew install peco
  • GCPに1つ以上GCEインスタンスが作られている
  • gcloudコマンドが実行できる状態になっている
    https://cloud.google.com/sdk/gcloud/

実施

GCP上にあがっているインスタンス情報を取得

$ gcloud compute instances list | awk "NR>1 {print \$1,\$2}" > ~/.ssh/gce_hosts

無事取れました。リージョン指定できるようにリージョンも入れてます。

$ cat ~/.ssh/gce_hosts
dev-build-0 asia-east1-a
dev-cache-0 asia-east1-a
dev-db-0 asia-east1-a
dev-redis-mkhz asia-east1-a
dev-web-0 asia-east1-a
dev-web-autoscaler-zg1o asia-east1-a

先ほど作成したgce_hostsとpecoを使ってsshコマンドを作成。

$ gcloud compute ssh --zone $(cat ~/.ssh/gce_hosts | peco | awk "{print \$2,\$1}")

おお、これは便利!
Screen Shot 2015-09-02 at 19.01.28.png

user ~]$ gcloud compute ssh --zone $(cat ~/.ssh/gce_hosts | peco | awk "{print \$2,\$1}")
Warning: Permanently added '0.0.0.0' (RSA) to the list of known hosts.
[user@dev-web-0 ~]$

ちなみに

.bashrcにalias貼っておくとさらに便利。

alias reload-gcessh='gcloud compute instances list | awk "NR>1 {print \$1,\$2}" > ~/.ssh/gce_hosts'
alias peco-gcessh='gcloud compute ssh --zone $(cat ~/.ssh/gce_hosts | peco | awk "{print \$2,\$1}")'

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
11