設定範本屬性並使用環境變數

使用範本進行部署的好處之一是,能夠建立和定義自訂屬性,可讓您跨區域、跨地區及跨專案重複使用範本。

範本屬性是任意變數。任何設定檔或範本檔都可以提供範本屬性值,而不需要修改範本。因此,您可以變更各種設定的屬性值,而不用變更範本本身。

如要參照任意值,請在範本中使用下列語法:

context.properties["property-name"]

除了範本屬性外,您也可以使用已預先填入部署相關資訊的部署專用環境變數。您可以使用範本中的環境變數來取得部署相關的專屬資訊。

您可以使用下列語法呼叫環境變數:

context.env['variable-name']

有效的環境變數包括部署作業名稱、專案 ID、資源的名稱屬性,以及設定的類型。進一步瞭解環境變數

範本屬性和範本中的環境變數

在這個步驟中,vm-template.py 說明範本屬性和環境變數的好處。開啟 vm-template.py

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

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

範本的各個部分已替換為範本屬性和環境變數。舉例來說,專案 ID 已替換為 context.env[project],這樣您就不必手動替換範本中的專案 ID。

檔案中的註解說明範本的其他相關變更。

# 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(context):
  """Creates the virtual machine with environment variables."""

  resources = [{
      # `the-first-vm` is replaced with `context.env[`name`]`
      'name': context.env['name'],
      'type': 'compute.v1.instance',
      'properties': {
          # All occurrences of `us-central1-f` are replaced with
          # `context.properties[`zone`]. 
          # All occurrences of the project ID are replaced with 
          # `context.env[`project`]`.
          # `f1-micro` is replaced with `context.properties["machineType"].  
          'zone': context.properties['zone'],
          'machineType': ''.join([COMPUTE_URL_BASE, 'projects/',
                                  context.env['project'], '/zones/',
                                  context.properties['zone'], '/machineTypes/',
                                  context.properties['machineType']]),
          'disks': [{
              'deviceName': 'boot',
              'type': 'PERSISTENT',
              'boot': True,
              'autoDelete': True,
              'initializeParams': {
                  'sourceImage': ''.join([COMPUTE_URL_BASE, 'projects/',
                                          'debian-cloud/global/',
                                          'images/family/debian-11'])
              }
          }],
          # `$(ref.a-new-network.selfLink)` is replaced with 
          # `$(ref.` + context.properties[`network`] + `selfLink)`.
          'networkInterfaces': [{
              'network': '$(ref.' + context.properties['network']
                         + '.selfLink)',
              'accessConfigs': [{
                  'name': 'External NAT',
                  'type': 'ONE_TO_ONE_NAT'
              }]
          }]
      }
  }]
  return {'resources': resources}

同樣地,network-template.pyfirewall-template.py 會透過呼叫 context.env['name'] 來使用其定義的部署名稱。

部署設定

如要查看這個部署作業的設定檔,請執行下列指令:

nano config-with-many-templates.yaml

儲存變更並重新部署設定,以確認變數是否有效。

gcloud deployment-manager deployments create deployment-with-template-properties --config config-with-many-templates.yaml

刪除部署作業

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

gcloud deployment-manager deployments delete deployment-with-template-properties

預做準備:輔助指令碼

接下來,我們將瞭解如何使用輔助指令碼,有效率地執行週期性工作。