使用 Terraform 部署基本的 Flask 網路伺服器

在本教學課程中,您將瞭解如何開始使用 Terraform,並透過 Terraform 在 Compute Engine 上建立基本網路伺服器。

在本教學課程中,執行下列操作:

  • 使用 Terraform 在 Google Cloud中建立 VM。
  • 啟動基本的 Python Flask 伺服器。

費用

In this document, you use the following billable components of Google Cloud:

Compute Engine

To generate a cost estimate based on your projected usage, use the pricing calculator. New Google Cloud users might be eligible for a free trial.

When you finish the tasks that are described in this document, you can avoid continued billing by deleting the resources that you created. For more information, see Clean up.

事前準備

準備開始教學課程。

選取或建立專案

  1. In the Google Cloud console, go to the project selector page.

    Go to project selector

  2. Select or create a Google Cloud project.

設定權限

請確認您已在使用者帳戶中取得必要的 Compute Engine 權限

  • compute.instances.*
  • compute.firewalls.*

前往「身分與存取權管理」頁面

進一步瞭解角色和權限。

啟用 API

Enable the Compute Engine API.

Enable the API

啟動 Cloud Shell

Cloud Shell 是 Compute Engine 虛擬機器。

與這個虛擬機器相關聯的服務憑證會自動產生,因此您不需要設定或下載服務帳戶金鑰。

Terraform 已與 Cloud Shell 整合,Cloud Shell 會自動驗證 Terraform,讓您不必進行太多設定就能開始使用。

建立 Compute Engine VM

首先,您必須在 Terraform 設定檔中定義 VM 的設定。接著,您可以執行 Terraform 指令,在專案中建立 VM。

建立目錄

建立新目錄。在新目錄中,建立 Terraform 設定的 main.tf 檔案。此檔案的內容會說明專案中要建立的所有 Google Cloud 資源。

在 Cloud Shell 中:

mkdir tf-tutorial && cd tf-tutorial
nano main.tf

建立虛擬私有雲網路和子網路

在本節中,您會為 VM 的網路介面建立虛擬私有雲 (VPC) 網路和子網路。

將下列 Terraform 資源新增至您建立的 main.tf 檔案:

resource "google_compute_network" "vpc_network" {
  name                    = "my-custom-mode-network"
  auto_create_subnetworks = false
  mtu                     = 1460
}

resource "google_compute_subnetwork" "default" {
  name          = "my-custom-subnet"
  ip_cidr_range = "10.0.1.0/24"
  region        = "us-west1"
  network       = google_compute_network.vpc_network.id
}

建立 Compute Engine VM 資源

在本節中,您將建立單一 Compute Engine 執行個體,並執行 Debian。在本教學課程中,您將使用可用的最小機器類型。之後,您可以升級至更大的機器類型。

將下列 google_compute_instance Terraform 資源新增至您建立的 main.tf 檔案。

# Create a single Compute Engine instance
resource "google_compute_instance" "default" {
  name         = "flask-vm"
  machine_type = "f1-micro"
  zone         = "us-west1-a"
  tags         = ["ssh"]

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-11"
    }
  }

  # Install Flask
  metadata_startup_script = "sudo apt-get update; sudo apt-get install -yq build-essential python3-pip rsync; pip install flask"

  network_interface {
    subnetwork = google_compute_subnetwork.default.id

    access_config {
      # Include this section to give the VM an external IP address
    }
  }
}

程式碼範例會將 Google Cloud 區域設為 us-west1-a。您可以將其變更為其他區域

初始化 Terraform

此時,您可以執行 terraform init 來新增必要的外掛程式,並建構 .terraform 目錄。

terraform init

輸出內容:

Initializing the backend...

Initializing provider plugins...
...

Terraform has been successfully initialized!

驗證 Terraform 設定

您可以選擇驗證目前已建構的 Terraform 程式碼。執行 terraform plan,執行以下操作:

  • 驗證 main.tf 的語法是否正確
  • 顯示即將建立的資源預覽畫面
terraform plan

輸出內容:

...

Plan: 1 to add, 0 to change, 0 to destroy.

Note: You didn't use the -out option to save this plan, so Terraform can't
guarantee to take exactly these actions if you run "terraform apply" now.

套用設定

如要建立 VM,請執行 terraform apply

terraform apply

系統顯示提示訊息時,請輸入 yes

Terraform 會呼叫 API 來設定新的 VM。 Google Cloud 查看「VM instances」(VM 執行個體) 頁面,瞭解新的 VM。

在 Google Cloud上執行網路伺服器

接下來,您需要建立網頁應用程式、將其部署至 VM,並建立防火牆規則,允許用戶端向網頁應用程式提出要求。

新增自訂 SSH 防火牆規則

default 網路中的 default-allow-ssh 防火牆規則可讓您使用 SSH 連線至 VM。如果您想使用自訂防火牆規則,可以在 main.tf 檔案結尾新增下列資源:

resource "google_compute_firewall" "ssh" {
  name = "allow-ssh"
  allow {
    ports    = ["22"]
    protocol = "tcp"
  }
  direction     = "INGRESS"
  network       = google_compute_network.vpc_network.id
  priority      = 1000
  source_ranges = ["0.0.0.0/0"]
  target_tags   = ["ssh"]
}

執行 terraform apply 建立防火牆規則。

使用 SSH 連線至 VM

請使用 SSH 連線至 VM,驗證目前所有設定是否正確無誤。

  1. 前往「VM instances」(VM 執行個體) 頁面

  2. 找出名稱為 flask-vm 的 VM。

  3. 在「連線」欄中,按一下「SSH」

    系統會為執行中的 VM 開啟「SSH-in-browser」終端機視窗。

詳情請參閱「連線至 VM」。

建構 Flask 應用程式

您會為本教學課程建構 Python Flask 應用程式,以便您擁有一個描述網路伺服器和測試端點的單一檔案。

  1. 在 SSH 終端機中,建立名為 app.py 的檔案。

    nano app.py
    
  2. 請將下列內容新增至 app.py 檔案:

    from flask import Flask
    app = Flask(__name__)
    
    @app.route('/')
    def hello_cloud():
      return 'Hello Cloud!'
    
    app.run(host='0.0.0.0')
    
  3. 執行 app.py

    python3 app.py
    

    根據預設,Flask 會在 localhost:5000 上提供流量。

  4. 開啟第二個 SSH 連線:

    1. 前往「VM instances」(VM 執行個體) 頁面
    2. 找出名為 flask-vm 的 VM,然後按一下「SSH」SSH
  5. 在第二個 SSH 連線中,執行 curl,確認您在 app.py 中設定的問候語是否已傳回。

    curl http://0.0.0.0:5000
    

    這個指令的輸出結果為 Hello Cloud

在 VM 上開啟 5000 通訊埠

如要從本機電腦連線至網路伺服器,VM 必須開啟通訊埠 5000。 Google Cloud 可讓您使用防火牆規則開啟通訊埠。

main.tf 檔案的結尾新增下列 google_compute_firewall Terraform 資源。

resource "google_compute_firewall" "flask" {
  name    = "flask-app-firewall"
  network = google_compute_network.vpc_network.id

  allow {
    protocol = "tcp"
    ports    = ["5000"]
  }
  source_ranges = ["0.0.0.0/0"]
}

在 Cloud Shell 中執行 terraform apply 來建立防火牆規則。

為 Web 伺服器網址新增輸出變數

  1. main.tf 的結尾,新增Terraform 輸出變數,以便輸出 Web 伺服器網址:

    // A variable for extracting the external IP address of the VM
    output "Web-server-URL" {
     value = join("",["https://",google_compute_instance.default.network_interface.0.access_config.0.nat_ip,":5000"])
    }
    
  2. 執行 terraform apply

    terraform apply
    

    出現提示時,請輸入 yes。Terraform 會將 VM 的外部 IP 位址和 5000 埠列印到畫面上,如下所示:

    Web-server-URL = "http://IP_ADDRESS:5000"
    

    您隨時可以執行 terraform output 來傳回以下輸出內容:

    terraform output
    
  3. 按一下上一個步驟的網址,即可看到「Hello Cloud!」訊息。

    這表示您的伺服器正在運作。

疑難排解

  • 如果未啟用必要的 API,Terraform 會傳回錯誤。錯誤訊息中包含啟用 API 的連結。啟用 API 後,您可以重新執行 terraform apply

  • 如果無法透過 SSH 連線至 VM:

清除所用資源

完成教學課程後,您可以刪除所有建立的內容,避免產生任何額外費用。

您可以透過執行 terraform destroy 指令,使用 Terraform 移除設定檔中定義的所有資源:

terraform destroy

輸入 yes 可讓 Terraform 刪除資源。

後續步驟