Descripción de las plantillas reutilizables

Durante el desarrollo de una aplicación, lo más probable es que necesites arquitecturas complejas. Para que sea más fácil replicar y solucionar problemas en tu despliegue, te recomendamos que dividas la configuración en plantillas.

Una plantilla es un archivo independiente que define un conjunto de recursos. Puedes reutilizar plantillas en diferentes implementaciones, lo que crea coherencia en implementaciones complejas.

Puedes usar Python o Jinja2 para crear plantillas de Deployment Manager. Te recomendamos que uses plantillas de Python, ya que este lenguaje te ofrece más flexibilidad y funciones a medida que tu aplicación vaya creciendo.

Plantillas de Python

Si decides escribir plantillas en Python, estas deben cumplir los siguientes requisitos:

  • La plantilla debe estar escrita en Python 3.x.

  • La plantilla debe definir un método llamado GenerateConfig(context) o generate_config(context). Si usa ambos nombres de método en la misma plantilla, tendrá prioridad el método generate_config().

    El objeto context contiene metadatos sobre la implementación y tu entorno, como el nombre de la implementación, el proyecto actual, etc. Usarás estas variables específicas del despliegue en pasos posteriores.

  • El método debe devolver un diccionario de Python.

Examinar plantillas de ejemplo

En el repositorio de muestras, abre 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

Esta plantilla define la primera máquina virtual (VM) de los ejemplos anteriores:

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

Abre la segunda plantilla, vm-template-2.py, que define la segunda 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 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}

En ambas plantillas, sustituye MY_PROJECT por el ID de tu proyecto.

Importar plantillas

Después de crear plantillas, debe importarlas a su configuración. Abre la nueva 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

Este archivo de configuración tiene una nueva sección imports que llama a las dos plantillas de VM, vm-template.py y 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.

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

Nota sobre los nombres de recursos

Cuando usas una plantilla, los nombres de los recursos se definen mediante el campo name que se proporciona en la plantilla, no con el nombre del archivo de configuración.

Por ejemplo, en este caso, las instancias de VM se crean con los nombres de las plantillas the-first-vm y the-second-vm. Los valores vm-1 y vm-2 definidos en la configuración se usan para asignar un nombre a una instanciación de la plantilla, pero no son nombres de recursos.

Guardar la configuración y desplegarla

Para implementar la configuración, ejecuta este comando:

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

Para ver tu implementación, ejecuta este comando:

gcloud deployment-manager deployments describe deployment-with-templates

De cara al futuro: usar varias plantillas

En el siguiente paso, combinarás las plantillas para que tu configuración solo llame a una plantilla para implementar todos tus recursos.

Eliminar el despliegue

Antes de continuar, te recomendamos que elimines la implementación para evitar que se te apliquen cargos. No necesitas este despliegue para el siguiente paso. Ejecuta el siguiente comando para eliminar la implementación:

gcloud deployment-manager deployments delete deployment-with-templates