הסבר על תבניות לשימוש חוזר

כשמפתחים אפליקציה, בדרך כלל צריך ארכיטקטורות מורכבות. כדי שיהיה קל יותר לשכפל את הפריסה ולפתור בה בעיות, מומלץ לפצל את ההגדרות לתבניות.

תבנית היא קובץ נפרד שמגדיר קבוצה של משאבים. אפשר להשתמש בתבניות בפריסות שונות, וכך ליצור עקביות בפריסות מורכבות.

אתם יכולים להשתמש ב-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-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 במזהה הפרויקט.

ייבוא תבניות

אחרי שיוצרים תבניות, צריך לייבא אותן להגדרות האישיות. פותחים את 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, שקורא לשתי התבניות של המכונות הווירטואליות, vm-template.py ו-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.

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-vm ו-the-second-vm. הערכים vm-1 ו-vm-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