Comprende las plantillas reutilizables

Cuando desarrollas una app, lo más probable es que requieras arquitecturas complejas. Para facilitar la replicación de tu implementación y la resolución de problemas en ella, te recomendamos que dividas la configuración en plantillas.

Una plantilla es un archivo separado que define un conjunto de recursos. Puedes volver a usar plantillas en diferentes implementaciones, lo que crea coherencia en implementaciones complejas.

Puedes usar Python o Jinja2 a fin de crear plantillas para Deployment Manager. Te recomendamos que uses plantillas de Python, ya que te brinda una mayor flexibilidad y más funciones a medida que escalas tu app.

Plantillas de Python

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

  • La plantilla debe escribirse en Python 3.x.

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

    El objeto context contiene metadatos sobre la implementación y el entorno, como el nombre de la implementación, el proyecto actual, etcétera. En los próximos pasos, usarás estas variables específicas de la implementación.

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

Examina plantillas de muestra

Desde 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, reemplaza MY_PROJECT por el ID del proyecto.

Importa plantillas

Después de crear las plantillas, debes importarlas a tu configuración. Abre el two-vms.yaml nuevo:

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 sección imports nueva 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

Una nota sobre los nombres de recursos

Cuando usa una plantilla, los nombres de tus recursos se definen con el campo name provisto en la plantilla, no el nombre en el archivo de configuración.

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

Guarda tu configuración y, luego, impleméntala

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: usa plantillas múltiples

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

Borrar tu implementación

Antes de continuar, te recomendamos que borres la implementación para evitar cargos. No necesitas esta implementación para el siguiente paso. Ejecuta el siguiente comando para borrar la implementación:

gcloud deployment-manager deployments delete deployment-with-templates