diff --git a/compute/api/__init__.py b/compute/api/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/compute/api/create_instance.py b/compute/api/create_instance.py new file mode 100644 index 00000000000..1b5126d383e --- /dev/null +++ b/compute/api/create_instance.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python + +# Copyright 2015 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. + +"""Example of using the Compute Engine API to create and delete instances. + +Creates a new compute engine instance and uses it to apply a caption to +an image. + + https://cloud.google.com/bigquery/querying-data#asyncqueries + +For more information, see the README.md under /bigquery. +""" + +import argparse +import os +import time + +from googleapiclient import discovery +from oauth2client.client import GoogleCredentials +from six.moves import input + + +# [START list_instances] +def list_instances(compute, project, zone): + result = compute.instances().list(project=project, zone=zone).execute() + return result['items'] +# [END list_instances] + + +# [START create_instance] +def create_instance(compute, project, zone, name, bucket): + source_disk_image = \ + "projects/debian-cloud/global/images/debian-7-wheezy-v20150320" + machine_type = "zones/%s/machineTypes/n1-standard-1" % zone + startup_script = open( + os.path.join( + os.path.dirname(__file__), 'startup-script.sh'), 'r').read() + image_url = "http://storage.googleapis.com/gce-demo-input/photo.jpg" + image_caption = "Ready for dessert?" + + config = { + 'name': name, + 'machineType': machine_type, + + # Specify the boot disk and the image to use as a source. + 'disks': [ + { + 'boot': True, + 'autoDelete': True, + 'initializeParams': { + 'sourceImage': source_disk_image, + } + } + ], + + # Specify a network interface with NAT to access the public + # internet. + 'networkInterfaces': [{ + 'network': 'global/networks/default', + 'accessConfigs': [ + {'type': 'ONE_TO_ONE_NAT', 'name': 'External NAT'} + ] + }], + + # Allow the instance to access cloud storage and logging. + 'serviceAccounts': [{ + 'email': 'default', + 'scopes': [ + 'https://www.googleapis.com/auth/devstorage.read_write', + 'https://www.googleapis.com/auth/logging.write' + ] + }], + + # Metadata is readable from the instance and allows you to + # pass configuration from deployment scripts to instances. + 'metadata': { + 'items': [{ + # Startup script is automatically executed by the + # instance upon startup. + 'key': 'startup-script', + 'value': startup_script + }, { + 'key': 'url', + 'value': image_url + }, { + 'key': 'text', + 'value': image_caption + }, { + 'key': 'bucket', + 'value': bucket + }] + } + } + + return compute.instances().insert( + project=project, + zone=zone, + body=config).execute() +# [END create_instance] + + +# [START delete_instance] +def delete_instance(compute, project, zone, name): + return compute.instances().delete( + project=project, + zone=zone, + instance=name).execute() +# [END delete_instance] + + +# [START wait_for_operation] +def wait_for_operation(compute, project, zone, operation): + print('Waiting for operation to finish...') + while True: + result = compute.zoneOperations().get( + project=project, + zone=zone, + operation=operation).execute() + + if result['status'] == 'DONE': + print("done.") + if 'error' in result: + raise Exception(result['error']) + return result + + time.sleep(1) +# [END wait_for_operation] + + +# [START run] +def main(project, bucket, zone, instance_name, wait=True): + credentials = GoogleCredentials.get_application_default() + compute = discovery.build('compute', 'v1', credentials=credentials) + + print('Creating instance.') + + operation = create_instance(compute, project, zone, instance_name, bucket) + wait_for_operation(compute, project, zone, operation['name']) + + instances = list_instances(compute, project, zone) + + print('Instances in project %s and zone %s:' % (project, zone)) + for instance in instances: + print(' - ' + instance['name']) + + print(""" +Instance created. +It will take a minute or two for the instance to complete work. +Check this URL: http://storage.googleapis.com/{}/output.png +Once the image is uploaded press enter to delete the instance. +""".format(bucket)) + + if wait: + input() + + print('Deleting instance.') + + operation = delete_instance(compute, project, zone, instance_name) + wait_for_operation(compute, project, zone, operation['name']) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('project_id', help='Your Google Cloud project ID.') + parser.add_argument( + 'bucket_name', help='Your Google Cloud Storage bucket name.') + parser.add_argument( + '--zone', + default='us-central1-f', + help='Compute Engine zone to deploy to.') + parser.add_argument( + '--name', default='demo-instance', help='New instance name.') + + args = parser.parse_args() + + main(args.project_id, args.bucket_name, args.zone, args.name) +# [END run] diff --git a/compute/api/create_instance_test.py b/compute/api/create_instance_test.py new file mode 100644 index 00000000000..8c69d2c778e --- /dev/null +++ b/compute/api/create_instance_test.py @@ -0,0 +1,28 @@ +# Copyright 2015, Google, Inc. +# 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. + +import tests + +from .create_instance import main + + +class TestComputeGettingStarted(tests.CloudBaseTest): + + def test_main(self): + with tests.capture_stdout(): + main( + self.project_id, + self.bucket_name, + 'us-central1-f', + 'test-instance', + wait=False) diff --git a/compute/api/startup-script.sh b/compute/api/startup-script.sh new file mode 100644 index 00000000000..b0afa8266b9 --- /dev/null +++ b/compute/api/startup-script.sh @@ -0,0 +1,40 @@ +#!/bin/bash + +# Copyright 2015 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. + +# [START startup_script] +apt-get update +apt-get -y install imagemagick + +# Use the metadata server to get the configuration specified during +# instance creation. Read more about metadata here: +# https://cloud.google.com/compute/docs/metadata#querying +IMAGE_URL=$(curl http://metadata/computeMetadata/v1/instance/attributes/url -H "X-Google-Metadata-Request: True") +TEXT=$(curl http://metadata/computeMetadata/v1/instance/attributes/text -H "X-Google-Metadata-Request: True") +CS_BUCKET=$(curl http://metadata/computeMetadata/v1/instance/attributes/bucket -H "X-Google-Metadata-Request: True") + +mkdir image-output +cd image-output +wget $IMAGE_URL +convert * -pointsize 30 -fill white -stroke black -gravity center -annotate +10+40 "$TEXT" output.png + +# Create a Google Cloud Storage bucket. +gsutil mb gs://$CS_BUCKET + +# Store the image in the Google Cloud Storage bucket and allow all users +# to read it. +gsutil cp -a public-read output.png gs://$CS_BUCKET/output.png + +# [END startup_script]