이 단계에서 vm-template.py는 템플릿 속성과 환경 변수의 이점을 보여줍니다. vm-template.py를 엽니다.
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}
마찬가지로 network-template.py 및 firewall-template.py는 context.env['name']을 호출하여 정의된 배포 이름을 사용합니다.
[[["이해하기 쉬움","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(UTC)"],[[["\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."]]