【问题标题】:How to auth into BigQuery on Google Compute Engine?如何在 Google Compute Engine 上授权进入 BigQuery?
【发布时间】:2014-10-01 00:54:05
【问题描述】:

在 Google Compute Engine 实例上向 Google BigQuery 进行身份验证的最简单方法是什么?

【问题讨论】:

    标签: python bash curl google-bigquery google-compute-engine


    【解决方案1】:

    首先确保您的实例具有访问 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`
    

    可以在变量 CURL_RESPONSE 中找到 JSON 格式的响应

    PS:我现在意识到这个问题被标记为 Python,但同样的原则也适用。

    【讨论】:

    • 感谢您的回答,我也添加了 bash 和 curl 标签以确保适当性:)
    【解决方案2】:

    在 Python 中:

    AppAssertionCredentials 是一个 python 类,它允许 Compute Engine 实例向 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 
    

    【讨论】:

      猜你喜欢
      • 2013-07-06
      • 2014-03-28
      • 2013-12-24
      • 2014-08-05
      • 1970-01-01
      • 2020-10-28
      • 1970-01-01
      • 2016-06-19
      • 2014-01-23
      相关资源
      最近更新 更多