Informazioni sui modelli riutilizzabili

Durante lo sviluppo di un'app, molto probabilmente hai bisogno di architetture complesse. A semplificare la replica e la risoluzione dei problemi del deployment, ti consigliamo suddividere la configurazione in modelli.

Un modello è un file separato che definisce un insieme di risorse. Puoi riutilizzare di modelli in diversi deployment, in modo da garantire coerenza tra i modelli deployment di machine learning.

Puoi utilizzare Python o Jinja2 per creare modelli per Deployment Manager. Ti consigliamo di utilizzare i modelli Python, perché Python consente una maggiore flessibilità e più funzionalità man mano che scala la tua app.

Modelli Python

Se scegli di scrivere modelli in Python, i modelli devono soddisfare questi requisiti:

  • Il modello deve essere scritto in Python 3.x

  • Il modello deve definire un metodo chiamato GenerateConfig(context) o generate_config(context). Se utilizzi entrambi i nomi di metodi nello stesso modello, il metodo generate_config() avrà la precedenza.

    L'oggetto context contiene metadati sul deployment e su dell'ambiente di deployment, ad esempio il nome del deployment, il progetto attuale e così via. Utilizzerai queste variabili specifiche del deployment nei passaggi successivi.

  • Il metodo deve restituire un dizionario Python.

Analisi dei modelli di esempio

Dal repository di esempi, apri 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

Questo modello definisce la prima macchina virtuale (VM) dagli esempi precedenti:

# 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}

Apri il secondo modello, vm-template-2.py, che definisce la seconda 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}

In entrambi i modelli, sostituisci MY_PROJECT con il tuo dell'ID progetto.

Importazione di modelli

Dopo aver creato i modelli, devi importarli nella configurazione. Aperto il nuovo 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

Questo file di configurazione ha una nuova sezione imports che chiama le due VM modelli, vm-template.py e 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

Una nota sui nomi delle risorse

Quando utilizzi un modello, i nomi delle risorse vengono definiti utilizzando il campo name fornito nel modello, non il nome nel file di configurazione.

In questo caso, ad esempio, le istanze VM vengono create utilizzando i nomi in modelli, the-first-vm e the-second-vm. I valori vm-1 e vm-2, definiti nella configurazione, vengono utilizzati per assegnare un nome a un'istanza del modello, ma non sono nomi di risorse.

Salvataggio e deployment della configurazione in corso...

Per eseguire il deployment della configurazione, esegui questo comando:

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

Per visualizzare il deployment, esegui questo comando:

gcloud deployment-manager deployments describe deployment-with-templates

Prospettive future: utilizzo di più modelli

Nel passaggio successivo, combinerai i modelli in modo che la tua configurazione chiami solo un modello per eseguire il deployment di tutte le risorse.

Eliminazione del deployment in corso...

Prima di procedere, ti consigliamo di eliminare il deployment per evitare addebiti. Questo deployment non è necessario per il passaggio successivo. Esegui questo comando per elimina il deployment:

gcloud deployment-manager deployments delete deployment-with-templates