如何在Google Compute Engine上进行BigQuery身份验证?

5

当在Google Compute Engine实例上时,最简单的身份验证方式是什么?

涉及到Google BigQuery。
2个回答

3
在Python中: AppAssertionCredentials是一个Python类,允许计算引擎实例向Google和其他OAuth 2.0服务器自我识别,而不需要流程。

https://developers.google.com/api-client-library/python/

项目ID可以从元数据服务器读取,因此不需要将其设置为变量。

https://cloud.google.com/compute/docs/metadata

以下代码使用AppAssertionCredentials获取令牌,从元数据服务器获取项目ID,并使用此数据实例化BigqueryClient:
import bigquery_client
import urllib2
from oauth2client import gce

def GetMetadata(path):
  return urllib2.urlopen(
      'http://metadata/computeMetadata/v1/%s' % path,
      headers={'Metadata-Flavor': 'Google'}
      ).read()

credentials = gce.AppAssertionCredentials(
    scope='https://www.googleapis.com/auth/bigquery')

client = bigquery_client.BigqueryClient(
    credentials=credentials,
    api='https://www.googleapis.com',
    api_version='v2',
    project_id=GetMetadata('project/project-id'))

为了使此功能正常工作,您需要在创建GCE实例时为其授予对BigQuery API的访问权限:
gcloud compute instances create <your_instance_name> --scopes storage-ro bigquery 

3

首先,确保您的实例具有访问BigQuery的权限-您只能在创建时决定。

在bash脚本中,通过调用以下命令获取oauth令牌:

ACCESSTOKEN=`curl -s "http://metadata/computeMetadata/v1/instance/service-accounts/default/token" -H "X-Google-Metadata-Request: True" | jq ".access_token" | sed 's/"//g'`
echo "retrieved access token $ACCESSTOKEN"

现在假设你想要一个项目中数据集的列表:

CURL_URL="https://www.googleapis.com/bigquery/v2/projects/YOURPROJECTID/datasets"
CURL_OPTIONS="-s --header 'Content-Type: application/json' --header 'Authorization: OAuth $ACCESSTOKEN' --header 'x-goog-project-id:YOURPROJECTID' --header 'x-goog-api-version:1'"
CURL_COMMAND="curl --request GET $CURL_URL $CURL_OPTIONS"    
CURL_RESPONSE=`eval $CURL_COMMAND`

JSON格式的响应可以在变量CURL_RESPONSE中找到。
PS:我现在意识到这个问题被标记为Python,但是同样的原则适用。

谢谢您的答复,我也添加了 Bash 和 Curl 标签以便适当。 :) - Felipe Hoffa

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