הגדרת מאפייני תבנית ושימוש במשתני סביבה

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

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

כדי להפנות לערך שרירותי, משתמשים בתחביר הבא בתבנית:

context.properties["property-name"]

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

כדי לקרוא למשתנה סביבה, משתמשים בתחביר הבא:

context.env['variable-name']

משתני סביבה תקינים כוללים את שם הפריסה, מזהה הפרויקט, מאפיין השם של המשאב וסוג ההגדרה. מידע נוסף על משתני סביבה

מאפייני תבנית ומשתני סביבה בתבנית

בשלב הזה, vm-template.py מציג את היתרונות של מאפייני התבנית ומשתני הסביבה. פותחים את vm-template.py:

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

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

חלקים שונים בתבנית הוחלפו במאפייני תבנית ובמשתני סביבה. לדוגמה, מזהה הפרויקט מוחלף ב-context.env[project], כך שלא צריך להחליף את מזהה הפרויקט בתבניות באופן ידני.

בתגובות בקובץ מתוארים שינויים נוספים בתבנית.

# 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 = [{
      # `the-first-vm` is replaced with `context.env[`name`]`
      'name': context.env['name'],
      'type': 'compute.v1.instance',
      'properties': {
          # All occurrences of `us-central1-f` are replaced with
          # `context.properties[`zone`]. 
          # All occurrences of the project ID are replaced with 
          # `context.env[`project`]`.
          # `f1-micro` is replaced with `context.properties["machineType"].  
          '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-11'])
              }
          }],
          # `$(ref.a-new-network.selfLink)` is replaced with 
          # `$(ref.` + context.properties[`network`] + `selfLink)`.
          'networkInterfaces': [{
              'network': '$(ref.' + context.properties['network']
                         + '.selfLink)',
              'accessConfigs': [{
                  'name': 'External NAT',
                  'type': 'ONE_TO_ONE_NAT'
              }]
          }]
      }
  }]
  return {'resources': resources}

באופן דומה, network-template.py ו-firewall-template.py משתמשים בשם הפריסה בהגדרה שלהם, על ידי קריאה ל-context.env['name'].

פריסת ההגדרה

כדי להציג את קובץ התצורה של הפריסה הזו, מריצים את הפקודה הבאה:

nano config-with-many-templates.yaml

שומרים את השינויים ומפעילים מחדש את ההגדרה כדי לוודא שהמשתנים פועלים.

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

מחיקת הפריסה

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

gcloud deployment-manager deployments delete deployment-with-template-properties

במבט קדימה: סקריפטים מסייעים

בשלב הבא, נסביר על סקריפטים של עזרה לביצוע יעיל של משימות חוזרות.