使用 Cloud Deployment Manager 部署 Python Bookshelf 應用程式

本教學課程說明如何使用 Cloud Deployment Manager 部署 Python Bookshelf 範例應用程式。

Deployment Manager 可讓您透過宣告式的可重複程序,在單一步驟中建立部署作業所需的Google Cloud 資源。您可以使用 Deployment Manager 更新部署作業、追蹤各時期的修改內容、透過 Jinja 或 Python 建立範本,以及將範本參數化,以便相似的部署作業共用範本。

目標

  • 複製並設定 Bookshelf 範例應用程式。
  • 建立 Deployment Manager 設定與範本。
  • 建立 Deployment Manager 部署作業。
  • 使用 Deployment Manager 部署 Bookshelf 範例應用程式。

費用

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

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

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

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

事前準備

  1. 登入 Google Cloud 帳戶。如果您是 Google Cloud新手,歡迎 建立帳戶,親自評估產品在實際工作環境中的成效。新客戶還能獲得價值 $300 美元的免費抵免額,可用於執行、測試及部署工作負載。
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Datastore API, Cloud Storage API, Pub/Sub API APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  5. 安裝 Google Cloud CLI。

  6. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI

  7. 執行下列指令,初始化 gcloud CLI:

    gcloud init
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  9. Verify that billing is enabled for your Google Cloud project.

  10. Enable the Datastore API, Cloud Storage API, Pub/Sub API APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  11. 安裝 Google Cloud CLI。

  12. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI

  13. 執行下列指令,初始化 gcloud CLI:

    gcloud init
  14. 在系統上安裝 Python、pipvirtualenv。如需操作說明,請參閱設定 Python 開發環境一文。 Google Cloud

建立 Cloud Storage 值區

以下指示說明如何建立 Cloud Storage 值區。值區是在 Cloud Storage 中保存資料的基本容器。

  1. 在終端機視窗中,建立 Cloud Storage bucket,其中 YOUR_BUCKET_NAME 代表 bucket 名稱:

    gcloud storage buckets create gs://YOUR_BUCKET_NAME
  2. 如要在 Bookshelf 應用程式中查看已上傳的圖片,請設定 bucket 的 Identity and Access Management 政策,將 legacyObjectReader 角色授予 allUsers

    gcloud storage buckets add-iam-policy-binding gs://YOUR_BUCKET_NAME
    --member=allUsers --role=roles/storage.legacyObjectReader

複製範例應用程式

您可以在 GitHub 的 GoogleCloudPlatform/getting-started-python 中找到範例應用程式。

  1. 複製存放區:

    git clone https://github.com/GoogleCloudPlatform/getting-started-python.git -b steps
    
  2. 前往範例目錄:

    cd getting-started-python/7-gce
    

設定應用程式

  1. 開啟 config.py 進行編輯。

    • PROJECT_ID 的值設定為您的專案 ID。

    • 將值 CLOUD_STORAGE_BUCKET 設為您的 Cloud Storage 值區名稱。

  2. 儲存並關閉 config.py

在本機電腦上執行應用程式

  1. 建立獨立的 Python 環境,並安裝依附元件:

    Linux/macOS

    virtualenv -p python3 env
    source env/bin/activate
    pip install -r requirements.txt
    

    Windows

    virtualenv -p python3 env
    env\scripts\activate
    pip install -r requirements.txt
    

  2. 執行應用程式:

    python main.py
    
  3. 在瀏覽器中,輸入下列網址:

    http://localhost:8080

如要停止本機網路伺服器,請按下 Control+C 鍵。如要退出虛擬環境,請輸入 deactivate

部署範例應用程式

將程式碼推送至存放區

您可以透過以下幾種方式,將程式碼推送至執行中的 Compute Engine 執行個體。其中一種方式是使用 Cloud Source Repositories。每個專案都包含一個 Git 存放區,可供 Compute Engine 執行個體使用。這樣一來,您的執行個體就可以在啟動期間,提取最新版本的應用程式程式碼。Git 存放區使用起來相當便利,因為更新應用程式無須設定新的映像檔或執行個體,只要重新啟動現有執行個體或新建執行個體即可。

  1. 初次使用 Git 時,請利用 git config --global 設定您的身分

  2. 在 Google Cloud 控制台中建立存放區:

    建立存放區

  3. 接下來,將您的應用程式程式碼推送至您專案的存放區;其中 [YOUR_PROJECT_ID] 是您的專案 ID,而 [YOUR_REPO] 是您的存放區名稱:

    git commit -am "Updating configuration"
    git config credential.helper gcloud.sh
    git remote add cloud https://source.developers.google.com/p/[YOUR_PROJECT_ID]/r/[YOUR_REPO]
    git push cloud master
    

建立部署作業

在設定修訂完成,且程式碼已上傳至 Cloud Source Repositories 之後,您就可以使用 Deployment Manager 建立部署作業:

  1. 前往 deployment_manager 目錄:

    cd getting-started-python/7-gce/gce/deployment_manager
    
  2. 建立部署作業:

    gcloud deployment-manager deployments create my-deployment --config config.yaml
    
  3. 查看所有部署作業的清單:

    gcloud deployment-manager deployments list
    
  4. 取得部署作業及其所建立資源的說明:

    gcloud deployment-manager deployments describe my-deployment
    

查看您的應用程式

建立轉送規則後,可能需要花費幾分鐘時間來傳播設定及將流量轉送至執行個體。

  1. 如要查看進度,請輸入下列指令碼:

    gcloud compute backend-services get-health bookshelf-my-deployment-frontend --global
    
  2. 當至少有一個執行個體回報 HEALTHY 時,請取得負載平衡器的轉送 IP 位址:

    gcloud compute forwarding-rules list --global
    

    您的轉送規則 IP 位址位於 IP_ADDRESS 資料欄。

  3. 請在瀏覽器中輸入清單列出的 IP 位址。

    您的應用程式現在會在 Google Cloud上執行。

瞭解程式碼

設定部署作業

您可以在 config.yaml 中看到部署作業的設定方式:

imports:
- name: bookshelf.jinja
  path: ./bookshelf.jinja

resources:
- name: bookshelf
  type: bookshelf.jinja
  properties:
    zone: us-central1-f
    machine-type: n1-standard-1
    machine-image: https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/family/debian-9
    min-instances: 1
    max-instances: 10
    target-utilization: 0.6
    scopes:
    - https://www.googleapis.com/auth/cloud-platform

這個設定檔會將範本檔案當成資源匯入,並使用該檔案來定義名為 bookshelf 的資源。範本會採用多個屬性做為參數。如要進一步瞭解如何建立 Deployment Manager 設定檔,請參閱建立設定的相關說明。

設定部署作業範本的結構定義

查看結構定義檔案 bookshelf.jinja.schema,這個檔案定義並記錄了部署作業應在設定檔中提供的參數。如要進一步瞭解設定結構定義,請參閱使用結構定義一文。


info:
  title: Bookshelf GCE Deploy
  author: Google Inc.
  description: Creates a GCE Deployment

imports:
- name: startup-script
  path: ../startup-script.sh

required:
- zone
- machine-type
- min-instances
- max-instances
- scopes

properties:
  zone:
    description: Zone to create the resources in.
    type: string
  machine-type:
    description: Type of machine to use
    type: string
  machine-image:
    description: The OS image to use on the machines
    type: string
  min-instances:
    description: The minimum number of VMs the autoscaler will create
    type: integer
  max-instances:
    description: The maximum number of VMs the autoscaler will create
    type: integer
  target-utilization:
    description: The target CPU usage for the autoscaler to base its scaling on
    type: number
  scopes:
    description: A list of scopes to create the VM with
    type: array
    minItems: 1
    items:
      type: string

設定部署作業範本

範本定義了多個資源,來建立已自動調度資源且已達到負載平衡的代管執行個體群組。如要澈底瞭解在定義過程中建立的資源,請查看範本中的註解,並參閱 Compute Engine 上的 Bookshelf 教學課程。

請注意,Deployment Manager 提供以宣告方式定義資源的方法,但特定資源的大部分設定是由其 API 定義。舉例來說,執行個體範本資源的大部分設定選項,都位於 Compute Engine API 參考文件中的執行個體範本資源定義

範本使用 Jinja 範本語言編寫。編寫 Deployment Manager 範本時,您可以使用 Jinja 或 Python。Jinja 的優勢在於宣告性更強,比 Python 更容易閱讀和理解。Python 的完整表達能力可能會使部分複雜的部署作業更為簡化。針對本例,使用 Jinja 就足以建立必要資源。

範本中的環境變數會自動設定,您可以使用 env 字典存取這些變數。部署作業的名稱會做為要在指派名稱給建立資源時重複使用的名稱參照。如要進一步瞭解可用的環境變數,請參閱 Deployment Manager 說明文件中的「使用環境變數」一節:

{% set NAME = "bookshelf-" + env["deployment"] %}
{% set SERVICE = "bookshelf-" + env["deployment"] + "-frontend" %}

範本使用的開機指令碼與 Compute Engine 教學課程中所用的相同。這個指令碼的內容會插入範本,Jinja 縮排指令會對內容進行正確縮排:

            value: |
{{imports['startup-script']|indent(14, true)}}

在 Deployment Manager Jinja 範本中,您也可以參閱在範本中其他位置建立的資源。在下例中,後端服務使用代管執行個體群組的參考資料,取得服務應指向的執行個體群組:

- group: $(ref.{{ NAME }}-frontend-group.instanceGroup)
  zone: {{ properties['zone'] }}

您在 config.yaml 中指定的屬性可用於此範本:

minNumReplicas: {{ properties['min-instances'] }}
maxNumReplicas: {{ properties['max-instances'] }}
loadBalancingUtilization:
  utilizationTarget: {{ properties['target-utilization'] }}

清除所用資源

為避免因為本教學課程所用資源,導致系統向 Google Cloud 收取費用,請刪除含有相關資源的專案,或者保留專案但刪除個別資源。

刪除專案

如要避免付費,最簡單的方法就是刪除您為了本教學課程所建立的專案。

刪除專案的方法如下:

  1. 前往 Google Cloud 控制台的「Manage resources」(管理資源) 頁面。

    前往「Manage resources」(管理資源)

  2. 在專案清單中選取要刪除的專案,然後點選「Delete」(刪除)
  3. 在對話方塊中輸入專案 ID,然後按一下 [Shut down] (關閉) 以刪除專案。

刪除部署作業

如要刪除部署作業,請輸入下列指令,即可刪除負載平衡器,以及與部署作業相關聯的任何 Compute Engine 執行個體:

gcloud deployment-manager deployments delete my-deployment

後續步驟