瞭解可重複使用的範本

開發應用程式時,您很可能需要使用複雜的架構。為了讓部署作業更容易進行複製和疑難排解,建議您將設定拆分為多個「範本」

範本是定義一組資源的個別檔案。您可以跨不同部署作業重複使用範本,在多個複雜部署作業之間產生一致性。

您可以使用 Python 或 Jinja2 建立 Deployment Manager 適用的範本。建議您使用 Python 範本,因為 Python 可讓您在擴充應用程式的同時擁有更大的彈性和更多功能。

Python 範本

如果您選擇使用 Python 編寫範本,範本必須符合下列要求:

  • 該範本必須使用 Python 3.x 編寫

  • 範本必須定義名為 GenerateConfig(context)generate_config(context) 的方法。如果您在一個範本中同時使用這兩個方法名稱,系統會優先採用 generate_config() 方法。

    context 物件包含部署作業和環境的中繼資料,例如部署作業的名稱、目前的專案等。您將在後續步驟中使用這些部署專屬變數。

  • 該方法必須傳回 Python 字典

檢查範本範例

從範例存放區中開啟 vm-template.py

cd deploymentmanager-samples/examples/v2/step_by_step_guide/step5_create_a_template/python

nano vm-template.py  # use your preferred text editor

這個範本定義了先前範例中的第一個虛擬機器 (VM):

# Copyright 2016 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Creates the virtual machine."""

COMPUTE_URL_BASE = 'https://www.googleapis.com/compute/v1/'


def GenerateConfig(unused_context):
  """Creates the first virtual machine."""

  resources = [{
      'name': 'the-first-vm',
      'type': 'compute.v1.instance',
      'properties': {
          'zone': 'us-central1-f',
          'machineType': ''.join([COMPUTE_URL_BASE, 'projects/MY_PROJECT',
                                  '/zones/us-central1-f/',
                                  'machineTypes/f1-micro']),
          'disks': [{
              'deviceName': 'boot',
              'type': 'PERSISTENT',
              'boot': True,
              'autoDelete': True,
              'initializeParams': {
                  'sourceImage': ''.join([COMPUTE_URL_BASE, 'projects/',
                                          'debian-cloud/global/',
                                          'images/family/debian-11'])
              }
          }],
          'networkInterfaces': [{
              'network': '$(ref.a-new-network.selfLink)',
              'accessConfigs': [{
                  'name': 'External NAT',
                  'type': 'ONE_TO_ONE_NAT'
              }]
          }]
      }
  }]
  return {'resources': resources}

開啟定義第二個 VM 的第二個範本 vm-template-2.py

# Copyright 2016 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Creates the virtual machine."""

COMPUTE_URL_BASE = 'https://www.googleapis.com/compute/v1/'


def GenerateConfig(unused_context):
  """Creates the second virtual machine."""

  resources = [{
      'name': 'the-second-vm',
      'type': 'compute.v1.instance',
      'properties': {
          'zone': 'us-central1-f',
          'machineType': ''.join([COMPUTE_URL_BASE, 'projects/MY_PROJECT',
                                  '/zones/us-central1-f/',
                                  'machineTypes/g1-small']),
          'disks': [{
              'deviceName': 'boot',
              'type': 'PERSISTENT',
              'boot': True,
              'autoDelete': True,
              'initializeParams': {
                  'sourceImage': ''.join([COMPUTE_URL_BASE, 'projects/',
                                          'debian-cloud/global',
                                          '/images/family/debian-11'])
              }
          }],
          'networkInterfaces': [{
              'network': '$(ref.a-new-network.selfLink)',
              'accessConfigs': [{
                  'name': 'External NAT',
                  'type': 'ONE_TO_ONE_NAT'
              }]
          }]
      }
  }]
  return {'resources': resources}

在這兩個範本中,將 MY_PROJECT 替換為您的專案 ID。

匯入範本

建立範本後,您必須將範本匯入至設定中。開啟新的 two-vms.yaml

cd deploymentmanager-samples/examples/v2/step_by_step_guide/step5_create_a_template/python

nano two-vms.yaml  # use your preferred text editor

這個設定檔有一個新的 imports 區段,會呼叫 vm-template.pyvm-template-2.py 這兩個 VM 範本:

# Copyright 2016 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

imports:
- path: vm-template.py
- path: vm-template-2.py

# In the resources section below, the properties of the resources are replaced
# with the names of the templates.
resources:
- name: vm-1
  type: vm-template.py
- name: vm-2
  type: vm-template-2.py
- name: a-new-network
  type: compute.v1.network
  properties:
    routingConfig:
      routingMode: REGIONAL
    autoCreateSubnetworks: true

資源名稱注意事項

使用範本時,系統會使用範本提供的 name 欄位來定義資源名稱,而不是使用設定檔中的名稱。

例如在本範例中,系統會使用範本中的名稱 the-first-vmthe-second-vm 來建立 VM 執行個體,設定中定義的 vm-1vm-2 值則會用來命名針對這個範本建立的執行個體,但這些值並非資源名稱。

儲存並部署設定

如要部署設定,請執行下列指令:

gcloud deployment-manager deployments create deployment-with-templates --config two-vms.yaml

如要查看部署作業,請執行下列指令:

gcloud deployment-manager deployments describe deployment-with-templates

預做準備:使用多個範本

在下一個步驟中,您會合併範本,讓設定只呼叫一個範本即可部署所有資源。

刪除部署作業

建議您先刪除部署作業,以免產生費用。下一個步驟不需要用到這個部署作業。執行下列指令以刪除部署作業:

gcloud deployment-manager deployments delete deployment-with-templates