Google Cloud SDK をMac OS X環境にインストール

2019.09.10

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

最近、AWSと合わせてGCPにも触れる機会が増えてきました。とは行っても弊部署内(データアナリティクス事業本部)でのお話なのですが、プラットフォームが変わってくるとサービス1つ、機能1つ、コマンド1つ取ってみても勝手が違うところが出てきますので実際に少しずつ触ってみないと分かりません。個人的にはGCPは全く触れていませんでしたが、違いを把握して手順を身に付けるための備忘録として基本的なところからインプット&アウトプットして行こうと思います。

まずはGoogle Cloud Platform でのメインCLIツールとなるgcloud コマンドライン ツールの導入からやってみたいと思います。導入出来る環境は幾つか用意されており、当エントリではMac OSXへのインストール手順について実際にやった手順を紹介します。

Google Cloud SDKインストール手順 in Mac OSX:実践

導入は以下の公式ドキュメントに沿って行います。

Cloud SDK導入にはPython 2(Python2.7.9以降)が必要です。手元の環境に条件を満たすバージョンのPythonが導入されていることを確認(無ければ導入)してください。

$ python -V
Python 2.7.15

また、GCPアカウントが既に開設済であり、任意のプロジェクトが作成されている、という前提で進めます。

インストーラを公式ページリンクからダウンロード&解凍。今回はユーザー配下にgcpというフォルダを作成し、その配下に導入する形で進めてみました。

$ pwd
/Users/xxxx.yyyyyyyyyy/gcp
$ ls
google-cloud-sdk-245.0.0-darwin-x86_64.tar.gz
$ tar xvf google-cloud-sdk-245.0.0-darwin-x86_64.tar.gz

中に含まれているインストールスクリプト(./google-cloud-sdk/install.sh)を実行。途中幾つかYes/Noを聞かれるので、回答しつつ導入を進めてください。終盤には必要な「環境変数の指定」に関する設定の記述先の追記も行われています。

$ ./google-cloud-sdk/install.sh 
Welcome to the Google Cloud SDK!

To help improve the quality of this product, we collect anonymized usage data
and anonymized stacktraces when crashes are encountered; additional information
is available at <https://cloud.google.com/sdk/usage-statistics>. You may choose
to opt out of this collection now (by choosing 'N' at the below prompt), or at
any time in the future by running the following command:

    gcloud config set disable_usage_reporting true

Do you want to help improve the Google Cloud SDK (Y/n)?  Y
(※Google Cloud SDKの改善に協力したいですか? -> Yを選択、[Enter]押下)

Your current Cloud SDK version is: 245.0.0
The latest available version is: 256.0.0

┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                                   Components                                                  │
├──────────────────┬──────────────────────────────────────────────────────┬──────────────────────────┬──────────┤
│      Status      │                         Name                         │            ID            │   Size   │
├──────────────────┼──────────────────────────────────────────────────────┼──────────────────────────┼──────────┤
│ Update Available │ BigQuery Command Line Tool                           │ bq                       │  < 1 MiB │
│ Update Available │ Cloud SDK Core Libraries                             │ core                     │ 11.3 MiB │
│ Update Available │ Cloud Storage Command Line Tool                      │ gsutil                   │  3.6 MiB │
│ Not Installed    │ App Engine Go Extensions                             │ app-engine-go            │ 56.4 MiB │
│ Not Installed    │ Cloud Bigtable Command Line Tool                     │ cbt                      │  7.3 MiB │
│ Not Installed    │ Cloud Bigtable Emulator                              │ bigtable                 │  6.6 MiB │
│ Not Installed    │ Cloud Datalab Command Line Tool                      │ datalab                  │  < 1 MiB │
│ Not Installed    │ Cloud Datastore Emulator                             │ cloud-datastore-emulator │ 18.4 MiB │
│ Not Installed    │ Cloud Datastore Emulator (Legacy)                    │ gcd-emulator             │ 38.1 MiB │
│ Not Installed    │ Cloud Firestore Emulator                             │ cloud-firestore-emulator │ 35.9 MiB │
│ Not Installed    │ Cloud Pub/Sub Emulator                               │ pubsub-emulator          │ 34.8 MiB │
│ Not Installed    │ Cloud SQL Proxy                                      │ cloud_sql_proxy          │  3.7 MiB │
│ Not Installed    │ Emulator Reverse Proxy                               │ emulator-reverse-proxy   │ 14.5 MiB │
│ Not Installed    │ Google Cloud Build Local Builder                     │ cloud-build-local        │  5.9 MiB │
│ Not Installed    │ Google Container Registry's Docker credential helper │ docker-credential-gcr    │  1.8 MiB │
│ Not Installed    │ gcloud Alpha Commands                                │ alpha                    │  < 1 MiB │
│ Not Installed    │ gcloud Beta Commands                                 │ beta                     │  < 1 MiB │
│ Not Installed    │ gcloud app Java Extensions                           │ app-engine-java          │ 85.9 MiB │
│ Not Installed    │ gcloud app PHP Extensions                            │ app-engine-php           │ 21.9 MiB │
│ Not Installed    │ gcloud app Python Extensions                         │ app-engine-python        │  6.0 MiB │
│ Not Installed    │ gcloud app Python Extensions (Extra Libraries)       │ app-engine-python-extras │ 28.5 MiB │
│ Not Installed    │ kubectl                                              │ kubectl                  │  < 1 MiB │
└──────────────────┴──────────────────────────────────────────────────────┴──────────────────────────┴──────────┘
To install or remove components at your current SDK version [245.0.0], run:
  $ gcloud components install COMPONENT_ID
  $ gcloud components remove COMPONENT_ID

To update your SDK installation to the latest version [256.0.0], run:
  $ gcloud components update



To take a quick anonymous survey, run:
  $ gcloud alpha survey


Modify profile to update your $PATH and enable shell command 
completion?

Do you want to continue (Y/n)?  Y
(※続行しますか? -> Yを選択、[Enter]を押下)

The Google Cloud SDK installer will now prompt you to update an rc 
file to bring the Google Cloud CLIs into your environment.

Enter a path to an rc file to update, or leave blank to use 
[/Users/xxxxx.yyyyyyyy/.bash_profile]:  
(※パスを通してコマンド実行を有効にする設定:ここはそのまま[Enter]押下)
Backing up [/Users/xxxxx.yyyyyyyy/.bash_profile] to [/Users/xxxxx.yyyyyyyy/.bash_profile.backup].
[/Users/xxxxx.yyyyyyyy/.bash_profile] has been updated.

==> Start a new shell for the changes to take effect.


For more information on how to get started, please visit:
  https://cloud.google.com/sdk/docs/quickstarts

$

上記手順で追記された内容を確認してみます。

$ cat /Users/xxxxx.yyyyyyyy/.bash_profile
  :
  :
# The next line updates PATH for the Google Cloud SDK.
if [ -f '/Users/xxxxx.yyyyyyyy/gcp/google-cloud-sdk/path.bash.inc' ]; then . '/Users/xxxxx.yyyyyyyy/gcp/google-cloud-sdk/path.bash.inc'; fi

# The next line enables shell command completion for gcloud.
if [ -f '/Users/xxxxx.yyyyyyyy/gcp/google-cloud-sdk/completion.bash.inc' ]; then . '/Users/xxxxx.yyyyyyyy/gcp/google-cloud-sdk/completion.bash.inc'; fi

$

gcloud initコマンド を実行して Cloud SDKの初期化を実施。途中、利用したいプロジェクト名を聞かれるので対応する番号を入力して[Enter]を押下します。途中、認証のためにログインを促されるので合わせて実施します。

$ ./google-cloud-sdk/bin/gcloud init
Welcome! This command will take you through the configuration of gcloud.

Your current configuration has been set to: [default]

You can skip diagnostics next time by using the following flag:
  gcloud init --skip-diagnostics

Network diagnostic detects and fixes local network connection issues.
Checking network connection...done.                                                                                                        
Reachability Check passed.
Network diagnostic passed (1/1 checks passed).

You must log in to continue. Would you like to log in (Y/n)?  Y
(※ログイン処理実行)

Your browser has been opened to visit:

    https://accounts.google.com/o/oauth2/auth?redirect_uri=(以下略)

ここで一旦、ブラウザにフォーカスが移りログインを促されるので実施します。また、アカウント選択等も対応するものを選択して進めてください。

画面操作が完了すると、利用するプロジェクトの選択を促されます。選択したプロジェクトやその他情報が出力されるとコマンドのインストールは完了です。

Updates are available for some Cloud SDK components.  To install them,
please run:
  $ gcloud components update

You are logged in as: [GCPにアクセスしているGMailアカウント].

Pick cloud project to use: 
 [1] oo-xxxxx-yyyyyyyy
 [2] tokyo-xxxxxxx-00000000
 [3] Create a new project
Please enter numeric choice or text value (must exactly match list 
item):  1

Your current project has been set to: [oo-xxxxx-yyyyyyyy].

Your project default Compute Engine zone has been set to [asia-northeast1-b].
You can change it by running [gcloud config set compute/zone NAME].

Your project default Compute Engine region has been set to [asia-northeast1].
You can change it by running [gcloud config set compute/region NAME].

Created a default .boto configuration file at [/Users/xxxxxx.yyyyyyy/.boto]. See this file and
[https://cloud.google.com/storage/docs/gsutil/commands/config] for more
information about configuring Google Cloud Storage.
Your Google Cloud SDK is configured and ready to use!

* Commands that require authentication will use (GCPにアクセスしているGMailアカウント) by default
* Commands will reference project `oo-xxxxx-yyyyyyyy` by default
* Compute Engine commands will use region `asia-northeast1` by default
* Compute Engine commands will use zone `asia-northeast1-b` by default

Run `gcloud help config` to learn how to change individual settings

This gcloud configuration is called [default]. You can create additional configurations if you work with multiple accounts and/or projects.
Run `gcloud topic configurations` to learn more.

Some things to try next:

* Run `gcloud --help` to see the Cloud Platform services you can interact with. And run `gcloud help COMMAND` to get help on any gcloud command.
* Run `gcloud topic --help` to learn about advanced features of the SDK like arg files and output formatting
$

コマンドラインツールのバージョン確認はgcloud versionで行います。

$ gcloud version 
Google Cloud SDK 245.0.0
bq 2.0.43
core 2019.05.03
gsutil 4.38
Updates are available for some Cloud SDK components.  To install them,
please run:
  $ gcloud components update

また、コマンドラインツールのアップデートはgcloud components updateで行います。コマンドを実行するとアップデート対象となるコンポーネントの情報やバージョン毎のリリースノート情報がザーッと出力されます。文字情報としてこのタイミングで確認確認出来るのは便利ですね。

$ gcloud components update

Your current Cloud SDK version is: 245.0.0
You will be upgraded to version: 260.0.0

┌─────────────────────────────────────────────────────────────────────────────┐
│                      These components will be updated.                      │
├─────────────────────────────────────────────────────┬────────────┬──────────┤
│                         Name                        │  Version   │   Size   │
├─────────────────────────────────────────────────────┼────────────┼──────────┤
│ BigQuery Command Line Tool                          │     2.0.47 │  < 1 MiB │
│ BigQuery Command Line Tool (Platform Specific)      │     2.0.46 │  < 1 MiB │
│ Cloud SDK Core Libraries                            │ 2019.08.23 │ 11.4 MiB │
│ Cloud SDK Core Libraries (Platform Specific)        │ 2019.08.16 │  < 1 MiB │
│ Cloud Storage Command Line Tool                     │       4.42 │  3.6 MiB │
│ Cloud Storage Command Line Tool (Platform Specific) │       4.42 │  < 1 MiB │
│ gcloud cli dependencies                             │ 2019.08.16 │  3.3 MiB │
└─────────────────────────────────────────────────────┴────────────┴──────────┘

The following release notes are new in this upgrade.
Please read carefully for information about new features, breaking changes,
and bugs fixed.  The latest full release notes can be viewed at:
  https://cloud.google.com/sdk/release_notes

260.0.0 (2019-08-27)
  Breaking Changes
      ▪ **(Cloud Dataproc)** Modified --region flag to be mandatory.
        ◆ To use Cloud Dataproc commands, pass the --region flag on every
          invocation, or set the dataproc/region configuration variable via
          gcloud config set dataproc/region.
        ◆ For gcloud beta dataproc commands, this flag/config value is
          required.
        ◆ For gcloud dataproc commands, the default will remain global until
          January 2020.
      ▪ **(Cloud Run)** Removed --[no-]allow-unauthenticated flag from gcloud
        beta run services update. Use gcloud beta run services
        add-iam-policy-binding and gcloud beta run services
        remove-iam-policy-binding commands to modify the policies of an
        existing service.
:
:
:

途中、導入を行うか否かを聞かれるので承認(Yを選択&Enter押下)でアップデートを実施。

Do you want to continue (Y/n)?  Y

╔════════════════════════════════════════════════════════════╗
╠═ Creating update staging area                             ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Uninstalling: Cloud SDK Core Libraries                   ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: Cloud SDK Core Libraries                     ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Creating backup and activating new installation          ═╣
╚════════════════════════════════════════════════════════════╝

Performing post processing steps...done.                                                                                                   

Update done!

To revert your SDK to the previously installed version, you may run:
  $ gcloud components update --version 260.0.0

gcloudの後にtabコマンドで補完を効かせてみると、以下のように利用可能なオプションが一覧で表示されます。この辺りはAWS CLIと同じですね。

$ gcloud <tab>
access-context-manager   composer                 docker                   init                     resource-manager 
ai-platform              compute                  domains                  iot                      services 
alpha                    config                   endpoints                kms                      source 
app                      container                feedback                 logging                  spanner 
asset                    dataflow                 filestore                ml                       sql 
auth                     dataproc                 firebase                 ml-engine                topic 
beta                     datastore                functions                organizations            version 
bigtable                 debug                    help                     projects                 
builds                   deployment-manager       iam                      pubsub                   
components               dns                      info                     redis

まとめ

というわけでGoogle Cloud SDKのインストール手順(Mac OSX編)のご紹介でした。この様な形で他のOS/手法についても幾つか実践してみたいと思います。