템플릿 모듈은 템플릿을 더 효율적으로 만들 수 있는 특정 기능을 수행하는 도우미 파일입니다. 예를 들어 리소스에 대해 고유 이름을 생성하는 모듈을 사용할 수 있습니다. Deployment Manager는 Python 또는 Jinja로 작성된 모든 모듈을 실행할 수 있습니다.
그런 후 이 템플릿을 가져와서 모듈로 사용할 수 있습니다. Jinja 템플릿에서는 다음과 같은 모듈을 사용할 수 있습니다.
# 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.{%import'helpers/common.jinja'ascommon%}resources:- name: {{ common.GenerateMachineName("myfrontend", "prod") }} type: compute.v1.instance properties: zone: us-central1-f machineType: https://www.googleapis.com/compute/v1/projects/{{ env['project'] }}/zones/us-central1-f/machineTypes/f1-micro disks: - deviceName: boot type: PERSISTENT boot: true autoDelete: true initializeParams: sourceImage: https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/family/debian-11 networkInterfaces: - network: https://www.googleapis.com/compute/v1/projects/{{ env['project'] }}/global/networks/default accessConfigs: - name: External NAT type: ONE_TO_ONE_NAT
그러면 구성에서 두 파일을 가져와야 합니다(helpers/common.jinja 파일 포함).
# Copyright 2015 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:helpers/common.jinja-path:vm-instance-example.jinjaresources:-name:my-vmtype:vm-instance-example.jinja
Deployment Manager 서비스가 구성을 확장하고 최종 구성이 다음과 같이 표시됩니다.
Python에서 도우미 템플릿(이 예시에서는 helpers/common.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."""Generates name of a VM."""defGenerateMachineName(prefix,suffix):returnprefix+"-"+suffix
이를 Python 템플릿에서 사용하려면 다음을 사용하세요.
# 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."""Constructs a VM with imported module."""fromhelpersimportcommonCOMPUTE_URL_BASE='https://www.googleapis.com/compute/v1/'defGenerateConfig(context):"""Generates configuration of a VM."""resources=[{'name':common.GenerateMachineName('myfrontend','prod'),'type':'compute.v1.instance','properties':{'zone':'us-central1-f','machineType':COMPUTE_URL_BASE+'projects/'+context.env['project']+'/zones/us-central1-f/machineTypes/f1-micro','disks':[{'deviceName':'boot','type':'PERSISTENT','boot':True,'autoDelete':True,'initializeParams':{'sourceImage':COMPUTE_URL_BASE+'projects/''debian-cloud/global/images/family/debian-11'}}],'networkInterfaces':[{'network':COMPUTE_URL_BASE+'projects/'+context.env['project']+'/global/networks/default','accessConfigs':[{'name':'External NAT','type':'ONE_TO_ONE_NAT'}]}]}}]return{'resources':resources}
그러면 구성에서 두 파일을 가져와야 합니다(helpers/common.py 파일 포함).
# Copyright 2015 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:helpers/common.py-path:vm-instance-example.pyresources:-name:my-vmtype:vm-instance-example.py
다음은 보다 복잡한 도우미 모듈입니다.
# Copyright 2015 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."""Helper methods for working with containers in config."""importcommonimportdefaultimportyaml# Specific properties for this component, also see container_instanceDCKRENV=default.DCKRENVDCKRIMAGE=default.DCKRIMAGEMANIFEST="""version: v1beta2containers: - name: %(name)s image: %(dockerImage)s ports: - name: %(name)s-port hostPort: %(port)i containerPort: %(port)i%(env)s"""defGenerateManifest(context):"""Generates a Container Manifest given a Template context. Args: context: Template context, which must contain dockerImage and port properties, and an optional dockerEnv property. Returns: A Container Manifest as a YAML string. """env=""env_list=[]ifDCKRENVincontext.properties:forkey,valueincontext.properties[DCKRENV].iteritems():env_list.append({"name":key,"value":value})ifenv_list:env="env: "+yaml.dump(env_list,default_flow_style=True)manifest_yaml_string=MANIFEST%{"name":context.env["name"],"dockerImage":context.properties[DCKRIMAGE],"port":context.properties[default.PORT],"env":env}returncommon.GenerateEmbeddableYaml(manifest_yaml_string)
[[["이해하기 쉬움","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\u003eTemplate modules are helper files that enhance template efficiency by performing specific functions, such as generating unique resource names.\u003c/p\u003e\n"],["\u003cp\u003eDeployment Manager can utilize template modules written in either Jinja or Python, offering flexibility in coding preference.\u003c/p\u003e\n"],["\u003cp\u003eA template module can be imported and used within other templates, like the example provided where a Jinja template uses a module to generate a machine name with a given prefix and suffix.\u003c/p\u003e\n"],["\u003cp\u003eThe configuration must import all used files, which include both the main template and any helper template modules, for the Deployment Manager service to properly expand it.\u003c/p\u003e\n"],["\u003cp\u003eThe same principles apply to modules in Python, and the content shows examples of using a python module to generate names in a python template, as well as a more complicated python module example.\u003c/p\u003e\n"]]],[],null,[]]