템플릿 속성 설정 및 환경 변수 사용

배포에 템플릿을 사용할 때의 장점 중 하나는 커스텀 속성을 만들고 정의할 수 있어 영역, 리전, 프로젝트 간에 템플릿을 재사용할 수 있는 점입니다.

템플릿 속성은 임의의 변수입니다. 모든 구성 파일 또는 템플릿 파일에서 템플릿을 수정하지 않고 템플릿 속성 값을 제공할 수 있습니다. 따라서 템플릿 자체를 변경하지 않고 다양한 구성의 속성 값을 변경할 수 있습니다.

임의의 값을 참조하려면 템플릿에서 다음 구문을 사용합니다.

context.properties["property-name"]

템플릿 속성 외에도 배포 정보로 미리 채워진 배포별 환경 변수를 사용할 수 있습니다. 템플릿에서 환경 변수를 사용하면 고유한 배포 정보를 가져올 수 있습니다.

환경 변수를 호출하려면 다음 구문을 사용합니다.

context.env['variable-name']

유효한 환경 변수에는 배포 이름, 프로젝트 ID, 리소스의 이름 속성, 구성 유형이 포함됩니다. 환경 변수에 대해 자세히 알아보세요.

템플릿의 템플릿 속성 및 환경 변수

이 단계에서 vm-template.py는 템플릿 속성과 환경 변수의 이점을 보여줍니다. vm-template.py를 엽니다.

cd deploymentmanager-samples/examples/v2/step_by_step_guide/step7_use_environment_variables/python

nano vm-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/'

def GenerateConfig(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.pyfirewall-template.pycontext.env['name']을 호출하여 정의된 배포 이름을 사용합니다.

구성 배포

이 배포의 구성 파일을 보려면 다음 명령어를 실행합니다.

nano config-with-many-templates.yaml

변경사항을 저장하고 구성을 다시 배포하여 변수가 작동하는지 확인합니다.

gcloud deployment-manager deployments create deployment-with-template-properties --config config-with-many-templates.yaml

배포 삭제

요금이 청구되지 않도록 배포를 삭제하는 것이 좋습니다. 다음 단계에는 이 배포가 필요하지 않습니다. 다음 명령어를 실행하여 배포를 삭제합니다.

gcloud deployment-manager deployments delete deployment-with-template-properties

미리보기: 도우미 스크립트

다음으로 반복 태스크를 효율적으로 수행할 수 있는 도우미 스크립트를 알아봅니다.