【GCP】gcloudをzshにインストールする

半年ぶりぐらいにGCPを触ろうとgcloudコマンドを打ったのですが

$ zsh: command not found: gcloud

というエラーに遭遇しました。

途中で自分のマシンをzshに置き換えていたことを思い出し
せっかくなのでインストールメモです。

前提条件

  • zshがインストールされていること
  • .zshrcはユーザー直下に配置されていること(/Users/ユーザー名/.zshrc)

インストール

公式ドキュメントにしたがい、コマンドを実行します。

$ curl https://sdk.cloud.google.com | bash

3回ほどEnterやらを押す(この辺は任意なので各マシンの環境と相談)と
以下の様な感じで入力待ち状態になります。

$ Enter path to an rc file to update, or leave blank to use
$ [/Users/ユーザー名/.bash_profile]:

zshにしているので、以下のように入力します。

$ Enter path to an rc file to update, or leave blank to use
$ [/Users/ユーザー名/.bash_profile]: /Users/ユーザー名/.zshrc

そうすると、バックアップが取られ.zshrcファイルに追記されます。

$ Backing up [/Users/ユーザー名/.zshrc] to [/Users/ユーザー名/.zshrc.backup].
$ [/Users/ユーザー名/.zshrc] has been updated.
$ Start a new shell for the changes to take effect.

追記されたかどうか確認します。

# The next line updates PATH for the Google Cloud SDK.
source '/Users/ユーザー名/google-cloud-sdk/path.bash.inc'

# The next line enables bash completion for gcloud.
source '/Users/ユーザー名/google-cloud-sdk/completion.bash.inc'

なお、このままでは「source .zshrc」をやると

/Users/ユーザー名/google-cloud-sdk/path.bash.inc:3: = not found

となってしまいます。
なので、.zshrcに追記された記述を以下のように記述を修正します。

# The next line updates PATH for the Google Cloud SDK.
source '/Users/ユーザー名/google-cloud-sdk/path.zsh.inc'

# The next line enables bash completion for gcloud.
source '/Users/ユーザー名/google-cloud-sdk/completion.zsh.inc'

そして、「source .zshrc」をやるとエラーが出ずに適用されます。

動作確認として、GCEにアクセスしてみます。

# project名は伏せておきます。念のため。
$ gcloud compute --project "XXX" ssh --zone "asia-east1-a" "web"
[ユーザー名@web ~]$

繋げることができました。

ちょっとしたことで繋がらないと焦りますが
落ち着いて対処すれば大丈夫なことでした。

余談

gcloudはPython2系じゃないとダメっぽいです。
pyenv入れているとrbenvみたいに切り替えができるので
入れておいた方がいいです。