使用多个模板

在此步骤中,您将了解用于导入其他模板的模板。

整合这些模板后,您的配置只需调用单个模板即可创建包含所有这些资源的部署。

打开适用于网络的模板

打开名为 compute-engine-template.py 的模板:

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

nano compute-engine-template.py  # use your preferred text editor

此模板会导入适用于部署中的所有资源的其他模板:vm-template.py、适用于虚拟机 (VM) 的 vm-template-2.py、适用于网络的 network-template.py 以及适用于防火墙规则的 firewall-template.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 Compute Engine."""


def GenerateConfig(context):
  """Creates the Compute Engine with network and firewall."""

  resources = [{
      'name': 'vm-1',
      'type': 'vm-template.py'
  }, {
      'name': 'vm-2',
      'type': 'vm-template-2.py'
  }, {
      'name': 'network-1',
      'type': 'network-template.py'
  }, {
      'name': 'firewall-1',
      'type': 'firewall-template.py'
  }]
  return {'resources': resources}

查看配置

打开部署的配置文件:

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

nano config-with-many-templates.yaml  # use your preferred text editor

请注意,该配置没有直接调用其他模板。不过,其他模板是导入的,因为 compute-engine-template.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
- path: network-template.py
- path: firewall-template.py
- path: compute-engine-template.py

resources:
- name: compute-engine-setup
  type: compute-engine-template.py

保存配置并进行部署

运行以下命令以部署配置:

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

要查看部署,请运行以下命令:

gcloud deployment-manager deployments describe deployment-with-many-templates

接下来:模板属性和环境变量

接下来,您将使用自定义模板和环境变量等可重复使用的格式替换模板的一些硬编码部分。

删除部署

我们建议您删除部署以避免产生费用。您无需此部署即可执行下一步操作。运行以下命令可删除部署:

gcloud deployment-manager deployments delete deployment-with-many-templates