Cloud Deployment Manager will reach end of support on December 31, 2025. If you currently use Deployment Manager, please migrate to Infrastructure Manager or an alternative deployment technology by December 31, 2025 to ensure your services continue without interruption.
Stay organized with collections
Save and categorize content based on your preferences.
While developing an app, you most likely require complex architectures. To
make your deployment easier to replicate and troubleshoot, we recommend that you
break your configuration into templates.
A template is a separate file that defines a set of resources. You can reuse
templates across different deployments, which creates consistency across complex
deployments.
You can use Python or Jinja2 to create templates for Deployment Manager.
We recommend that you use Python templates, because Python allows for greater
flexibility and more features as you scale your app.
Python templates
If you choose to write templates in Python, your templates must meet
these requirements:
The template must be written in Python 3.x
The template must define a method called GenerateConfig(context) or
generate_config(context). If you use both method names in the same template,
the generate_config() method will take precedence.
The context object contains metadata about the deployment and your
environment, such as the deployment's name, the current project, and so on.
You'll use these deployment-specific variables in later steps.
cddeploymentmanager-samples/examples/v2/step_by_step_guide/step5_create_a_template/python
nanovm-template.py# use your preferred text editor
This template defines the first virtual machine (VM) from the earlier samples:
# 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}
Open the second template, vm-template-2.py, which defines the second 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}
In both templates, replace MY_PROJECT with your
project ID.
Importing templates
After you create templates, you must import them into your configuration. Open
the new two-vms.yaml:
cddeploymentmanager-samples/examples/v2/step_by_step_guide/step5_create_a_template/python
nanotwo-vms.yaml# use your preferred text editor
This configuration file has a new imports section that calls the two VM
templates, vm-template.py and 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
A note about resource names
When you use a template, your resource names are defined using the name field
provided in the template, not the name in the configuration file.
For example, in this case, the VM instances are created using the names in the
templates, the-first-vm and the-second-vm. The values vm-1 and vm-2,
defined in the configuration, are used to name an instantiation of the template,
but are not resource names.
In the next step, you combine templates so that your configuration only calls
one template to deploy all your resources.
Deleting your deployment
Before proceeding, we recommend that you delete the deployment to avoid charges.
You don't need this deployment for the next step. Run the following command to
delete the deployment:
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-21 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"]]