재사용 가능한 템플릿 이해

앱 개발 중에는 복잡한 아키텍처가 필요한 경우가 많습니다. 배포의 복제와 문제해결을 쉽게 만들려면 구성을 템플릿으로 분리하는 것이 좋습니다.

템플릿은 일련의 리소스를 정의하는 별도의 파일입니다. 여러 배포에서 템플릿을 재사용할 수 있어 복잡한 배포 사이에서 일관성을 유지할 수 있습니다.

Python 또는 Jinja2를 사용하여 Deployment Manager용 템플릿을 만들 수 있습니다. Python을 사용하면 앱을 확장할 때 유연성과 기능이 향상되므로 Python 템플릿을 사용하는 것이 좋습니다.

Python 템플릿

Python으로 템플릿을 작성할 경우 템플릿이 다음과 같은 요구사항을 충족해야 합니다.

  • 템플릿은 Python 3.x로 작성되어야 합니다.

  • 템플릿에서 GenerateConfig(context) 또는 generate_config(context)라는 메서드를 정의해야 합니다. 동일한 템플릿에서 두 메서드 이름을 모두 사용하면 generate_config() 메서드가 우선 적용됩니다.

    context 객체에는 배포에 대한 메타데이터와 배포 이름, 현재 프로젝트 등의 환경이 포함됩니다. 이후 단계에서 이러한 배포 관련 변수를 사용합니다.

  • 메서드가 Python 사전을 반환해야 합니다.

샘플 템플릿 살펴보기

샘플 저장소에서 vm-template.py를 엽니다.

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

nano vm-template.py  # use your preferred text editor

이 템플릿은 이전 샘플의 첫 번째 가상 머신(VM)을 정의합니다.

# 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(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}

두 번째 VM을 정의하는 두 번째 템플릿 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.

"""Creates the virtual machine."""

COMPUTE_URL_BASE = 'https://www.googleapis.com/compute/v1/'

def GenerateConfig(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}

두 템플릿 모두에서 MY_PROJECT를 프로젝트 ID로 바꿉니다.

템플릿 가져오기

템플릿을 만든 후에 구성으로 가져와야 합니다. 새 two-vms.yaml을 엽니다.

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

nano two-vms.yaml  # use your preferred text editor

이 구성 파일에는 VM 템플릿 두 개(vm-template.pyvm-template-2.py)를 호출하는 새로운 imports 섹션이 있습니다.

# 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-1
  type: vm-template.py
- name: vm-2
  type: vm-template-2.py
- name: a-new-network
  type: compute.v1.network
  properties:
    routingConfig:
      routingMode: REGIONAL
    autoCreateSubnetworks: true

리소스 이름에 대한 유의사항

템플릿을 사용할 때 리소스 이름은 템플릿에서 제공된 name 필드를 사용하여 정의되며 구성 파일에 있는 이름이 아닙니다.

예를 들어 이 경우 VM 인스턴스는 the-first-vmthe-second-vm 템플릿에 있는 이름을 사용하여 생성됩니다. 구성에서 정의된 vm-1vm-2 값은 템플릿의 인스턴스화 이름을 지정하는 데 사용되지만 리소스 이름에는 사용되지 않습니다.

구성 저장 및 배포

구성을 배포하려면 다음 명령어를 실행합니다.

gcloud deployment-manager deployments create deployment-with-templates --config two-vms.yaml

배포를 보려면 다음 명령어를 실행합니다.

gcloud deployment-manager deployments describe deployment-with-templates

미리보기: 여러 템플릿 사용

다음 단계에서 구성이 템플릿 한 개만 호출하여 모든 리소스를 배포할 수 있도록 템플릿을 결합합니다.

배포 삭제

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

gcloud deployment-manager deployments delete deployment-with-templates