cddeploymentmanager-samples/examples/v2/step_by_step_guide/step7_use_environment_variables/python
nanovm-template.py# use your preferred text editor
範本的各個部分已替換為範本屬性和環境變數。舉例來說,專案 ID 已替換為 context.env[project],這樣您就不必手動替換範本中的專案 ID。
檔案中的註解說明範本的其他相關變更。
# 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(context):"""Creates the virtual machine with environment variables."""resources=[{# `the-first-vm` is replaced with `context.env[`name`]`'name':context.env['name'],'type':'compute.v1.instance','properties':{# All occurrences of `us-central1-f` are replaced with# `context.properties[`zone`]. # All occurrences of the project ID are replaced with # `context.env[`project`]`.# `f1-micro` is replaced with `context.properties["machineType"]. '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'])}}],# `$(ref.a-new-network.selfLink)` is replaced with # `$(ref.` + context.properties[`network`] + `selfLink)`.'networkInterfaces':[{'network':'$(ref.'+context.properties['network']+'.selfLink)','accessConfigs':[{'name':'External NAT','type':'ONE_TO_ONE_NAT'}]}]}}]return{'resources':resources}
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["難以理解","hardToUnderstand","thumb-down"],["資訊或程式碼範例有誤","incorrectInformationOrSampleCode","thumb-down"],["缺少我需要的資訊/範例","missingTheInformationSamplesINeed","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-09-03 (世界標準時間)。"],[[["\u003cp\u003eTemplates can use custom properties, which are arbitrary variables, allowing for template reuse across different zones, regions, and projects without modification.\u003c/p\u003e\n"],["\u003cp\u003eTemplate properties are referenced using the syntax \u003ccode\u003econtext.properties["property-name"]\u003c/code\u003e, enabling the changing of a property's value for various configurations without altering the template itself.\u003c/p\u003e\n"],["\u003cp\u003eIn addition to template properties, environment variables, pre-populated with information about the deployment, can be used in templates by calling them with \u003ccode\u003econtext.env['variable-name']\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eEnvironment variables can provide unique details about a deployment, such as the deployment name, project ID, resource name, and configuration type.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003evm-template.py\u003c/code\u003e file demonstrates how to replace static parts of a template with template properties and environment variables, making the templates more dynamic and reusable.\u003c/p\u003e\n"]]],[],null,["# Setting template properties and using environment variables\n\nOne advantage of using templates for your deployment is the ability to create\nand define custom properties, which let you reuse templates across zones,\nregions, and projects.\n\nTemplate properties are arbitrary variables. Any configuration file or\ntemplate file can provide a value for a template property without modifying the\ntemplate. Therefore, you can change a property's value for various\nconfigurations without changing the template itself.\n\nTo reference an arbitrary value, use this syntax in a template: \n\n context.properties[\"property-name\"]\n\nIn addition to template properties, you can also use environment variables\nspecific to your deployment, which are pre-populated with information about the\ndeployment. You can use environment variables in templates to get unique\ninformation about your deployment.\n\nYou call an environment variable by using this syntax: \n\n context.env['variable-name']\n\nValid environment variables include the deployment name, the project ID, the\nname property of your resource, and the type of your configuration.\n[Learn more about environment variables](/deployment-manager/docs/configuration/templates/use-environment-variables).\n\nTemplate properties and environment variables in a template\n-----------------------------------------------------------\n\nIn this step, `vm-template.py` shows the benefits of template properties and\nenvironment variables. Open `vm-template.py`: \n\n cd deploymentmanager-samples/examples/v2/step_by_step_guide/step7_use_environment_variables/python\n\n nano vm-template.py # use your preferred text editor\n\nVarious parts of the template have been replaced with template properties and\nenvironment variables. For example, the project ID is replaced with\n`context.env[project]`, so you don't have to manually replace the project ID in\nyour templates.\n\nThe comments in the file describe other changes to the template. \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(context):\n \"\"\"Creates the virtual machine with environment variables.\"\"\"\n\n resources = [{\n # `the-first-vm` is replaced with `context.env[`name`]`\n 'name': context.env['name'],\n 'type': 'compute.v1.instance',\n 'properties': {\n # All occurrences of `us-central1-f` are replaced with\n # `context.properties[`zone`]. \n # All occurrences of the project ID are replaced with \n # `context.env[`project`]`.\n # `f1-micro` is replaced with `context.properties[\"machineType\"]. \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 # `$(ref.a-new-network.selfLink)` is replaced with \n # `$(ref.` + context.properties[`network`] + `selfLink)`.\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 }\n }]\n return {'resources': resources}\n\nSimilarly, `network-template.py` and `firewall-template.py` use the deployment's\nname in their definition, by calling `context.env['name']`.\n\nDeploying the configuration\n---------------------------\n\nTo view the configuration file for this deployment, run the following command: \n\n nano config-with-many-templates.yaml\n\nSave your changes and redeploy your configuration to confirm the variables work. \n\n gcloud deployment-manager deployments create deployment-with-template-properties --config config-with-many-templates.yaml\n\nDeleting your deployment\n------------------------\n\nWe recommend that you delete the deployment to avoid charges. You don't need\nthis deployment for the next step. Run the following command to delete the\ndeployment: \n\n gcloud deployment-manager deployments delete deployment-with-template-properties\n\nLooking ahead: helper scripts\n-----------------------------\n\nNext, learn about helper scripts to efficiently perform repeated tasks."]]