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

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

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

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

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

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

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