Cloud Deployment Manager dejará de estar disponible el 31 de diciembre de 2025. Si actualmente usas Deployment Manager, migra a Infrastructure Manager o a una tecnología de implementación alternativa antes del 31 de diciembre de 2025 para asegurarte de que tus servicios continúen sin interrupciones.
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
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.
Desde el repositorio de muestras, abre vm-template.py:
cddeploymentmanager-samples/examples/v2/step_by_step_guide/step5_create_a_template/python
nanovm-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/'defGenerateConfig(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/'defGenerateConfig(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:
cddeploymentmanager-samples/examples/v2/step_by_step_guide/step5_create_a_template/python
nanotwo-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-1type:vm-template.py-name:vm-2type:vm-template-2.py-name:a-new-networktype:compute.v1.networkproperties:routingConfig:routingMode:REGIONALautoCreateSubnetworks: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:
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:
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-03 (UTC)"],[[["\u003cp\u003eTemplates are recommended for complex app deployments to enhance replication and troubleshooting by breaking down configurations into separate, reusable files.\u003c/p\u003e\n"],["\u003cp\u003ePython is preferred over Jinja2 for creating templates due to its greater flexibility and expanded feature set when scaling applications.\u003c/p\u003e\n"],["\u003cp\u003ePython templates must be written in Python 3.x and include a \u003ccode\u003eGenerateConfig(context)\u003c/code\u003e or \u003ccode\u003egenerate_config(context)\u003c/code\u003e method, which returns a Python dictionary.\u003c/p\u003e\n"],["\u003cp\u003eTo use templates, you import them into a configuration file, like \u003ccode\u003etwo-vms.yaml\u003c/code\u003e, which specifies the path to each template and creates template instantiations.\u003c/p\u003e\n"],["\u003cp\u003eThe resource names within the templates, such as \u003ccode\u003ethe-first-vm\u003c/code\u003e and \u003ccode\u003ethe-second-vm\u003c/code\u003e, are used for the actual resource names, not the names provided in the main configuration file.\u003c/p\u003e\n"]]],[],null,["# Understanding reusable templates\n\nWhile developing an app, you most likely require complex architectures. To\nmake your deployment easier to replicate and troubleshoot, we recommend that you\nbreak your configuration into *templates*.\n\nA template is a separate file that defines a set of resources. You can reuse\ntemplates across different deployments, which creates consistency across complex\ndeployments.\n\nYou can use Python or Jinja2 to create templates for Deployment Manager.\nWe recommend that you use Python templates, because Python allows for greater\nflexibility and more features as you scale your app.\n\n### Python templates\n\nIf you choose to write templates in Python, your templates must meet\nthese requirements:\n\n- The template must be written in Python 3.x\n\n- The template must define a method called `GenerateConfig(context)` or\n `generate_config(context)`. If you use both method names in the same template,\n the `generate_config()` method will take precedence.\n\n The `context` object contains metadata about the deployment and your\n environment, such as the deployment's name, the current project, and so on.\n You'll use these deployment-specific variables in later steps.\n- The method must return a\n [Python dictionary](https://docs.python.org/3.0/tutorial/datastructures.html#dictionaries).\n\nExamining sample templates\n--------------------------\n\nFrom the samples repository, open `vm-template.py`: \n\n cd deploymentmanager-samples/examples/v2/step_by_step_guide/step5_create_a_template/python\n\n nano vm-template.py # use your preferred text editor\n\nThis template defines the first virtual machine (VM) from the earlier samples: \n\n # Copyright 2016 Google Inc. All rights reserved.\n #\n # Licensed under the Apache License, Version 2.0 (the \"License\");\n # you may not use this file except in compliance with the License.\n # You may obtain a copy of the License at\n #\n # http://www.apache.org/licenses/LICENSE-2.0\n #\n # Unless required by applicable law or agreed to in writing, software\n # distributed under the License is distributed on an \"AS IS\" BASIS,\n # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n # See the License for the specific language governing permissions and\n # limitations under the License.\n\n \"\"\"Creates the virtual machine.\"\"\"\n\n COMPUTE_URL_BASE = 'https://www.googleapis.com/compute/v1/'\n\n\n def GenerateConfig(unused_context):\n \"\"\"Creates the first virtual machine.\"\"\"\n\n resources = [{\n 'name': 'the-first-vm',\n 'type': 'compute.v1.instance',\n 'properties': {\n 'zone': 'us-central1-f',\n 'machineType': ''.join([COMPUTE_URL_BASE, 'projects/MY_PROJECT',\n '/zones/us-central1-f/',\n 'machineTypes/f1-micro']),\n 'disks': [{\n 'deviceName': 'boot',\n 'type': 'PERSISTENT',\n 'boot': True,\n 'autoDelete': True,\n 'initializeParams': {\n 'sourceImage': ''.join([COMPUTE_URL_BASE, 'projects/',\n 'debian-cloud/global/',\n 'images/family/debian-11'])\n }\n }],\n 'networkInterfaces': [{\n 'network': '$(ref.a-new-network.selfLink)',\n 'accessConfigs': [{\n 'name': 'External NAT',\n 'type': 'ONE_TO_ONE_NAT'\n }]\n }]\n }\n }]\n return {'resources': resources}\n\nOpen the second template, `vm-template-2.py`, which defines the second VM: \n\n # Copyright 2016 Google Inc. All rights reserved.\n #\n # Licensed under the Apache License, Version 2.0 (the \"License\");\n # you may not use this file except in compliance with the License.\n # You may obtain a copy of the License at\n #\n # http://www.apache.org/licenses/LICENSE-2.0\n #\n # Unless required by applicable law or agreed to in writing, software\n # distributed under the License is distributed on an \"AS IS\" BASIS,\n # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n # See the License for the specific language governing permissions and\n # limitations under the License.\n\n \"\"\"Creates the virtual machine.\"\"\"\n\n COMPUTE_URL_BASE = 'https://www.googleapis.com/compute/v1/'\n\n\n def GenerateConfig(unused_context):\n \"\"\"Creates the second virtual machine.\"\"\"\n\n resources = [{\n 'name': 'the-second-vm',\n 'type': 'compute.v1.instance',\n 'properties': {\n 'zone': 'us-central1-f',\n 'machineType': ''.join([COMPUTE_URL_BASE, 'projects/MY_PROJECT',\n '/zones/us-central1-f/',\n 'machineTypes/g1-small']),\n 'disks': [{\n 'deviceName': 'boot',\n 'type': 'PERSISTENT',\n 'boot': True,\n 'autoDelete': True,\n 'initializeParams': {\n 'sourceImage': ''.join([COMPUTE_URL_BASE, 'projects/',\n 'debian-cloud/global',\n '/images/family/debian-11'])\n }\n }],\n 'networkInterfaces': [{\n 'network': '$(ref.a-new-network.selfLink)',\n 'accessConfigs': [{\n 'name': 'External NAT',\n 'type': 'ONE_TO_ONE_NAT'\n }]\n }]\n }\n }]\n return {'resources': resources}\n\nIn **both** templates, replace \u003cvar translate=\"no\"\u003eMY_PROJECT\u003c/var\u003e with your\nproject ID.\n\nImporting templates\n-------------------\n\nAfter you create templates, you must import them into your configuration. Open\nthe new `two-vms.yaml`: \n\n cd deploymentmanager-samples/examples/v2/step_by_step_guide/step5_create_a_template/python\n\n nano two-vms.yaml # use your preferred text editor\n\nThis configuration file has a new `imports` section that calls the two VM\ntemplates, `vm-template.py` and `vm-template-2.py`: \n\n # Copyright 2016 Google Inc. All rights reserved.\n #\n # Licensed under the Apache License, Version 2.0 (the \"License\");\n # you may not use this file except in compliance with the License.\n # You may obtain a copy of the License at\n #\n # http://www.apache.org/licenses/LICENSE-2.0\n #\n # Unless required by applicable law or agreed to in writing, software\n # distributed under the License is distributed on an \"AS IS\" BASIS,\n # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n # See the License for the specific language governing permissions and\n # limitations under the License.\n\n imports:\n - path: vm-template.py\n - path: vm-template-2.py\n\n # In the resources section below, the properties of the resources are replaced\n # with the names of the templates.\n resources:\n - name: vm-1\n type: vm-template.py\n - name: vm-2\n type: vm-template-2.py\n - name: a-new-network\n type: compute.v1.network\n properties:\n routingConfig:\n routingMode: REGIONAL\n autoCreateSubnetworks: true\n\nA note about resource names\n---------------------------\n\nWhen you use a template, your resource names are defined using the `name` field\nprovided in the template, not the name in the configuration file.\n\nFor example, in this case, the VM instances are created using the names in the\ntemplates, `the-first-vm` and `the-second-vm`. The values `vm-1` and `vm-2`,\ndefined in the configuration, are used to name an instantiation of the template,\nbut are not resource names.\n\nSaving your configuration and deploying it\n------------------------------------------\n\nTo deploy the configuration, run this command: \n\n gcloud deployment-manager deployments create deployment-with-templates --config two-vms.yaml\n\nTo view your deployment, run this command: \n\n gcloud deployment-manager deployments describe deployment-with-templates\n\nLooking ahead: using multiple templates\n---------------------------------------\n\nIn the next step, you combine templates so that your configuration only calls\none template to deploy all your resources.\n\nDeleting your deployment\n------------------------\n\nBefore proceeding, we recommend that you delete the deployment to avoid charges.\nYou don't need this deployment for the next step. Run the following command to\ndelete the deployment: \n\n gcloud deployment-manager deployments delete deployment-with-templates"]]