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.
Quando você tiver uma implantação, poderá atualizá-la à medida que o aplicativo evolui. Use o
Deployment Manager para atualizar uma implantação:
adicionando ou removendo recursos da implantação;
atualizando algumas propriedades de recursos atuais na implantação.
O Deployment Manager usa as APIs de base dos serviços do Google Cloud para gerenciar recursos na implantação. O Deployment Manager pode atualizar os recursos atuais se houver um método update ou patch na API correspondente.
Implantar a configuração original
Nesta etapa, implante a configuração que você atualizará mais tarde. Navegue até a pasta no repositório do GitHub e implante a configuração:
A configuração implanta duas máquinas virtuais (VMs) que executam um script de inicialização.
O modelo de 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 with environment variables and startup script."""COMPUTE_URL_BASE='https://www.googleapis.com/compute/v1/'defGenerateConfig(context):"""Creates the virtual machine."""resources=[{'name':context.env['name'],'type':'compute.v1.instance','properties':{'zone':context.properties['zone'],'machineType':''.join([COMPUTE_URL_BASE,'projects/',context.env['project'],'/zones/',context.properties['zone'],'/machineTypes/',context.properties['machineType']]),'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.'+context.properties['network']+'.selfLink)','accessConfigs':[{'name':'External NAT','type':'ONE_TO_ONE_NAT'}]}],'metadata':{'items':[{'key':'startup-script','value':''.join(['#!/bin/bash\n','python -m SimpleHTTPServer 80'])}]}}}]return{'resources':resources}
No modelo atualizado, na seção metadata, o script de inicialização da VM foi alterado:
# 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 with environment variables and startup script."""COMPUTE_URL_BASE='https://www.googleapis.com/compute/v1/'defGenerateConfig(context):"""Creates the virtual machine."""resources=[{'name':context.env['name'],'type':'compute.v1.instance','properties':{'zone':context.properties['zone'],'machineType':''.join([COMPUTE_URL_BASE,'projects/',context.env['project'],'/zones/',context.properties['zone'],'/machineTypes/',context.properties['machineType']]),'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.'+context.properties['network']+'.selfLink)','accessConfigs':[{'name':'External NAT','type':'ONE_TO_ONE_NAT'}]}],'metadata':{'items':[{'key':'startup-script','value':''.join(['#!/bin/bash\n','INSTANCE=$(curl http://metadata.google.','internal/computeMetadata/v1/instance/','hostname -H "Metadata-Flavor: Google")\n','echo "<html><header><title>Hello from ','Deployment Manager!</title></header>','<body><h2>Hello from $INSTANCE</h2><p>','Deployment Manager bids you good day!</p>','</body></html>" > index.html\n','python -m SimpleHTTPServer 80\n'])}]}}}]return{'resources':resources}
Você usará esse modelo atualizado para alterar a implantação criada anteriormente.
Visualizar a atualização
Para visualizar a implantação atualizada, execute o comando update com uma sinalização --preview:
Para verificar se a atualização funcionou, você precisa primeiro reiniciar as instâncias para usar o novo script de inicialização. Restart the-first-vm:
gcloud compute instances reset the-first-vm
A instância pode levar algum tempo para iniciar novamente. Espere alguns minutos antes de verificar a alteração.
Abra um navegador e cole o endereço IP na barra de endereço para visitar sua instância.
Agora a página deve mostrar uma mensagem de boas-vindas dizendo "Deployment Manager bids you good day!"
Também é possível repetir essas etapas com the-second-vm e ver uma mensagem um pouco diferente.
Excluir a implantação
Assim como nas etapas anteriores, recomendamos que você exclua a implantação para evitar cobranças. 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\u003eDeployment Manager allows you to update a deployment by adding or removing resources, or by updating properties of existing resources, using the underlying Google Cloud APIs.\u003c/p\u003e\n"],["\u003cp\u003eTo update a deployment, you first deploy an initial configuration which will later be modified, such as deploying two virtual machines (VMs) running a startup script.\u003c/p\u003e\n"],["\u003cp\u003eThe process involves opening and modifying an updated template where a specific aspect of the initial setup is changed, as demonstrated by changing the startup script for a virtual machine.\u003c/p\u003e\n"],["\u003cp\u003eBefore finalizing the update, you can preview the changes to the deployment to ensure they align with your expectations, followed by committing the update.\u003c/p\u003e\n"],["\u003cp\u003eAfter committing the update, it's necessary to restart the affected instances and then confirm the update has been applied by examining the instance, such as by checking for the new welcome message in this example.\u003c/p\u003e\n"]]],[],null,["# Updating a deployment\n\nAfter you have a deployment, you can update it as your app evolves. You can use\nDeployment Manager to update a deployment by:\n\n- Adding or removing resources to the deployment\n- Updating some properties of existing resources in your deployment\n\nDeployment Manager uses the underlying APIs of Google Cloud services\nto manage resources in your deployment. Deployment Manager can update\nexisting resources if there is an `update` or `patch` method in the\ncorresponding API.\n\nDeploy the original configuration\n---------------------------------\n\nIn this step, deploy the configuration that you will update later. Navigate to\nthe folder in the GitHub repository, and deploy the configuration: \n\n cd deploymentmanager-samples/examples/v2/step_by_step_guide/step8_metadata_and_startup_scripts/python\n\n gcloud deployment-manager deployments create deployment-to-update --config config-with-many-templates.yaml\n\nThe configuration deploys two virtual machines (VMs) that run a startup script.\nThe VM template is: \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 with environment variables and startup script.\"\"\"\n\n\n COMPUTE_URL_BASE = 'https://www.googleapis.com/compute/v1/'\n\n\n def GenerateConfig(context):\n \"\"\"Creates the virtual machine.\"\"\"\n\n resources = [{\n 'name': context.env['name'],\n 'type': 'compute.v1.instance',\n 'properties': {\n 'zone': context.properties['zone'],\n 'machineType': ''.join([COMPUTE_URL_BASE, 'projects/',\n context.env['project'], '/zones/',\n context.properties['zone'], '/machineTypes/',\n context.properties['machineType']]),\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.' + context.properties['network']\n + '.selfLink)',\n 'accessConfigs': [{\n 'name': 'External NAT',\n 'type': 'ONE_TO_ONE_NAT'\n }]\n }],\n 'metadata': {\n 'items': [{\n 'key': 'startup-script',\n 'value': ''.join(['#!/bin/bash\\n',\n 'python -m SimpleHTTPServer 80'])\n }]\n }\n }\n }]\n return {'resources': resources}\n\nOpen the updated template\n-------------------------\n\nNow, open the updated template: \n\n cd deploymentmanager-samples/examples/v2/step_by_step_guide/step9_update_a_deployment/python\n\n nano vm-template.py\n\nIn the updated template, in the `metadata` section, the VM's startup script\nhas been changed: \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 with environment variables and startup script.\"\"\"\n\n\n COMPUTE_URL_BASE = 'https://www.googleapis.com/compute/v1/'\n\n\n def GenerateConfig(context):\n \"\"\"Creates the virtual machine.\"\"\"\n\n resources = [{\n 'name': context.env['name'],\n 'type': 'compute.v1.instance',\n 'properties': {\n 'zone': context.properties['zone'],\n 'machineType': ''.join([COMPUTE_URL_BASE, 'projects/',\n context.env['project'], '/zones/',\n context.properties['zone'], '/machineTypes/',\n context.properties['machineType']]),\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.' + context.properties['network']\n + '.selfLink)',\n 'accessConfigs': [{\n 'name': 'External NAT',\n 'type': 'ONE_TO_ONE_NAT'\n }]\n }],\n 'metadata': {\n 'items': [{\n 'key': 'startup-script',\n 'value': ''.join(['#!/bin/bash\\n',\n 'INSTANCE=$(curl http://metadata.google.',\n 'internal/computeMetadata/v1/instance/',\n 'hostname -H \"Metadata-Flavor: Google\")\\n',\n 'echo \"\u003chtml\u003e\u003cheader\u003e\u003ctitle\u003eHello from ',\n 'Deployment Manager!\u003c/title\u003e\u003c/header\u003e',\n '\u003cbody\u003e\u003ch2\u003eHello from $INSTANCE\u003c/h2\u003e\u003cp\u003e',\n 'Deployment Manager bids you good day!\u003c/p\u003e',\n '\u003c/body\u003e\u003c/html\u003e\" \u003e index.html\\n',\n 'python -m SimpleHTTPServer 80\\n'])\n }]\n }\n }\n }]\n return {'resources': resources}\n\nYou will use this updated template to change the deployment you created.\n\nPreview the update\n------------------\n\nTo preview the updated deployment, run the `update` command with a `--preview`\nflag: \n\n gcloud deployment-manager deployments update deployment-to-update --config config-with-many-templates.yaml --preview\n\nCommit the update\n-----------------\n\nTo commit the update, run: \n\n gcloud deployment-manager deployments update deployment-to-update\n\nVerify the update\n-----------------\n\nTo check if the update worked, you must first restart the instances to use\nthe new startup script. Restart `the-first-vm`: \n\n gcloud compute instances reset the-first-vm\n\nThe instance might take some time to start back up. Wait a couple minutes before\nconfirming the change.\n\n### Confirm the new startup script\n\n1. Get the external IP of `the-first-vm`:\n\n gcloud compute instances describe the-first-vm | grep \"natIP\"\n\n2. Copy the value.\n\n3. Open a browser and paste the IP address into the address bar to visit your\n instance.\n\n The page should now show a welcome message that says\n \"Deployment Manager bids you good day!\"\n\nYou can also repeat these steps with `the-second-vm` and see a slightly\ndifferent message.\n\nDelete your deployment\n----------------------\n\nAs with previous steps, we recommend that you delete the deployment to avoid\ncharges. Run the following command to delete the deployment: \n\n gcloud deployment-manager deployments delete deployment-to-update\n\nWhat's next\n-----------\n\nHere are some areas to explore as you use Deployment Manager more:\n\n- [Explore more complex tutorials](/deployment-manager/docs/tutorials)\n- [Learn about available resource types](/deployment-manager/docs/configuration/supported-resource-types)\n- [Learn more about environment variables](/deployment-manager/docs/configuration/templates/use-environment-variables)\n- [Learn about importing Python libraries](/deployment-manager/docs/configuration/templates/import-python-libraries)\n- [Read the guidelines for preparing updates](/deployment-manager/docs/deployments/updating-deployments)"]]