Google Cloud SDK のインストール/アンインストールメモ(公式バージョン)


## イントロ

[FirebaseとGoogle Cloud Platform をさわれる環境を構築する/Google Cloud Platform のCLIのインストール](https://qiita.com/masatomix/items/0ddbfacb9bc1797044a1#google-cloud-platform-%E3%81%AEcli%E3%81%AE%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%E3%83%AB) で ``gcloud`` コマンドをインストールする手順を整理したけど ``brew cask`` でやるより公式のがシンプルでよかったので、そちらの手順のメモ。。といってもほぼ公式をなぞったくらいです、、、、。


## 前提環境

```bash
$ sw_vers
ProductName:	Mac OS X
ProductVersion:	10.14.6
BuildVersion:	18G95
$
```

## インストール

https://cloud.google.com/sdk/docs/downloads-interactive?hl=ja を参考に実行していきます。


```bash

$ curl https://sdk.cloud.google.com | bash
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   443  100   443    0     0   1346      0 --:--:-- --:--:-- --:--:--  1346
Downloading Google Cloud SDK install script: https://dl.google.com/dl/cloudsdk/channels/rapid/install_google_cloud_sdk.bash
######################################################################## 100.0%
Running install script from: /var/folders/fp/ph0q_b6s64v9pmpbn8x547400000gp/T/tmp.XXXXXXXXXX.G4GMjyqO/install_google_cloud_sdk.bash
which curl
curl -# -f https://dl.google.com/dl/cloudsdk/channels/rapid/google-cloud-sdk.tar.gz
######################################################################## 100.0%

Installation directory (this will create a google-cloud-sdk subdirectory) (/Users/xxxxxx):   'インストール先の指定'

...ぶわーっとでるので省略...

/Users/xxxxxx/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)?   'とりあえずreturn'


This will install all the core command line tools necessary for working with
the Google Cloud Platform.



Your current Cloud SDK version is: 263.0.0
Installing components from version: 263.0.0

┌────────────────────────────────────────────────────────────────────────────┐
│                    These components will be installed.                     │
├─────────────────────────────────────────────────────┬────────────┬─────────┤
│                         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 (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 │
│ Default set of gcloud commands                      │            │         │
│ gcloud cli dependencies                             │ 2018.08.03 │ 1.5 MiB │
└─────────────────────────────────────────────────────┴────────────┴─────────┘

For the latest full release notes, please visit:
  https://cloud.google.com/sdk/release_notes

╔════════════════════════════════════════════════════════════╗
╠═ Creating update staging area                             ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: BigQuery Command Line Tool                   ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: BigQuery Command Line Tool (Platform Spec... ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: Cloud SDK Core Libraries (Platform Specific) ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: Cloud Storage Command Line Tool              ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: Cloud Storage Command Line Tool (Platform... ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: Default set of gcloud commands               ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: gcloud cli dependencies                      ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Creating backup and activating new installation          ═╣
╚════════════════════════════════════════════════════════════╝

Performing post processing steps...done.

Update done!



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)?   'とりあえずreturn'

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/xxxxxx/.bash_profile]:
Backing up [/Users/xxxxxx/.bash_profile] to [/Users/xxxxxx/.bash_profile.backup].
[/Users/xxxxxx/.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

```

``~/.bash_profile``が書き換えられたようなので一応確認。

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

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

$
```

パスを通す処理が追加されていますね。
つづいて、シェルの再起動を実施。

```bash
$ exec -l $SHELL
$
```

さいごに、環境の初期化をします。たとえば Firebaseなどを一緒に使ってると、該当するログインユーザ(下記でいうと``xxxx@ki-no.org``)と、プロジェクト名(``fb-samples-xxxxx``など)は決まっていたりすると思うので、それらを指定しましょう。

```bash
$ 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)?

Your browser has been opened to visit:

    https://accounts.google.com/o/oauth2/auth?code_challenge=xxx&prompt=select_account&code_challenge_method=S256&access_type=offline&redirect_uri=http%3A%2F%2Flocalhost%3A8085%2F&response_type=code&client_id=32555940559.apps.googleusercontent.com&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fappengine.admin+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcompute+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Faccounts.reauth

'ブラウザでOAuthの認証画面が上がりますので、認証・認可してください'

You are logged in as: [xxxx@ki-no.org].

Pick cloud project to use:
 [1] fb-samples-xxxxx
 [2] spring-base-xxxxx
 [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: [fb-samples-xxxxx].

Not setting default zone/region (this feature makes it easier to use
[gcloud compute] by setting an appropriate default value for the
--zone and --region flag).
See https://cloud.google.com/compute/docs/gcloud-compute section on how to set
default compute region and zone manually. If you would like [gcloud init] to be
able to do this for you the next time you run it, make sure the
Compute Engine API is enabled for your project on the
https://console.developers.google.com/apis page.

Your Google Cloud SDK is configured and ready to use!

* Commands that require authentication will use fb@ki-no.org by default
* Commands will reference project `fb-samples-xxxxx` 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
$
```

インストール完了ですね。。

## 疎通確認。

```bash
$ gcloud projects describe fb-samples-xxxxx
createTime: '2019-09-01T11:33:55.627Z'
lifecycleState: ACTIVE
name: fb-samples
parent:
  id: 'xx'
  type: organization
projectId: fb-samples-xxxxx
projectNumber: 'xx'
$
```

うん、なんか返ってきてますね！

## 疎通確認2

スケジューラを表示してみます。

```bash
$ gcloud  scheduler jobs list
ERROR: (gcloud.scheduler.jobs.list) User [xx@ki-no.org] does not have permission to access project [fb-samples-xxxxx] (or it may not exist):
 Cloud Scheduler API has not been used in project xx before or it is disabled. 
Enable it by visiting https://console.cloud.google.com/apis/api/cloudscheduler.googleapis.com/overview?project=xx then retry.
 If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.
- '@type': type.googleapis.com/google.rpc.Help
  links:
  - description: Google Cloud Console API activation
    url: https://console.cloud.google.com/apis/api/cloudscheduler.googleapis.com/overview?project=xx
$
```

なんか怒られました。上記URLにアクセスすると、、、あー、スケジューラは課金が必要ぽいですね。

![sche.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/73777/fb3440a7-b874-60d7-08ef-f2afcb3cd5af.png)

というわけで必要に応じて有効化してください。

そのうえで、もう一度やってみると、

```bash
$ gcloud  scheduler jobs list
Listed 0 items.
$
```

うん、スケジュール設定してないのでゼロ件とでました。OKですね。




## アンインストール

もっかい初めからやり直すとか、全部消したい場合。コレも https://cloud.google.com/sdk/docs/uninstall-cloud-sdk?hl=ja を参考に。

```bash
$ gcloud info --format='value(installation.sdk_root)'
/Users/xxxxxx/google-cloud-sdk
$
```

```bash
$ gcloud info --format='value(config.paths.global_config_dir)'
/Users/xxxxxx/.config/gcloud
$
```

これらでインストールディレクトリと、環境設定ディレクトリが表示されるので、それらを削除するだけでOK.

```bash
$ rm -fr /Users/xxxxxx/google-cloud-sdk
$ rm -fr /Users/xxxxxx/.config/gcloud
$
```


おつかれさまでしたー。

## 関連リンク

- [公式ドキュメント](https://cloud.google.com/sdk/docs/initializing?hl=ja) この辺からをとっかかりにして、コマンドを学べそう
- [インストール](https://cloud.google.com/sdk/docs/downloads-interactive?hl=ja)
- [アンインストール](https://cloud.google.com/sdk/docs/uninstall-cloud-sdk?hl=ja)