libcloud 和 GCP。如何使用服务帐户进行身份验证

libcloud and GCP. How to autheticate using service account

我正在尝试使用 Apache libcloud 访问 GCP,希望能够启动计算实例。因此,根据文档,我在 GCP 上创建了一个与我的电子邮件关联的服务帐户,并暂时授予其所有者访问权限。之后,我使用 libcloud 如下:

from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
ComputeEngine = get_driver(Provider.GCE)

driver = ComputeEngine('luca@googlemail.com', 'gcp-key.json', project='first-gcp')

这实际上显示了一个 URL 并要求我从中输入一个代码。当我单击 URL 时,我收到错误消息:

The OAuth client was not found.

这不是我设想的工作流程。我认为提供密钥只会让我进入,然后我就可以使用方法来启动实例等。因此,我不确定通过在 GCP 上使用服务帐户来做这件事是否正确。

因此,我收到以下请求代码的请求:

所以我明白了:

Please Go to the following URL and sign in:

https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=xxx&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcompute+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdevstorage.full_control+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fndev.clouddns.readwrite&state=Libcloud+Request
Enter Code: 

我应该如何处理这个问题?最终我们将有一些远程人员来处理这个问题,所以理想情况下每个人都会有自己的密钥来使用,如果不需要手动输入代码,这应该以一种有点自主的方式发生,那就太好了。

从控制台 (https://cloud.google.com/console),select 您的项目。当您的项目打开时,select "APIs & auth" 然后 "Credentials" 如下所示:

正在开发中:最好每人制作一个,可以全部使用一个用于测试目的。

在生产中:为每个使用此服务的用户创建一个服务帐户。

当您下载服务帐户时,您应该将其作为 .pem.json 文件。使用服务帐户中的电子邮件地址(如果您打开 json/pem 您应该能够看到该电子邮件)并为其提供正确的值 region/project/email 和 pem 文件的路径。

您使用的代码是正确的,请避免使用名称 "ComputeEngine",因为它可能是关键字(即使它可能不是,最佳做法)

from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
Driver = get_driver(Provider.GCE)
gce = Driver('your_service_account_email', 'path_to_pem_file',
             datacenter='us-central1-a',
             project='your_project_id')

看看 here 如果您对任何步骤感到困惑。但这应该是可行的。