コマンドラインでGoogleのインフラを操作する - Google Cloud SDKのインストールからインスタンス起動・停止まで

[Google Cloud Platform](https://cloud.google.com/)をご存知でしょうか？
私はAWSは知っていましたが、[Google Cloud Platform](https://cloud.google.com/)は聞いたことある程度でした。
[公式サイト](https://cloud.google.com/)に「Google が、Google のサービスのために開発した基盤を、デベロッパーやビジネスでも利用可能に。」とあるように、検索エンジンなどGoogleがGoogleのサービスで使っているインフラを自分たちのサービスのインフラとして活用できます。

この記事はGoogle Cloud Platform でcommand-line toolの導入からインスタンスの生成、ログイン、停止までをやった際の記録です。20分程度で完了できる見込みです。
Google Cloud Platfromには60日間の無料枠があるのでぜひお試しください！


# 前提条件
GooglePlatformへのプロジェクト作成まではできているものとします。
持っていない方はこちらの記事の「Webコンソールからアカウントをセットアップしてプロジェクト作成」までなどを参考にプロジェクトの作成までをやってみてください。＞ http://heartbeats.jp/hbblog/2014/06/google-cloud-platform.html
操作ログの出力は一部伏せ字にしています。手順の部分では、操作ログの下に説明を書いています。

# 実行環境

* OS: CentOS 7
* python: 2.7.5
    * Google Cloud SDKのSystem RequirementsにPython 2.7系が指定されています
    * 参照: https://cloud.google.com/sdk/
* Google Cloud SDK: 0.9.80

```shell-session

[cloudy@sky ~]$ cat /etc/redhat-release
CentOS Linux release 7.1.1503 (Core)
[cloudy@sky ~]$ python --version
Python 2.7.5
[cloudy@sky ~]$ gcloud --version
Google Cloud SDK 0.9.80

bq 2.0.18
bq-nix 2.0.18
core 2015.09.25
core-nix 2015.09.03
gcloud 2015.09.25
gsutil 4.15
gsutil-nix 4.14


```

それではまずはインストールから。

# command-line toolインストール

公式サイトに書いている通りにすればできました。＞ https://cloud.google.com/sdk/#nix
MinimalなISOを元にインストールしたCentOS 7.1にはpython2.7.5が入っているので事前準備も不要でした。
CentOS 6.Xにはpython2.7.Xは入っていなかったので別途インストールする必要があります。

## 詳細手順

対話形式のスクリプトが実行されます。対話形式はちょっとわくわくします。

```shell-session
[cloudy@sky ~]$ curl https://sdk.cloud.google.com | bash
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
105   421    0   421    0     0     41      0 --:--:--  0:00:10 --:--:--    81
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: /tmp/tmp.3MoQfnXPPs/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) (/home/znc):
mkdir -p /home/znc
tar -C /home/znc -xvf /tmp/tmp.EbkSyfxzsG/google-cloud-sdk.tar.gz
google-cloud-sdk/
google-cloud-sdk/lib/
… 中略 …
google-cloud-sdk/.install/core.manifest
google-cloud-sdk/.install/.download/

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

To help improve the quality of this product, we collect anonymized data on how
the SDK is used. 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 --scope=user disable_usage_reporting true

Do you want to help improve the Google Cloud SDK (Y/n)?  n


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



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

+----------------------------------------------------------------------------+
|                    These components will be installed.                     |
+-----------------------------------------------------+------------+---------+
|                         Name                        |  Version   |   Size  |
+-----------------------------------------------------+------------+---------+
| BigQuery Command Line Tool                          |     2.0.18 | < 1 MiB |
| BigQuery Command Line Tool (Platform Specific)      |     2.0.18 | < 1 MiB |
| Cloud SDK Core Libraries (Platform Specific)        | 2015.09.03 | < 1 MiB |
| Cloud Storage Command Line Tool                     |       4.15 | 2.7 MiB |
| Cloud Storage Command Line Tool (Platform Specific) |       4.14 | < 1 MiB |
| Default set of gcloud commands                      | 2015.09.25 | < 1 MiB |
+-----------------------------------------------------+------------+---------+

For the latest full release notes, please visit:
  https://dl.google.com/dl/cloudsdk/channels/rapid/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               =#
#============================================================#
#= Creating backup and activating new installation          =#
#============================================================#

Update done!


Modify profile to update your $PATH and enable shell command
completion? (Y/n)?  Y

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
[/home/znc/.bashrc]:  
Backing up [/home/znc/.bashrc] to [/home/znc/.bashrc.backup].
[/home/znc/.bashrc] has been updated.
Start a new shell for the changes to take effect.


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

```

### インストールスクリプト実行中に入力をもとめられること
* GoogleさんにGCPの改善のために匿名の情報を提供するか
    * ```Do you want to help improve the Google Cloud SDK (Y/n)?```のところ
    * 送ることを厭わない場合は```Y```を入力してEnter（私は疑い深いので```n```の選択をしました）
* PATHを更新していいか
    * ```Modify profile to update your $PATH and enable shell command completion?```のところ
    * 更新してもいい場合は```Y```を入力してEnter（私は複数バージョンを入れたりはしないので```Y```を選択しました）
* シェルのリソースファイルの場所
    * ```Enter a path to an rc file to update, or leave blank to use [/home/cloudy/.bashrc]```のところ
    * そこでOKなら```Y```を入力してEnter
    * バックアップファイルが作られてから更新されます

## shellの再起動

```shell-session

[cloudy@sky ~]$ exec -l $SHELL
```


## 初期設定

```gcloud init```を実行すると初期設定をしてくれます。

### 詳細手順

これも対話形式です。

```shell-session

[znc@cloudy ~]$ gcloud init
Welcome! This command will take you through the configuration of gcloud.

Your current configuration has been set to: [default]

To continue, you must login. Would you like to login (Y/n)?  Y

Go to the following link in your browser:

    https://accounts.google.com/o/oauth2/auth?redirect_uri=urn…中略…offline # <-このURLをコピーしてブラウザで開く


Enter verification code: xxxxSECRETxxxx
You are now logged in as: [xxxxxxx@gmail.com]

Enter project id you would like to use:  xxxxx-xxxxx-xxxxx     
[config set project xxxxx-xxxxx-xxxxx ] has failed
You can use [gcloud config] to change more gcloud settings.

Your current configuration is: [default]

[core]
account = xxxxxxx@gmail.com
disable_usage_reporting = True
[meta]
active_config = default
ERROR: (gcloud.init) Failed command: [config set project xxxxx-xxxxx-xxxxx ] with exit code [1]



[cloudy@sky ~]$ gcloud init
Welcome! This command will take you through the configuration of gcloud.

Settings from you current configuration [default] are:
[core]
account = xxxxxxx@gmail.com
disable_usage_reporting = True
[meta]
active_config = default

Pick configuration to use:
 [1] Re-initialize this configuration [default] with new settings
 [2] Create a new configuration
Please enter your numeric choice:  1

Your current configuration has been set to: [default]

Pick credentials to use:
 [1] xxxxxxx@gmail.com
 [2] Login with new credentials
Please enter your numeric choice:  1

You are now logged in as: [xxxxxxx@gmail.com]

Enter project id you would like to use:  xxxxx-xxxxx-xxxxx
Your current project has been set to: [xxxxx-xxxxx-xxxxx].

Your project default compute zone has been set to [us-central1-f].
You can change it by running [gcloud config set compute/zone NAME].

Your project default compute region has been set to [us-central1].
You can change it by running [gcloud config set compute/region NAME].


gcloud has now been configured!
You can use [gcloud config] to change more gcloud settings.

Your current configuration is: [default]

[compute]
region = us-central1
zone = us-central1-f
[core]
account = xxxxxxx@gmail.com
disable_usage_reporting = True
project = xxxxx-xxxxx-xxxxx
[meta]
active_config = default
```



### ```gcloud init```実行中に入力をもとめられること

#### ログインするか
* ```To continue, you must login. Would you like to login (Y/n)?```のところ
* ```Y```を入力して表示されたURLをブラウザで開く
    * ログインに使いたいアカウントをクリックする
        * <img src="https://qiita-image-store.s3.amazonaws.com/0/19495/0578ef2e-2daa-7a66-63a1-e7c0876548e3.png" width="300px">
    * "Allow"をクリックする
        * <img src="https://qiita-image-store.s3.amazonaws.com/0/19495/01e2d047-9eb8-d259-0ed4-f47dd7e4799e.png" width="300px">
    * 表示されたコードをコピーする
        * <img src="https://qiita-image-store.s3.amazonaws.com/0/19495/3ec4bf9c-e0cb-6a47-22ed-1b36e9ee1d7c.png" width="300px">

#### 確認コードの入力
* ```Enter verification code: ```のところ
* さっきコピーした確認コードを貼り付けてEnter

（不要な空白文字が入っていると```ERROR```になるので要注意です。私は入っていたため失敗してしまったので再度initを実行しました。）

#### インストールできたか確認

```shell-session

[cloudy@sky ~]$ gcloud components list

Your current Cloud SDK version is: 0.9.80
The latest available version is: 0.9.80

+--------------------------------------------------------------------------------------------+
|                                         Components                                         |
+---------------+---------------------------------------------+-------------------+----------+
|     Status    |                     Name                    |         ID        |   Size   |
+---------------+---------------------------------------------+-------------------+----------+
| Not Installed | App Engine Command Line Interface (Preview) | app               |  < 1 MiB |
| Not Installed | gcloud Alpha Commands                       | alpha             |  < 1 MiB |
| Not Installed | gcloud app Java Extensions                  | app-engine-java   | 96.5 MiB |
| Not Installed | gcloud app Python Extensions                | app-engine-python |  7.1 MiB |
| Not Installed | kubectl                                     | kubectl           |          |
| Installed     | BigQuery Command Line Tool                  | bq                |  < 1 MiB |
| Installed     | Cloud SDK Core Libraries                    | core              |  2.1 MiB |
| Installed     | Cloud Storage Command Line Tool             | gsutil            |  2.7 MiB |
| Installed     | Default set of gcloud commands              | gcloud            |  < 1 MiB |
| Installed     | gcloud Beta Commands                        | beta              |  < 1 MiB |
+---------------+---------------------------------------------+-------------------+----------+

 
To install new components or update existing ones, run:
 $ gcloud components update COMPONENT_ID
```

できました！
数日後更新してみたが、何もないもよう。

```shell-session

[cloudy@sky ~]$ gcloud components update

All components are up to date.
```

# インスタンス作成

## リージョンを確認

まず、インスタンス作成のコマンド引数に渡せるリージョン名の一覧を確認します。
確認をするのに必要なcommand-line toolのコンポーネントがインストールされていないので、インストールを許可します。

```shell-session

[cloudy@sky ~]$ gcloud beta compute zones list
You do not currently have this command group installed.  Using it
requires the installation of components: [beta]


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

+---------------------------------------------+
|     These components will be installed.     |
+----------------------+------------+---------+
|         Name         |  Version   |   Size  |
+----------------------+------------+---------+
| gcloud Beta Commands | 2015.08.17 | < 1 MiB |
+----------------------+------------+---------+

For the latest full release notes, please visit:
  https://dl.google.com/dl/cloudsdk/channels/rapid/RELEASE_NOTES
Do you want to continue (Y/n)?  Y

#============================================================#
#= Creating update staging area                             =#
#============================================================#
#= Installing: gcloud Beta Commands                         =#
#============================================================#
#= Creating backup and activating new installation          =#
#============================================================#

Update done!

Restarting command:
  $ gcloud beta compute zones list

NAME           REGION       STATUS NEXT_MAINTENANCE TURNDOWN_DATE
asia-east1-a   asia-east1   UP
asia-east1-b   asia-east1   UP
asia-east1-c   asia-east1   UP
europe-west1-b europe-west1 UP
europe-west1-c europe-west1 UP
europe-west1-d europe-west1 UP
us-central1-a  us-central1  UP
us-central1-b  us-central1  UP
us-central1-c  us-central1  UP
us-central1-f  us-central1  UP
us-east1-d     us-east1     UP
us-east1-c     us-east1     UP
us-east1-b     us-east1     UP
[cloudy@sky ~]$ gcloud beta compute zones list
NAME           REGION       STATUS NEXT_MAINTENANCE TURNDOWN_DATE
asia-east1-a   asia-east1   UP
asia-east1-b   asia-east1   UP
asia-east1-c   asia-east1   UP
europe-west1-b europe-west1 UP
europe-west1-c europe-west1 UP
europe-west1-d europe-west1 UP
us-central1-a  us-central1  UP
us-central1-b  us-central1  UP
us-central1-c  us-central1  UP
us-central1-f  us-central1  UP
us-east1-d     us-east1     UP
us-east1-c     us-east1     UP
us-east1-b     us-east1     UP
```

## 作成コマンド実行
10秒くらいで作成されました。

```shell-session

[cloudy@sky ~]$ gcloud compute instances create my-first-instance --zone asia-east1-a
Created [https://www.googleapis.com/compute/v1/projects/eighth-study-98508/zones/asia-east1-a/instances/my-first-instance].
NAME              ZONE         MACHINE_TYPE  PREEMPTIBLE INTERNAL_IP  EXTERNAL_IP     STATUS
my-first-instance asia-east1-a n1-standard-1             xx.xx.xx.xx  xxx.xxx.xxx.xxx RUNNING
```

* インスタンスの情報取得

```shell-session

[cloudy@sky ~]$ gcloud compute instances describe my-first-instance --zone asia-east1-a
canIpForward: false
cpuPlatform: Intel Ivy Bridge
creationTimestamp: '2015-10-01T19:58:42.445-07:00'
disks:
- autoDelete: true
  boot: true
  deviceName: persistent-disk-0
  index: 0
  interface: SCSI
  kind: compute#attachedDisk
  mode: READ_WRITE
  source: https://www.googleapis.com/compute/v1/projects/xxxxx-xxxxx-xxxxx/zones/asia-east1-a/disks/my-first-instance
  type: PERSISTENT
id: '11111111111111111111'
kind: compute#instance
machineType: https://www.googleapis.com/compute/v1/projects/xxxxx-xxxxx-xxxxx/zones/asia-east1-a/machineTypes/n1-standard-1
metadata:
  fingerprint: AaAaAaAaAaAa
  kind: compute#metadata
name: my-first-instance
networkInterfaces:
- accessConfigs:
  - kind: compute#accessConfig
    name: external-nat
    natIP: xxx.xxx.xxx.xxx
    type: ONE_TO_ONE_NAT
  name: nic0
  network: https://www.googleapis.com/compute/v1/projects/xxxxx-xxxxx-xxxxx/global/networks/default
  networkIP: yyy.yyy.yyy.yyy
scheduling:
  automaticRestart: true
  onHostMaintenance: MIGRATE
  preemptible: false
selfLink: https://www.googleapis.com/compute/v1/projects/xxxxx-xxxxx-xxxxx/zones/asia-east1-a/instances/my-first-instance
serviceAccounts:
- email: 2222222222222-compute@developer.gserviceaccount.com
  scopes:
  - https://www.googleapis.com/auth/cloud.useraccounts.readonly
  - https://www.googleapis.com/auth/devstorage.read_only
  - https://www.googleapis.com/auth/logging.write
status: RUNNING
tags:
  fingerprint: BbBbBbBbBbBb
zone: https://www.googleapis.com/compute/v1/projects/xxxxx-xxxxx-xxxxx/zones/asia-east1-a
```

* 起動しているか確認

```shell-session

[cloudy@sky ~]$ gcloud compute instances list my-first-instance
NAME              ZONE         MACHINE_TYPE  PREEMPTIBLE INTERNAL_IP EXTERNAL_IP STATUS
my-first-instance asia-east1-a n1-standard-1             xx.xx.xx.xx             RUNNING
```

## ログインする
command-line toolでできました。新鮮。AWS CLIにはなかった気がする(あるのかな…？)。

```shell-session
[cloudy@sky ~]$ gcloud compute --project "xxxxx-xxxxx-xxxxx" ssh --zone "asia-east1-a" "my-first-instance"
Warning: Permanently added 'xxx.xxx.xxx.xxx' (ECDSA) to the list of known hosts.
Linux my-first-instance 3.16.0-0.bpo.4-amd64 #1 SMP Debian 3.16.7-ckt11-1+deb8u3~bpo70+1 (2015-08-08) x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Fri Oct  2 13:31:08 2015 from sky
[ec2-user@my-first-instance~$ exit
logout
Connection to xxx.xxx.xxx.xxx closed.
```

# インスタンス停止

```shell-session

[cloudy@sky ~]$ gcloud compute instances stop my-first-instance --zone asia-east1-a
Updated [https://www.googleapis.com/compute/v1/projects/eighth-study-98508/zones/asia-east1-a/instances/my-first-instance].
```

* 停止したことの確認

```STATUS``` が ```TERMINATED``` だと停止できています。
AWSとは違い```TERMINATED```のステータスはインスタンスの削除ではありません。

```shell-session
[cloudy@sky ~]$ gcloud compute instances list my-first-instance
NAME              ZONE         MACHINE_TYPE  PREEMPTIBLE INTERNAL_IP EXTERNAL_IP STATUS
my-first-instance asia-east1-a n1-standard-1             xx.xx.xx.xx             TERMINATED
```

# 終わりに

最後まで読んでいただきありがとうございました！
```gcloud compute instances list```の結果が```RUNNING```なものをgrepしてircとかに流すことで、シャットダウンし忘れのインスタンスに気付くきっかけにはなりそうです。
ですが、CLIだけで起動したままのインスタンスをリストアップして自動で停止したりは、別の手段も使わないと少し厳しそうな印象です。
SDKを活用すればできるのか試してみたくなりました！

<br>

---

参考：

* https://cloud.google.com/sdk/#nix
* https://cloud.google.com/sdk/cloudplatform
* https://cloud.google.com/sdk/gcloud/reference/beta/compute/zones/list
* https://cloud.google.com/sdk/gcloud/reference/compute/instances/create
* https://cloud.google.com/sdk/gcloud/reference/compute/instances/stop
* http://qiita.com/yuko/items/1c4ee5b081c5b6a3ac8a
    * 参考にさせていただきました。ありがとうございます。