Setting Metadata and Using Startup Scripts

When you are deploying more complex configurations, you might have tens, hundreds, or even thousands of virtual machine instances. If you’re familiar with Compute Engine, it’s likely that you want to use startup scripts to help install or configure your instances automatically.

Using Deployment Manager, you can run the same startup scripts or add metadata to virtual machine instances in your deployment by specifying the metadata in your template or configuration.

To add metadata or startup scripts to your template, add the metadata property and the relevant metadata keys and values. For example, for specifying a startup script, the metadata key must be startup-script and the value would be the contents of your startup script.

A template with a startup script looks like this:

resources:
- name: my-first-vm-template
  type: compute.v1.instance
  properties:
   zone: us-central1-f
   machineType:
   ...[snip]...
   metadata:
     items:
     - key: startup-script
       value: "STARTUP-SCRIPT-CONTENTS"

Let’s add a simple startup script to your template that starts an HTTP server. At the end, you should be able to visit the server running on your virtual machine instance.

Edit the VM template file

Add the following fields to the vm-template.[jinja|py] file, under the properties section:

Jinja

metadata:
  items:
  - key: startup-script
    value: |
      #!/bin/bash
      sudo python -m SimpleHTTPServer 80

Python

'metadata': {
  'items': [{
      'key': 'startup-script',
      'value': ''.join(['#!/bin/bash\n',
                        'python -m SimpleHTTPServer 80'])
  }]
 }

Your template should look like this:

Jinja

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

resources:
- name: {{ env["name"] }}
  type: compute.v1.instance
  properties:
    zone: {{ properties["zone"] }}
    machineType: https://www.googleapis.com/compute/v1/projects/{{ env["project"] }}/zones/{{ properties["zone"] }}/machineTypes/{{ properties["machineType"] }}
    disks:
    - deviceName: boot
      type: PERSISTENT
      boot: true
      autoDelete: true
      initializeParams:
        sourceImage: https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/family/debian-9
    networkInterfaces:
    - network: $(ref.{{ properties["network"] }}.selfLink)
      accessConfigs:
      - name: External NAT
        type: ONE_TO_ONE_NAT
    metadata:
      items:
      - key: startup-script
        value: |
          #!/bin/bash
          python -m SimpleHTTPServer 80

Python

# 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 with environment variables and startup script."""


COMPUTE_URL_BASE = 'https://www.googleapis.com/compute/v1/'


def GenerateConfig(context):
  """Creates the virtual machine."""

  resources = [{
      'name': context.env['name'],
      'type': 'compute.v1.instance',
      'properties': {
          '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-9'])
              }
          }],
          'networkInterfaces': [{
              'network': '$(ref.' + context.properties['network']
                         + '.selfLink)',
              'accessConfigs': [{
                  'name': 'External NAT',
                  'type': 'ONE_TO_ONE_NAT'
              }]
          }],
          'metadata': {
              'items': [{
                  'key': 'startup-script',
                  'value': ''.join(['#!/bin/bash\n',
                                    'python -m SimpleHTTPServer 80'])
              }]
          }
      }
  }]
  return {'resources': resources}

Save your changes.

Redeploy your configuration

gcloud deployment-manager deployments create deployment-with-startup-script --config config-with-many-templates.yaml

Test your startup script

  1. Get the external IP of the-first-vm:

    gcloud compute instances describe the-first-vm | grep "natIP"
    
  2. Copy the natIP value.

  3. Open a browser and paste the IP address into the address bar.

If successful, you should see a directory listing of the files on your virtual machine.

For more information on startup scripts, read the Startup Scripts documentation.

Don't delete your deployment!

Unlike all the other sections of this guide, keep this deployment around because you will need it for the next step!

Next: Update a Deployment

Related topics

Var denne siden nyttig? Si fra hva du synes:

Send tilbakemelding om ...

Cloud Deployment Manager Documentation