设置模板属性和使用环境变量

为部署使用模板的一个好处是可以创建和定义自定义属性,这支持您在地区、区域和项目间重复使用模板。

模板属性是任意变量。任何配置文件或模板文件都可以为模板属性提供值,而无需修改模板。因此,您可以在不更改模板本身的情况下更改各种配置的属性值。

要引用任意值,请在模板中使用以下语法:

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

接下来:辅助脚本

接下来,了解有助于高效执行重复任务的辅助脚本。