Google Compute Engine 入門 (3)

今天要教大家用 command 的方式操作 GCE,只要記一些指令就能讓操作加速,非常方便喔。


1. 安裝 Cloud SDK:

使用 command access GCE 要先安裝 Cloud SDK,在 Ubuntu 的安裝方法如下:

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

這樣就裝完了,超簡單的。


2. 確認 Cloud SDK 有正常被安裝:

來個 gcloud 的 hello world:

$ ​gcloud -h

應該要有如下反應:

Usage: gcloud [optional flags] 
  group may be           app | auth | components | compute | config |
                         container | dataflow | dataproc | datastore | debug |
                         deployment-manager | dns | domains | endpoints |
                         firebase | iam | iot | kms | logging | ml | ml-engine |
                         organizations | projects | pubsub | services | source |
                         spanner | sql | topic
  command may be         docker | feedback | help | info | init | version

For detailed information on this command and its flags, run:
  gcloud --help

3. 授權 Google 帳戶

接下來要讓你的 Google 帳戶授權你用 command 登入 GCP:

$ ​gcloud auth login​

如果你要取消 Google 帳戶授權,就用下面的指令:

$ ​gcloud auth revoke <account>

4. 玩轉 Project:

假設大家有照 前一篇 創建了 project 和 instance 的話,我們就來看一下 project 的狀態吧。

列出所有 Projects:

$ gcloud projects list

切換 Project:

$ gcloud config set project <PROJECT_ID>

用 json 格式顯示 Project Info:

$ gcloud compute project-info describe --format=json | less

5. 玩轉 Instance:

列出所有 Instances:

$ gcloud compute instances list

假設你有火牆允許外部 IP 的話 EXTERNAL_IP 會有值

查詢所有 Instances 可用的設定值:

$ gcloud compute machine-types list​

$ gcloud compute images list​

$ gcloud compute regions list​

$ gcloud compute zones list

SSH 連線到 Instance:

$ gcloud compute ssh <instance name> --zone <zone name>​

例如:

$ gcloud compute ssh test-vm --zone us-central1-a

如果 instance name 沒有重複可以省略 zone

連線完後就可以更新或安裝套件,注意這時的機器名稱應該是你的 instance name

好了的話我們來裝個 apache2​ sever,預設會透過 HTTP 顯示 /var/www/html/index.html:

test-vm$ sudo apt-get update​

test-vm$ sudo apt-get install apache2​

test-vm$ sudo /etc/init.d/apache2 start

test-vm$ gcloud compute firewall-rules create http --allow tcp:80

注意到最後一條指令了嗎,我們是在遠端機器上執行 gcloud,打開了 80 port,這樣我們的 apache 才會被戳到(如果你的 instance 設定時有開 HTTP 就不用下這條指令)。

成功的話可以透過 EXTERNAL_IP:80 訪問網頁:


Reference

[1] Marc Cohen, Kathryn Hurley, and Paul Newson, Google Compute Engine, O’Reilly Media(2014)

留言

熱門文章