【问题标题】:Google Cloud Service Account VS. End User Account谷歌云服务帐号 VS。最终用户帐户
【发布时间】:2019-03-15 02:50:41
【问题描述】:

我目前正在学习 GCP,需要在 VM 实例中运行 python 笔记本。打开我的 VM 的 shell 时,我运行了以下代码:

sudo install python-pip
pip install --upgrade google-api-python-client
pip install --upgrade google-cloud-datastore
gcloud auth application-default login

然后我加载了我的 python 笔记本。运行此代码以启动笔记本时:

python mynotebook.py

我收到以下错误:

/home/rnby87/.local/lib/python2.7/site-packages/google/auth/_default.py:66: UserWarning: Your application has authenticated using end user credentials from Google Cloud SDK. We recommend that most server applications use service accounts instead. If your application continues to use end user credentials from Cloud SDK, you might receive a "quota exceeded" or "API not enabled" error. For more information about service accounts, see https://cloud.google.com/docs/authentication/warnings.warn(_CLOUD_SDK_CREDENTIALS_WARNING)

我正在运行 Google Cloud SDK 文档 (https://cloud.google.com/datastore/docs/datastore-api-tutorial) 中的 python 代码

from google.cloud import datastore 

def create_client(project_id):
     return datastore.Client(project_id)

非常感谢任何帮助!谢谢!

【问题讨论】:

    标签: python google-cloud-platform google-cloud-datastore gcloud google-cloud-iam


    【解决方案1】:

    对于 Google Cloud SDK 和 CLI,您应该使用服务帐户凭据。

    第 1 步:创建服务帐户并下载

    1. 登录 Google Cloud Console。
    2. 转到 IAM 和管理 -> 服务帐户
    3. 点击创建服务帐户
    4. 输入服务帐户名称和服务帐户说明
    5. 点击创建
    6. 在下一个屏幕服务帐户权限中,选择一个角色。
    7. 添加所需的角色。
    8. 点击继续
    9. 点击创建密钥
    10. 检查密钥类型的 JSON 单选按钮
    11. 将 json 文件保存到您的计算机。
    12. 由于您是在 VM 中运行,因此请上传到 VM。

    第 2 步:配置 gcloud 和 SDK 以使用服务帐号。

    您将需要服务帐户的电子邮件地址(也存储在 Json 文件中)和服务帐户文件名。

    从你的 VM 中的 shell 运行这个命令:

    gcloud auth activate-service-account SERVICE_ACCOUNT_EMAIL_ADDRESS --key-file=service_account_filename.json
    

    第 3 步:验证您的凭据是否有效:

    gcloud auth list

    您应该会在左列(指定帐户帐户)中看到带有星号的服务帐户。

    注意:由于您在 Google 虚拟机 (GCE) 实例中运行,因此高级用户通常会使用 Compute Engine 默认服务帐户作为凭据。我建议先学习如何使用服务帐号 Json 文件。

    第 4 步:指定服务帐号

    将环境变量GOOGLE_APPLICATION_CREDENTIALS 设置为指向您的服务帐户json 文件。这是一个示例,将路径更改为您的路径。

    对于 Linux:

    export GOOGLE_APPLICATION_CREDENTIALS="/home/username/[FILE_NAME].json"
    

    对于 Windows:

    set GOOGLE_APPLICATION_CREDENTIALS="c:\Users\username\[FILE_NAME].json"
    

    第 5 步:在创建服务客户端时可选择指定服务帐号:

    from google.cloud import datastore 
    
    def create_client(project_id):
         return datastore.Client(project_id).from_service_account_json('service_account_filename.json')
    

    【讨论】:

    • 谢谢!我这样做并添加了我的服务帐户,效果很好,但是在尝试运行我的 python 笔记本时仍然遇到同样的错误。有什么建议吗?
    • 我忘了添加最后的步骤 - 如何使用凭据。我更新了我的答案。
    • 谢谢!非常感谢您的帮助!
    猜你喜欢
    • 2019-05-23
    • 2022-01-14
    • 2020-06-28
    • 1970-01-01
    • 2018-07-25
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    相关资源
    最近更新 更多