O Cloud Deployment Manager vai chegar ao fim do suporte em 31 de dezembro de 2025. Se você usa o Deployment Manager, migre para o Infrastructure Manager ou uma tecnologia de implantação alternativa até 31 de dezembro de 2025 para garantir que seus serviços continuem sem interrupções.
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Ao desenvolver um aplicativo, você provavelmente precisará de arquiteturas complexas. Para
facilitar a replicação e a solução de problemas na implantação, recomendamos que você
divida a configuração em modelos.
Um modelo é um arquivo separado que define um conjunto de recursos. É possível reutilizar modelos em diferentes implantações, o que gera consistência em implantações complexas.
É possível usar o Python ou o Jinja2 para criar modelos para o Deployment Manager.
Recomendamos o uso de modelos Python porque ele fornece maior
flexibilidade e mais recursos conforme você dimensiona seu aplicativo.
Modelos no Python
Para gravar modelos no Python, eles precisam atender a estes requisitos:
O modelo deve ser escrito em Python 3.x
É preciso que seja definido pelo modelo um método chamado GenerateConfig(context) ou generate_config(context). Se você usar os dois nomes de método no mesmo modelo, o método generate_config() terá precedência.
O objeto context contém metadados sobre a implantação e seu ambiente, como o nome da implantação, o projeto atual e assim por diante.
Você usará essas variáveis específicas da implantação nas etapas posteriores.
cddeploymentmanager-samples/examples/v2/step_by_step_guide/step5_create_a_template/python
nanovm-template.py# use your preferred text editor
Este modelo define a primeira máquina virtual (VM) das amostras 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}
Abra o segundo modelo, vm-template-2.py, que define a 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}
Em ambos os modelos, substitua MY_PROJECT pelo ID do projeto.
Como importar modelos
Depois de criar modelos, você precisa importá-los para sua configuração. Abra o novo two-vms.yaml:
cddeploymentmanager-samples/examples/v2/step_by_step_guide/step5_create_a_template/python
nanotwo-vms.yaml# use your preferred text editor
Este arquivo de configuração tem uma nova seção imports que chama os dois modelos de VM, vm-template.py e 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
Uma observação sobre nomes de recursos
Quando você usa um modelo, os nomes dos recursos são definidos usando o campo name
fornecido no modelo, não o nome no arquivo de configuração.
Por exemplo, nesse caso, as instâncias de VM são criadas usando os nomes nos
modelos the-first-vm e the-second-vm. Os valores vm-1 e vm-2,
definidos na configuração, são usados para nomear uma instância do modelo,
mas não são nomes de recurso.
Como salvar e implantar a configuração
Para implantar a configuração, execute este comando:
Na próxima etapa, combine modelos para que sua configuração chame apenas um modelo para implantar todos os recursos.
Como excluir a implantação
Antes de continuar, recomendamos que você exclua a implantação para evitar cobranças.
Você não precisa desta implantação para a próxima etapa. Execute o seguinte comando para excluir a implantação:
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 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"]]