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

템플릿은 커스텀 템플릿 속성 및 미리 정의된 환경 변수 사용도 지원하므로 영역, 지역, 심지어 지역 간에도 템플릿을 재사용할 수 있습니다.

예를 들어 템플릿에서 특정 영역 값을 하드코딩하는 대신 임의 템플릿 속성을 선언할 수 있습니다. 템플릿을 사용할 때마다 템플릿을 포함하고, 최상위 구성에 영역에 대한 값을 제공합니다.

템플릿에서 다음 구문을 사용하여 임의 템플릿 속성을 선언합니다.

Jinja

{{ properties["property-name"] }}

Python

context.properties["property-name"]

예를 들어 다음 템플릿은 zone, machineType, network 템플릿 속성을 설정합니다.

Jinja

resources:
- name: 'example'
  type: compute.v1.instance
  properties:
    zone: {{ properties["zone"] }}
    machineType: https://www.googleapis.com/compute/v1/projects/my-project/zones/{{ properties["zone"] }}/machineTypes/{{ properties["machineType"] }}
    disks:
    - deviceName: boot
      type: PERSISTENT
      boot: true
      autoDelete: true
      initializeParams:
        sourceImage: https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/family/debian-8
    networkInterfaces:
    - network: $(ref.{{ properties["network"] }}.selfLink)
      accessConfigs:
      - name: External NAT
        type: ONE_TO_ONE_NAT

Python

"""Creates the virtual machine."""

def GenerateConfig(context):
  """Creates the virtual machine with environment variables."""

  resources = [{
      'name': 'example',
      'type': 'compute.v1.instance',
      'properties': {
          'zone': context.properties['zone'],
          'machineType': ''.join(['https://www.googleapis.com/compute/v1/',
                                  'projects/my-project/zones/',
                                  context.properties['zone'], '/machineTypes/',
                                  context.properties['machineType']]),
          'disks': [{
              'deviceName': 'boot',
              'type': 'PERSISTENT',
              'boot': True,
              'autoDelete': True,
              'initializeParams': {
                  'sourceImage': ''.join(['https://www.googleapis.com/compute/v1/', 'projects/',
                                          'debian-cloud/global/',
                                          'images/family/debian-8'])
              }
          }],
          'networkInterfaces': [{
              'network': '$(ref.' + context.properties['network']
                         + '.selfLink)',
              'accessConfigs': [{
                  'name': 'External NAT',
                  'type': 'ONE_TO_ONE_NAT'
              }]
          }]
      }
  }]
  return {'resources': resources}

그런 후 최상위 구성 또는 상위 템플릿에서 이 템플릿 속성의 값을 설정합니다.

resources:
- name: the-first-vm
  type: vm-template.jinja
  properties:
    machineType: f1-micro # Sets the 'machineType' template property
    zone: us-central1-f # Sets the 'zone' template property
    network: example-network # Sets the 'network' template property
- name: the-second-vm
  ...

템플릿 속성 외에도 배포에 대한 특정 정보로 미리 채워진 환경 변수를 참조할 수도 있습니다. 유효한 환경 변수에는 배포 이름, 프로젝트 ID, 리소스의 이름 속성, 구성 유형이 포함됩니다. 각 환경 변수에 대한 자세한 내용은 환경 변수 문서를 참조하세요.

다음 구문을 사용하여 환경 변수를 참조할 수 있습니다.

Jinja

{{ env["variable-name"] }}

Python

context.env['variable-name']

예를 들어 다음 템플릿은 nameproject 환경 변수를 사용합니다.

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

resources:
- name: {{ env["name"] }}
  type: compute.v1.instance
  properties:
    zone: {{ properties["zone"] }}
    machineType: https://www.googleapis.com/compute/v1/projects/{{ env["project"] }}/zones/{{ properties["zone"] }}/machineTypes/{{ properties["machineType"] }}
    disks:
    - deviceName: boot
      type: PERSISTENT
      boot: true
      autoDelete: true
      initializeParams:
        sourceImage: https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/family/debian-9
    networkInterfaces:
    - network: $(ref.{{ properties["network"] }}.selfLink)
      accessConfigs:
      - name: External NAT
        type: ONE_TO_ONE_NAT

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.

"""Creates the virtual machine."""

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

def GenerateConfig(context):
  """Creates the virtual machine with environment variables."""

  resources = [{
      'name': context.env['name'],
      'type': 'compute.v1.instance',
      'properties': {
          '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-9'])
              }
          }],
          'networkInterfaces': [{
              'network': '$(ref.' + context.properties['network']
                         + '.selfLink)',
              'accessConfigs': [{
                  'name': 'External NAT',
                  'type': 'ONE_TO_ONE_NAT'
              }]
          }]
      }
  }]
  return {'resources': resources}

템플릿 속성 및 환경 변수를 활용하기 위해 템플릿을 변환해보세요.

vm-template.jinja 파일 편집

vm-template 파일을 열고 파일의 다음 부분을 적합한 템플릿 속성 및 환경 변수로 바꿉니다.

  1. the-first-vm을 다음으로 바꿉니다.

    Jinja

    {{ env["name"] }}
    

    Python

    context.env['name']
    

  2. 모든 프로젝트 ID를 다음과 같은 변수로 바꿉니다.

    Jinja

    {{ env["project"] }}
    

    Python

    context.env['project']
    

  3. 이제 영역을 바꿉니다. 모든 us-central1-f를 다음으로 바꿉니다.

    Jinja

    {{ properties["zone"] }}
    

    Python

    context.properties['zone']
    

  4. f1-micro를 다음으로 바꿉니다.

    Jinja

    {{ properties["machineType"] }}
    

    Python

    context.properties["machineType"]
    

  5. $(ref.a-new-network.selfLink)를 다음으로 바꿉니다.

    Jinja

    $(ref.{{ properties["network"] }}.selfLink)
    

    Python

    '$(ref.' + context.properties['network'] + '.selfLink)'
    

상태 확인을 위해 vm-template.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.
#}

resources:
- name: {{ env["name"] }}
  type: compute.v1.instance
  properties:
    zone: {{ properties["zone"] }}
    machineType: https://www.googleapis.com/compute/v1/projects/{{ env["project"] }}/zones/{{ properties["zone"] }}/machineTypes/{{ properties["machineType"] }}
    disks:
    - deviceName: boot
      type: PERSISTENT
      boot: true
      autoDelete: true
      initializeParams:
        sourceImage: https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/family/debian-9
    networkInterfaces:
    - network: $(ref.{{ properties["network"] }}.selfLink)
      accessConfigs:
      - name: External NAT
        type: ONE_TO_ONE_NAT

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.

"""Creates the virtual machine."""

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

def GenerateConfig(context):
  """Creates the virtual machine with environment variables."""

  resources = [{
      'name': context.env['name'],
      'type': 'compute.v1.instance',
      'properties': {
          '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-9'])
              }
          }],
          'networkInterfaces': [{
              'network': '$(ref.' + context.properties['network']
                         + '.selfLink)',
              'accessConfigs': [{
                  'name': 'External NAT',
                  'type': 'ONE_TO_ONE_NAT'
              }]
          }]
      }
  }]
  return {'resources': resources}

network-template.jinja 템플릿 편집

network-template.jinja 파일을 편집하고 a-new-network를 다음으로 바꿉니다.

Jinja

{{ env["name"] }}

Python

context.env['name']

상태 확인을 위해 네트워크 템플릿이 다음과 같이 표시되는지 확인합니다.

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

resources:
- name: {{ env["name"] }}
  type: compute.v1.network
  properties:
    IPv4Range: 10.0.0.1/16

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.

"""Creates the network."""

def GenerateConfig(context):
  """Creates the network with environment variables."""

  resources = [{
      'name': context.env['name'],
      'type': 'compute.v1.network',
      'properties': {
          'IPv4Range': '10.0.0.1/16'
      }
  }]
  return {'resources': resources}

변경사항을 저장합니다.

firewall-template.jinja 템플릿 편집

  1. 방화벽 이름을 다음으로 바꿉니다.

    Jinja

    {{ env["name"] }}
    

    Python

    context.env['name']
    

  2. $(ref.a-new-network.selfLink)를 다음으로 바꿉니다.

    Jinja

    $(ref.{{ properties["network"] }}.selfLink)
    

    Python

    '$(ref.' + context.properties['network'] + '.selfLink)'
    

상태 확인을 위해 방화벽 템플릿이 다음과 같이 표시되는지 확인합니다.

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

resources:
- name: {{ env["name"] }}
  type: compute.v1.firewall
  properties:
    network: $(ref.{{ properties["network"] }}.selfLink)
    sourceRanges: ["0.0.0.0/0"]
    allowed:
    - IPProtocol: TCP
      ports: ["80"]

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.

"""Creates the firewall."""

def GenerateConfig(context):
  """Creates the firewall with environment variables."""

  resources = [{
      'name': context.env['name'],
      'type': 'compute.v1.firewall',
      'properties': {
          'network': '$(ref.' + context.properties['network'] + '.selfLink)',
          'sourceRanges': ['0.0.0.0/0'],
          'allowed': [{
              'IPProtocol': 'TCP',
              'ports': [80]
          }]
      }
  }]
  return {'resources': resources}

변경사항을 저장합니다.

compute-engine-template.jinja 템플릿 편집

vm-template.[jinja|py] 템플릿을 사용하여 새로운 가상 머신 인스턴스 이름이 포함되도록 compute-engine-template.[jinja|py]를 업데이트합니다. vm-template-2.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.
#}

{% set  NETWORK_NAME = "once-upon-a-custom-network" %}

resources:
- name: the-first-vm
  type: vm-template.jinja
  properties:
    machineType: f1-micro
    zone: us-central1-f
    network: {{ NETWORK_NAME }}
- name: the-second-vm
  type: vm-template.jinja
  properties:
    machineType: g1-small
    zone: us-central1-f
    network: {{ NETWORK_NAME }}
- name: {{ NETWORK_NAME }}
  type: network-template.jinja
- name: {{ NETWORK_NAME }}-firewall
  type: firewall-template.jinja
  properties:
    network: {{ NETWORK_NAME }}

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.

"""Creates the Compute Engine."""

NETWORK_NAME = 'once-upon-a-custom-network'

def GenerateConfig(unused_context):
  """Creates the Compute Engine with multiple templates."""

  resources = [{
      'name': 'the-first-vm',
      'type': 'vm-template.py',
      'properties': {
          'machineType': 'f1-micro',
          'zone': 'us-central1-f',
          'network': NETWORK_NAME
      }
  }, {
      'name': 'the-second-vm',
      'type': 'vm-template.py',
      'properties': {
          'machineType': 'f1-micro',
          'zone': 'us-central1-f',
          'network': NETWORK_NAME
      }
  }, {
      'name': NETWORK_NAME,
      'type': 'network-template.py'
  }, {
      'name': NETWORK_NAME + '-firewall',
      'type': 'firewall-template.py',
      'properties': {
          'network': NETWORK_NAME
      }
  }]
  return {'resources': resources}

기본 템플릿에 name 환경 변수를 추가했기 때문에 Deployment Manager는 상위 템플릿(기본 템플릿을 호출하는 템플릿)에 정의된 이름을 사용하여 리소스 이름을 지정합니다. 여기에서 상위 템플릿은 compute-engine-template.[jinja|py]이므로, 가상 머신 인스턴스 이름은 the-first-vmthe-second-vm이 됩니다. Deployment Manager가 프로젝트 변수를 환경 변수로 자동으로 인식하고, 값을 자동으로 채우기 때문에 개발자가 프로젝트 변수를 정의할 필요가 없습니다.

compute-engine-template.[jinja|py]가 이제 더 길고 조금 더 복잡하지만, 훨씬 동적입니다. 템플릿 및 환경 변수 조합을 사용하면 이 템플릿을 재사용하여 완전한 Compute Engine 클러스터를 만들 수 있으며, 템플릿을 재사용할 때마다 머신 유형, 영역 사양, 네트워크 이름을 맞춤설정할 수 있습니다. 그러면 동일한 설정의 배포에 대해 동일 구성의 사본을 여러 개 만들 필요가 없습니다.

구성 파일 업데이트

이제 구성 파일 config-with-many-templates.yaml을 편집하고, vm-template-2.[jinja|py]를 가져오는 행을 삭제하여, 구성이 다음과 같이 표시되도록 합니다.

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.

imports:
- path: vm-template.jinja
- path: network-template.jinja
- path: firewall-template.jinja
- path: compute-engine-template.jinja

resources:
- name: compute-engine-setup
  type: compute-engine-template.jinja

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.

imports:
- path: vm-template.py
- path: network-template.py
- path: firewall-template.py
- path: compute-engine-template.py

resources:
- name: compute-engine-setup
  type: compute-engine-template.py

변경사항을 저장합니다. 필요한 경우 구성을 다시 배포하여 변수가 작동하는지 확인할 수 있습니다.

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

이제 템플릿에 메타데이터 및 시작 스크립트를 추가하는 방법을 살펴보겠습니다.

배포 삭제

Compute Engine 리소스는 비용이 부과됩니다. 이 배포는 이후 단계에 더 이상 필요하지 않으므로 삭제해야 합니다. 이 배포를 삭제하면 이 배포에 있는 모든 리소스도 삭제됩니다. 배포를 삭제하지 않으면 이후 예제와 충돌합니다.

이 배포를 삭제하려면 다음을 수행하세요.

gcloud deployment-manager deployments delete deployment-with-many-templates

다음: 메타데이터 및 시작 스크립트 설정

관련 주제

이 페이지가 도움이 되었나요? 평가를 부탁드립니다.

다음에 대한 의견 보내기...

Cloud Deployment Manager Documentation