在GCP上建立GCE的三種方式(Console,gcloud,Terraform)

南瓜慢說發表於2023-01-19

1 簡介

如果要選擇GCP為雲平臺,則經常需要建立GCE(Google Compute Engine),有以下幾種方式:

(1) 在瀏覽器建立

(2) 命令 gcloud

(3) Terraform

在開始之前,可以檢視:《初始化一個GCP專案並用gcloud訪問操作》。

2 GCP Console

登陸操作介面,點選建立按鈕,然後選擇好引數即可:

會顯示出對應的價格。

3 gcloud命令

在操作介面建立時,可以直接檢視對應的gcould命令:

我們直接執行就可以建立了:

$ gcloud compute instances create pkslow-vm \
--project=pkslow \
--zone=us-west1-a \
--machine-type=e2-micro \
--network-interface=network-tier=PREMIUM,subnet=default \
--maintenance-policy=MIGRATE \
--service-account=admin-for-all@pkslow.iam.gserviceaccount.com \
--scopes=https://www.googleapis.com/auth/cloud-platform \
--tags=http-server,https-server \
--create-disk=auto-delete=yes,boot=yes,device-name=instance-1,image=projects/centos-cloud/global/images/centos-8-v20211105,mode=rw,size=20,type=projects/pkslow/zones/us-west1-a/diskTypes/pd-standard \
--no-shielded-secure-boot \
--shielded-vtpm \
--shielded-integrity-monitoring \
--reservation-affinity=any

Created [https://www.googleapis.com/compute/v1/projects/pkslow/zones/us-west1-a/instances/pkslow-vm].
NAME       ZONE        MACHINE_TYPE  PREEMPTIBLE  INTERNAL_IP  EXTERNAL_IP     STATUS
pkslow-vm  us-west1-a  e2-micro                   10.138.0.5   34.145.124.xxx  RUNNING

                10.138.0.5   34.145.124.xxx  RUNNING

檢查是否建立成功:

$ gcloud compute instances list
NAME       ZONE        MACHINE_TYPE  PREEMPTIBLE  INTERNAL_IP  EXTERNAL_IP     STATUS
pkslow-vm  us-west1-a  e2-micro   

4 Terraform

當然,最佳實踐是使用Terraform來管理,程式碼簡單易懂,具體如下:

provider "google" {
  project     = "pkslow"
}

resource "google_compute_instance" "test" {
  name         = "pkslow-test"
  machine_type = "e2-micro"
  zone         = "us-west1-a"

  tags = ["http-server", "https-server"]

  boot_disk {
    initialize_params {
      image = "projects/centos-cloud/global/images/centos-8-v20211105"
    }
  }


  network_interface {
    network = "default"

    access_config {
      // Ephemeral public IP
    }
  }

  metadata = {
    foo = "bar"
  }

  metadata_startup_script = "echo hi > /test.txt"

  service_account {
    # Google recommends custom service accounts that have cloud-platform scope and permissions granted via IAM Roles.
    email  = "admin-for-all@pkslow.iam.gserviceaccount.com"
    scopes = ["cloud-platform"]
  }
}

檢查是否建立成功:

$ gcloud compute instances list
NAME         ZONE        MACHINE_TYPE  PREEMPTIBLE  INTERNAL_IP  EXTERNAL_IP     STATUS
pkslow-test  us-west1-a  e2-micro                   10.138.0.6   34.83.138.xxx   RUNNING
pkslow-vm    us-west1-a  e2-micro                   10.138.0.5   34.145.124.xxx  RUNNING

也可以介面上檢視:

5 程式碼

程式碼請檢視GitHub: https://github.com/LarryDpk/p...

相關文章