Cloud Deployment Manager akan mencapai akhir dukungan pada 31 Desember 2025. Jika saat ini Anda menggunakan Deployment Manager, migrasikan ke Infrastructure Manager atau teknologi deployment alternatif paling lambat 31 Desember 2025 untuk memastikan layanan Anda berlanjut tanpa gangguan.
Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Saat mengembangkan aplikasi, kemungkinan besar Anda memerlukan arsitektur yang kompleks. Untuk
memudahkan deployment direplikasi dan dipecahkan masalahnya, sebaiknya
bagi konfigurasi Anda menjadi template.
Template adalah file terpisah yang menentukan sekumpulan resource. Anda dapat menggunakan kembali template di berbagai deployment, yang menciptakan konsistensi di seluruh deployment yang kompleks.
Anda dapat menggunakan Python atau Jinja2 untuk membuat template bagi Deployment Manager.
Sebaiknya gunakan template Python, karena Python memberikan fleksibilitas yang lebih besar dan lebih banyak fitur saat Anda menskalakan aplikasi.
Template Python
Jika Anda memilih untuk menulis template di Python, template Anda harus memenuhi persyaratan berikut:
Template harus ditulis dalam Python 3.x
Template harus menentukan metode yang disebut GenerateConfig(context) atau
generate_config(context). Jika Anda menggunakan kedua nama metode dalam template yang sama, metode generate_config() akan diprioritaskan.
Objek context berisi metadata tentang deployment dan lingkungan Anda, seperti nama deployment, project saat ini, dan sebagainya.
Anda akan menggunakan variabel khusus deployment ini pada langkah-langkah berikutnya.
cddeploymentmanager-samples/examples/v2/step_by_step_guide/step5_create_a_template/python
nanovm-template.py# use your preferred text editor
Template ini menentukan virtual machine (VM) pertama dari contoh sebelumnya:
# 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}
Buka template kedua, vm-template-2.py, yang menentukan VM kedua:
# 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}
Di kedua template, ganti MY_PROJECT dengan project ID Anda.
Mengimpor template
Setelah membuat template, Anda harus mengimpornya ke dalam konfigurasi. Buka
two-vms.yaml baru:
cddeploymentmanager-samples/examples/v2/step_by_step_guide/step5_create_a_template/python
nanotwo-vms.yaml# use your preferred text editor
File konfigurasi ini memiliki bagian imports baru yang memanggil dua template VM, vm-template.py dan 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
Catatan tentang nama resource
Saat Anda menggunakan template, nama resource ditentukan menggunakan kolom name yang disediakan dalam template, bukan nama dalam file konfigurasi.
Misalnya, dalam kasus ini, instance VM dibuat menggunakan nama dalam template, the-first-vm dan the-second-vm. Nilai vm-1 dan vm-2,
yang ditentukan dalam konfigurasi, digunakan untuk memberi nama instansiasi template,
tetapi bukan nama resource.
Menyimpan konfigurasi dan men-deploy-nya
Untuk men-deploy konfigurasi, jalankan perintah ini:
Pada langkah berikutnya, Anda akan menggabungkan template sehingga konfigurasi hanya memanggil satu template untuk men-deploy semua resource.
Menghapus deployment Anda
Sebelum melanjutkan, sebaiknya hapus deployment untuk menghindari biaya.
Anda tidak memerlukan deployment ini untuk langkah berikutnya. Jalankan perintah berikut untuk menghapus deployment:
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Sulit dipahami","hardToUnderstand","thumb-down"],["Informasi atau kode contoh salah","incorrectInformationOrSampleCode","thumb-down"],["Informasi/contoh yang saya butuhkan tidak ada","missingTheInformationSamplesINeed","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],["Terakhir diperbarui pada 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"]]