凭证无效 - 尝试从 GCE 实例访问 Google 数据存储时出现 401

Invalid credentials - 401 when trying to access Google Datastore from a GCE instance

我正在尝试在此 URL 上找到的 adams.py 示例 https://cloud.google.com/datastore/docs/getstarted/start_python/

如本 URL 中所述:

If you are running this code on Google Compute Engine, you do not have to create new service account credentials because the default service account for your project is used when you create an instance with the datastore and userinfo-email scopes.

创建我的实例时,我选中了选项:

Allow API access to all Google Cloud services in the same project.

当我运行

python adams.py my-instance

我得到:

    ERROR:root:Error while doing datastore operation
    ERROR:root:RPCError: beginTransaction Invalid Credentials
    ERROR:root:HTTPError: 401 Unauthorized

事实上,即使我为实例使用了错误的名称,我也会收到相同的消息。

我的问题似乎与一年前的这个帖子类似:Connect google datastore from existing google compute engine in python

在我自己的代码中,它可以很好地访问 BigQuery,然后当涉及到 Datastore 时,它​​会引发相同的错误,但至少更具体地解决了该行,即最后一个:resp = datastore.commit(要求)。这是使用 Datastore 的代码部分。

req = datastore.CommitRequest()
req.mode = datastore.CommitRequest.NON_TRANSACTIONAL
dsDashboard = req.mutation.insert_auto_id.add()

path_element = dsDashboard.key.path_element.add()
path_element.kind = 'Dashboard'
fmt = '%Y-%m-%d'
dashboardDate = dsDashboard.property.add()
dashboardDate.name = 'Date'
dashboardDate.value.string_value = dtDay.strftime(fmt)

dashboardValue = dsDashboard.property.add()
dashboardValue.name = 'Value'
dashboardValue.value.indexed = False
dashboardValue.value.string_value = encode(jDashboard)

resp = datastore.commit(req)

我的代码错误:

    Traceback (most recent call last):
      File "code.py", line 262, in <module>
        main()
      File "code.py", line 256, in main
        resp = datastore.commit(req)
      File "/usr/local/lib/python2.7/dist-packages/googledatastore/__init__.py", line 90, in commit
        return get_default_connection().commit(request)
      File "/usr/local/lib/python2.7/dist-packages/googledatastore/connection.py", line 135, in commit
        datastore_v1_pb2.CommitResponse)
      File "/usr/local/lib/python2.7/dist-packages/googledatastore/connection.py", line 195, in _call_method
        raise RPCError(method, response, content)
    googledatastore.connection.RPCError: commit RPC client failure with HTTP(401) Unauthorized: Invalid Credentials    

总之,做起来似乎很简单。这里有人遇到同样的问题并且找到了解决方法吗?

这里的问题是:

While creating my instance, I checked the option:

Allow API access to all Google Cloud services in the same project.

人们会认为这会使您的实例获得所有范围,但它似乎无法正常工作。我试过了,如果你检查一个新创建的实例:

gcloud compute instances describe my-instance

你会看到它只有一个作用域

scopes:
  - https://www.googleapis.com/auth/cloud-platform

这里的解决方案是

  • 在通过开发者控制台创建实例时手动启用“用户信息”和“云数据存储”(“管理、磁盘、网络、访问和安全选项”>“访问和安全”)
  • 确保在使用 gcloud 命令时使用正确的范围标志(--scopes datastore,userinfo-email),如 Getting started with Google Cloud Datastore and Python/Protobuf 文章
  • 中所述