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

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

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

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

費用

在本文件中,您會使用 Google Cloud的下列計費元件:

Compute Engine

如要根據預測用量估算費用,請使用 Pricing Calculator

初次使用 Google Cloud 的使用者可能符合免費試用資格。

完成本文所述工作後,您可以刪除已建立的資源,避免繼續計費。詳情請參閱清除所用資源一節。

事前準備

準備開始教學課程。

選取或建立專案

  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.*

前往「IAM」頁面

如要進一步瞭解角色和權限,請參閱這篇文章

啟用 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

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

在本節中,您會為虛擬機器的網路介面建立虛擬私有雲 (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 資源

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

將下列 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 會呼叫 Google Cloud API 來設定新的 VM。查看「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-in-browser 終端機中,建立名為 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 輸出變數,輸出網頁伺服器網址:

    // A variable for extracting the external IP address of the VM
    output "Web-server-URL" {
     value = join("",["http://",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 執行 terraform destroy 指令,移除設定檔中定義的所有資源:

terraform destroy

輸入 yes,允許 Terraform 刪除資源。

後續步驟