Maciej Strzelczyk | 1961461 | 2021-07-19 16:28:01 +0200 | [diff] [blame^] | 1 | #!/usr/bin/env python |
| 2 | |
| 3 | # Copyright 2015 Google Inc. All Rights Reserved. |
| 4 | # |
| 5 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | # you may not use this file except in compliance with the License. |
| 7 | # You may obtain a copy of the License at |
| 8 | # |
| 9 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | # |
| 11 | # Unless required by applicable law or agreed to in writing, software |
| 12 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | # See the License for the specific language governing permissions and |
| 15 | # limitations under the License. |
| 16 | |
| 17 | """Example of using the Compute Engine API to create and delete instances. |
| 18 | |
| 19 | Creates a new compute engine instance and uses it to apply a caption to |
| 20 | an image. |
| 21 | |
| 22 | For more information, see the README.md under samples/compute. |
| 23 | """ |
| 24 | |
| 25 | import argparse |
| 26 | import os |
| 27 | import time |
| 28 | |
| 29 | import googleapiclient.discovery |
| 30 | from six.moves import input |
| 31 | |
| 32 | |
| 33 | # [START compute_apiary_list_instances] |
| 34 | def list_instances(compute, project, zone): |
| 35 | result = compute.instances().list(project=project, zone=zone).execute() |
| 36 | return result['items'] if 'items' in result else None |
| 37 | # [END compute_apiary_list_instances] |
| 38 | |
| 39 | |
| 40 | # [START compute_apiary_create_instance] |
| 41 | def create_instance(compute, project, zone, name, bucket): |
| 42 | # Get the latest Debian Jessie image. |
| 43 | image_response = compute.images().getFromFamily( |
| 44 | project='debian-cloud', family='debian-9').execute() |
| 45 | source_disk_image = image_response['selfLink'] |
| 46 | |
| 47 | # Configure the machine |
| 48 | machine_type = "zones/%s/machineTypes/n1-standard-1" % zone |
| 49 | startup_script = open( |
| 50 | os.path.join( |
| 51 | os.path.dirname(__file__), 'startup-script.sh'), 'r').read() |
| 52 | image_url = "http://storage.googleapis.com/gce-demo-input/photo.jpg" |
| 53 | image_caption = "Ready for dessert?" |
| 54 | |
| 55 | config = { |
| 56 | 'name': name, |
| 57 | 'machineType': machine_type, |
| 58 | |
| 59 | # Specify the boot disk and the image to use as a source. |
| 60 | 'disks': [ |
| 61 | { |
| 62 | 'boot': True, |
| 63 | 'autoDelete': True, |
| 64 | 'initializeParams': { |
| 65 | 'sourceImage': source_disk_image, |
| 66 | } |
| 67 | } |
| 68 | ], |
| 69 | |
| 70 | # Specify a network interface with NAT to access the public |
| 71 | # internet. |
| 72 | 'networkInterfaces': [{ |
| 73 | 'network': 'global/networks/default', |
| 74 | 'accessConfigs': [ |
| 75 | {'type': 'ONE_TO_ONE_NAT', 'name': 'External NAT'} |
| 76 | ] |
| 77 | }], |
| 78 | |
| 79 | # Allow the instance to access cloud storage and logging. |
| 80 | 'serviceAccounts': [{ |
| 81 | 'email': 'default', |
| 82 | 'scopes': [ |
| 83 | 'https://www.googleapis.com/auth/devstorage.read_write', |
| 84 | 'https://www.googleapis.com/auth/logging.write' |
| 85 | ] |
| 86 | }], |
| 87 | |
| 88 | # Metadata is readable from the instance and allows you to |
| 89 | # pass configuration from deployment scripts to instances. |
| 90 | 'metadata': { |
| 91 | 'items': [{ |
| 92 | # Startup script is automatically executed by the |
| 93 | # instance upon startup. |
| 94 | 'key': 'startup-script', |
| 95 | 'value': startup_script |
| 96 | }, { |
| 97 | 'key': 'url', |
| 98 | 'value': image_url |
| 99 | }, { |
| 100 | 'key': 'text', |
| 101 | 'value': image_caption |
| 102 | }, { |
| 103 | 'key': 'bucket', |
| 104 | 'value': bucket |
| 105 | }] |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | return compute.instances().insert( |
| 110 | project=project, |
| 111 | zone=zone, |
| 112 | body=config).execute() |
| 113 | # [END compute_apiary_create_instance] |
| 114 | |
| 115 | |
| 116 | # [START compute_apiary_delete_instance] |
| 117 | def delete_instance(compute, project, zone, name): |
| 118 | return compute.instances().delete( |
| 119 | project=project, |
| 120 | zone=zone, |
| 121 | instance=name).execute() |
| 122 | # [END compute_apiary_delete_instance] |
| 123 | |
| 124 | |
| 125 | # [START compute_apiary_wait_for_operation] |
| 126 | def wait_for_operation(compute, project, zone, operation): |
| 127 | print('Waiting for operation to finish...') |
| 128 | while True: |
| 129 | result = compute.zoneOperations().get( |
| 130 | project=project, |
| 131 | zone=zone, |
| 132 | operation=operation).execute() |
| 133 | |
| 134 | if result['status'] == 'DONE': |
| 135 | print("done.") |
| 136 | if 'error' in result: |
| 137 | raise Exception(result['error']) |
| 138 | return result |
| 139 | |
| 140 | time.sleep(1) |
| 141 | # [END compute_apiary_wait_for_operation] |
| 142 | |
| 143 | |
| 144 | # [START compute_apiary_run] |
| 145 | def main(project, bucket, zone, instance_name, wait=True): |
| 146 | compute = googleapiclient.discovery.build('compute', 'v1') |
| 147 | |
| 148 | print('Creating instance.') |
| 149 | |
| 150 | operation = create_instance(compute, project, zone, instance_name, bucket) |
| 151 | wait_for_operation(compute, project, zone, operation['name']) |
| 152 | |
| 153 | instances = list_instances(compute, project, zone) |
| 154 | |
| 155 | print('Instances in project %s and zone %s:' % (project, zone)) |
| 156 | for instance in instances: |
| 157 | print(' - ' + instance['name']) |
| 158 | |
| 159 | print(""" |
| 160 | Instance created. |
| 161 | It will take a minute or two for the instance to complete work. |
| 162 | Check this URL: http://storage.googleapis.com/{}/output.png |
| 163 | Once the image is uploaded press enter to delete the instance. |
| 164 | """.format(bucket)) |
| 165 | |
| 166 | if wait: |
| 167 | input() |
| 168 | |
| 169 | print('Deleting instance.') |
| 170 | |
| 171 | operation = delete_instance(compute, project, zone, instance_name) |
| 172 | wait_for_operation(compute, project, zone, operation['name']) |
| 173 | |
| 174 | |
| 175 | if __name__ == '__main__': |
| 176 | parser = argparse.ArgumentParser( |
| 177 | description=__doc__, |
| 178 | formatter_class=argparse.RawDescriptionHelpFormatter) |
| 179 | parser.add_argument('project_id', help='Your Google Cloud project ID.') |
| 180 | parser.add_argument( |
| 181 | 'bucket_name', help='Your Google Cloud Storage bucket name.') |
| 182 | parser.add_argument( |
| 183 | '--zone', |
| 184 | default='us-central1-f', |
| 185 | help='Compute Engine zone to deploy to.') |
| 186 | parser.add_argument( |
| 187 | '--name', default='demo-instance', help='New instance name.') |
| 188 | |
| 189 | args = parser.parse_args() |
| 190 | |
| 191 | main(args.project_id, args.bucket_name, args.zone, args.name) |
| 192 | # [END compute_apiary_run] |