我正在CI / CD环境中操作,严格禁止将JSON密钥文件写入磁盘或将其包含在项目中。我所能做的就是将原始JSON数据注入一个环境变量,我们可以在运行时读回。将GOOGLE_APPLICATION_CREDENTIALS设置为密钥文件路径的常用方法在此处不起作用,因为我们无法首先编写该文件。它需要将JSON数据直接包含在字符串中。
不幸的是,我发现的所有Google Cloud文档都假设在身份验证之前存在JSON密钥文件。没有讨论如何通过变量值直接进行身份验证。 closest thing which I've found暗示明确设置凭证是可能的,但linked page仅讨论Credentials类的内部属性。
幸运的是,我阅读the code的运气比文档更好。稍微探讨了一下后,我找到了ServiceAccountCredentials._from_parsed_json_keyfile,这使我能够做我想做的事。这是我的测试代码:
import os
import json
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient import discovery
# Prepare the service object
json_data = json.loads(os.getenv("MY_CREDENTIALS_STRING"))
credentials = ServiceAccountCredentials._from_parsed_json_keyfile(json_data, scopes='')
service = discovery.build('compute', 'v1', credentials=credentials)
# Test the service object
request = service.images().list(project='my-project')
response = request.execute()
print(response)
这有效,但感觉就像一个黑客。函数名称中的“_”告诉我它不是支持的API的一部分,并且可能会在未来版本中消失而不会发出警告。
我没有看到正式的方法来实现这一目标。有吗?
使用课程google.oauth2.service_account
。该成员是from_service_account_info
。
from google.oauth2 import service_account
// load from a file
// service_account_info = json.load(open('service_account.json'))
// load from system environment
service_account_info = json.loads(os.getenv("MY_CREDENTIALS_STRING"))
credentials = service_account.Credentials.from_service_account_info(service_account_info)