1

I tried to replicate the following guide found on google's website https://cloud.google.com/compute/docs/tutorials/python-guide

I couldn't figure out what the bucket, and compute mean. What kind of parameter do I need to pass into the script? What should I put in the getFromFamily( project='debian-cloud', family='debian-8').execute() if I want to start my private image? and do I pass in the variable like the following?

create_instance(compute,projectname, us-east1-a, instance-1, bucket)

I have simplified the script as follows. Which I take out the parameter I don't think I need.

def create_instance(compute, project, zone, name, bucket):

image_response = compute.images().getFromFamily(
    project='debian-cloud', family='debian-8').execute()
source_disk_image = image_response['selfLink']

# Configure the machine
machine_type = "us-east1-b/%s/machineTypes/f1-micro" % zone
startup_script = open(
    os.path.join(
        os.path.dirname(__file__), 'startup-script.sh'), 'r').read()

config = {
    'name': instance-1,
    'machineType': f1-micro,

    # Specify the boot disk and the image to use as a source.
    'disks': [
        {
            'boot': True,
            'autoDelete': True,
            'initializeParams': {
                'sourceImage': /global/imagename,
            }
        }
    ],

    # 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',

        ]
    }],

    # 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': 'bucket',
            'value': bucket
        }]
    }
}

return compute.instances().insert(
    project=project,
    zone=zone,
    body=config).execute()
cherba
  • 8,681
  • 3
  • 27
  • 34
Stej
  • 29
  • 5

2 Answers2

3

This has been here some time, but here is some information.

The bucket is only required if you want your instances to have a shared storage location (doc here). If the bucket is not needed you should remove the metadata bucket key-value (although I was surprised to see that creating an instance with a fake bucket name will not fail).

compute is your authenticated client object for interacting with your 'Compute Engine' service. To obtain the client you need to follow these instructions to obtain the key, secret and refresh token. Here is a code example:

from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
from oauth2client import GOOGLE_TOKEN_URI
credentials = GoogleCredentials(access_token=None, client_id='your-client-id', 
                                client_secret='your-client-secret',
                                refresh_token='your-refresh-token',
                                token_expiry=None, token_uri=GOOGLE_TOKEN_URI,
                                user_agent='Python client library')
compute = discovery.build('compute', 'v1', credentials=credentials)

As for the private images, if you want to use the same code, then you need to locate and identify them in your GCE console and provide the project and family identifiers. You can also use the API to get image by name:

image = compute.images().get(project='your-project-id', image='your-image-name').execute(), where the same image['selfLink'] should be provided as the sourceImage in the instance config

mosh
  • 61
  • 4
1

The example is outdated: note oauth2client is now deprecated with Google Auth being the current client library. Here's an updated solution. Crucial step is to generate the correct updated json. This can be achieved by translating your intended instance with the equivalent REST command, under an authorized service account.

enter image description here

import google.auth
import googleapiclient.discovery
PROJECT_ID = "<your project ID>"
ZONE = "<your zone>"

credentials, _ = google.auth.default()
compute = googleapiclient.discovery.build('compute', 'v1', 
credentials=credentials)

config = "{generate your instance's json from equivalent REST}"

compute.instances().insert(project=PROJECT_ID, zone=ZONE, 
body=config).execute()
corticalhazard
  • 189
  • 2
  • 6