OAuth:在Google App Engine内部启动Google Compute实例

8
我有一个谷歌应用引擎Web应用程序,它运行了我的大部分网站。然而,对于某些功能,我需要一台Linux机器。我希望我的谷歌应用引擎应用程序在某些事件发生时自动启动一个谷歌计算实例。 我知道您可以使用计算引擎REST API添加Google Compute实例。但是,为了访问Google Compute REST API,您需要使用OAuth2身份验证过程获取访问令牌。 如何在Google App Engine内编程地获取访问令牌? 似乎所有的身份验证方法都需要出现一个窗口,以便您可以输入用户名和密码,这在Google App Engine中是不切实际的。

您可以使用服务账户。 - voscausa
2个回答

4
这是一个完整的示例,演示如何使用服务账号和App Engine定期任务来在运行一段时间后停止实例(相当于启动实例的反向操作,但授权代码将相同):

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

AppAssertionCredentials处理访问令牌,使用这段代码

# 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)

3
你应该能够使用与项目关联的服务帐户来进行身份验证,以便访问Compute Engine API并启动VM。 服务帐户文档建议使用以下Python代码获取服务帐户令牌。
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)

我原以为今年的Google I/O演示中建立视频分享网站的内容会公开,但我在GitHub上未找到。有许多演示使用AppEngine控制GCE,但大多数似乎使用用户的项目和凭据,而不是应用程序自己的凭据。
显然,除非您有非常大的预算或某种形式的速率限制,否则您可能不希望在直接用户输入时启动VM,但是当您需要进行大量计算时偶尔启动VM非常有帮助。(转码等)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接