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

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

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

אפשר להשתמש ב-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