8
votes

I have a Google App Engine web app that runs the majority of my site. However, for certain functions, I need a linux machine. I would like my Google App Engine app to automatically spin-up a Google Compute Instance on certain events.

I understand that you can add Google Compute instances using the Compute Engine REST API. However, in order to access the Google Compute REST API, you need to get an access token using the OAuth2 authentication process.

How can I programmatically get an access token from within Google App Engine?

It seems that all of the authentication methods require a window to appear so you can type in your username and password, which is impractical from within Google App Engine.

2
You can use a service accountvoscausa

2 Answers

3
votes

You should be able to use the service account associated with your project to authenticate to the Compute Engine API and launch VMs.

Documentation on service accounts suggests that the following python code should fetch a service account token.

import httplib2

import discovery
from oauth2client.appengine import AppAssertionCredentials
...
credentials = AppAssertionCredentials(
    scope='https://www.googleapis.com/auth/compute')
auth_http = credentials.authorize(httplib2.Http())
compute_service = discovery.build('compute', 'v1beta15', http=auth_http)

I'd thought that the Google I/O demo from this year where they built a video-sharing site was going to be available, but I don't see it on GitHub yet. There are a number of demos that use AppEngine to control GCE, but most of them seem to use the user's project and credentials, rather the app's own credentials.

Obviously, you probably don't want to spin up a VM on direct user input unless you've got a very large budget or some form of rate limiting in place, but it's quite helpful to spin up a VM now and then when you've got a lot of computation to do. (Transcoding, etc.)

4
votes

Here is a complete example of using service accounts and App Engine cron tasks to stop instances after they've been running for a while: (opposite of starting instances, but the authorization code will be the same)

https://github.com/GoogleCloudPlatform/compute-appengine-timeout-python

AppAssertionCredentials handles the access token using this code:

# Obtain App Engine AppAssertion credentials and authorize HTTP connection.
# https://developers.google.com/appengine/docs/python/appidentity/overview
credentials = AppAssertionCredentials(
    scope='https://www.googleapis.com/auth/compute')
HTTP = credentials.authorize(httplib2.Http(memcache))

# Build object for the 'v1beta15' version of the GCE API.
# https://developers.google.com/compute/docs/reference/v1beta13/
compute = build('compute', 'v1beta15', http=HTTP)