再利用可能なテンプレートについて

アプリの開発では、複雑なアーキテクチャが必要になることが少なくありません。デプロイの複製やトラブルシューティングを簡単に行えるように、構成をテンプレートに分割することをおすすめします。

テンプレートとは、一連のリソースを定義する独立したファイルです。デプロイ間でテンプレートを再利用すると、複雑なデプロイ間で一貫性を維持できます。

Deployment Manager のテンプレートを作成するには、Python または Jinja2 を使用します。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}

2 つ目のテンプレート vm-template-2.py を開き、2 つ目の 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 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

この構成ファイルに imports セクションが追加されます。これにより、2 つの VM テンプレート(vm-template.pyvm-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.

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 フィールドで定義されます。

たとえば、この場合は、テンプレート内の名前(the-first-vmthe-second-vm)を使用して VM インスタンスが作成されています。値 vm-1vm-2 はテンプレートのインスタンス化に使用されますが、リソース名ではありません。

構成の保存とデプロイ

構成をデプロイするには、次のコマンドを実行します。

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

デプロイを表示するには、次のコマンドを実行します。

gcloud deployment-manager deployments describe deployment-with-templates

次のステップ: 複数のテンプレートを使用する

1 つのテンプレートだけですべてのリソースをデプロイできるように、テンプレートを結合します。

デプロイの削除

次に進む前に、費用の発生を防ぐため、デプロイを削除することをおすすめします。このデプロイは次のステップで必要ありません。次のコマンドを実行して、デプロイを削除します。

gcloud deployment-manager deployments delete deployment-with-templates