Der Support für Cloud Deployment Manager endet am 31. Dezember 2025. Wenn Sie derzeit Deployment Manager verwenden, müssen Sie bis zum 31. Dezember 2025 zu Infrastructure Manager oder einer alternativen Bereitstellungstechnologie migrieren, damit Ihre Dienste ohne Unterbrechung weiterlaufen.
Mit Sammlungen den Überblick behalten
Sie können Inhalte basierend auf Ihren Einstellungen speichern und kategorisieren.
Bei der Entwicklung einer Anwendung benötigen Sie höchstwahrscheinlich komplexe Architekturen. Damit Sie Ihre Bereitstellung einfacher replizieren und Probleme leichter beheben können, empfehlen wir, Ihre Konfiguration in Vorlagen aufzuteilen.
Eine Vorlage ist eine separate Datei, mit der eine Reihe von Ressourcen definiert wird. Sie können Vorlagen in verschiedenen Bereitstellungen wiederverwenden, wodurch bei komplexen Bereitstellungen für Konsistenz gesorgt wird.
Zur Erstellung von Vorlagen für Deployment Manager können Sie Python oder Jinja2 verwenden.
Wir empfehlen die Verwendung von Python-Vorlagen, da Python mehr Flexibilität und mehr Features für das Skalieren Ihrer Anwendung bietet.
Python-Vorlagen
Wenn Sie Vorlagen in Python schreiben, müssen diese folgende Anforderungen erfüllen:
Die Vorlage muss in Python 3.x geschrieben sein.
Die Vorlage muss eine Methode mit dem Namen GenerateConfig(context) oder generate_config(context) definieren. Wenn Sie beide Methodennamen in derselben Vorlage verwenden, hat die Methode generate_config() Vorrang.
Das context-Objekt enthält Metadaten über die Bereitstellung und Ihre Umgebung, z. B. den Namen der Bereitstellung, das aktuelle Projekt usw.
Diese implementierungsspezifischen Variablen werden in späteren Schritten verwendet.
cddeploymentmanager-samples/examples/v2/step_by_step_guide/step5_create_a_template/python
nanovm-template.py# use your preferred text editor
Diese Vorlage definiert die erste virtuelle Maschine (VM) aus den vorherigen Beispielen:
# 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}
Öffnen Sie die zweite Vorlage, vm-template-2.py, die die zweite VM definiert:
# 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}
Ersetzen Sie in beiden Vorlagen MY_PROJECT durch Ihre Projekt-ID.
Vorlagen importieren
Nach der Erstellung von Vorlagen müssen Sie diese in Ihre Konfiguration importieren. Öffnen Sie die neue two-vms.yaml:
cddeploymentmanager-samples/examples/v2/step_by_step_guide/step5_create_a_template/python
nanotwo-vms.yaml# use your preferred text editor
Diese Konfigurationsdatei enthält einen neuen imports-Abschnitt, der die beiden VM-Vorlagen vm-template.py und vm-template-2.py aufruft:
# 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
Hinweis zu Ressourcennamen
Wenn Sie eine Vorlage verwenden, werden die Namen Ihrer Ressourcen nicht mit dem Namen in der Konfigurationsdatei definiert, sondern mit dem Feld name in der Vorlage.
In diesem Fall werden die VM-Instanzen beispielsweise mit den Namen in den Vorlagen (the-first-vm und the-second-vm) erstellt. Die in der Konfiguration definierten Werte vm-1 und vm-2 werden verwendet, um eine Instantiierung der Vorlage zu benennen, sind jedoch keine Ressourcennamen.
Konfiguration speichern und bereitstellen
Führen Sie den folgenden Befehl aus, um die Konfiguration bereitzustellen:
Im nächsten Schritt kombinieren Sie Vorlagen, sodass Ihre Konfiguration nur eine Vorlage aufruft, um alle Ihre Ressourcen bereitzustellen.
Bereitstellung löschen
Bevor Sie fortfahren, sollten Sie die Bereitstellung löschen, um Kosten zu vermeiden.
Diese Bereitstellung benötigen Sie für den nächsten Schritt nicht. Führen Sie den folgenden Befehl aus, um die Bereitstellung zu löschen:
[[["Leicht verständlich","easyToUnderstand","thumb-up"],["Mein Problem wurde gelöst","solvedMyProblem","thumb-up"],["Sonstiges","otherUp","thumb-up"]],[["Schwer verständlich","hardToUnderstand","thumb-down"],["Informationen oder Beispielcode falsch","incorrectInformationOrSampleCode","thumb-down"],["Benötigte Informationen/Beispiele nicht gefunden","missingTheInformationSamplesINeed","thumb-down"],["Problem mit der Übersetzung","translationIssue","thumb-down"],["Sonstiges","otherDown","thumb-down"]],["Zuletzt aktualisiert: 2025-08-19 (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"]]