了解可重复使用的模板

在开发应用时,您很可能需要复杂的架构。为了更轻松地复制部署和排查部署问题,我们建议您将配置分解为多个模板

模板是用于定义一组资源的独立文件。您可以在不同的部署中重复使用模板,从而在复杂部署间实现一致性。

您可以使用 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-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 这两个虚拟机模板:

# 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-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