在我的 Aws EC2 实例中,我有一个与 Google Bigquery 交互以执行多项操作的 Python 脚本。
出于安全原因,我不想在项目中使用服务账户私钥作为文件,因此,我将其存储在我的 AWS Secrets Manager 中。
在Python中,使用boto3很容易获取密钥:
import boto3
from botocore.exceptions import ClientError
import google.oauth2
def get_secret():
secret_name = "put_key_name_here"
region_name = "put_region_name_here"
session = boto3.session.Session()
client = session.client(service_name='secretsmanager', region_name=region_name)
get_secret_value_response = client.get_secret_value(SecretId = secret_name)
a = json.loads(get_secret_value_response['SecretString'])
return a['credentials'] #HERE I HAVE MY CREDENTIALS STRING
现在我需要使用Google客户端的方法之一。 我无法使用 from_service_account_file 但只能使用 from_service_account_info https://googleapis.dev/python/google-auth/1.7.0/user-guide.html
但是代码出现错误:
dict_secrets={}
dict_secrets["client_email"]="[email protected]"
dict_secrets["token_uri"]="https://oauth2.googleapis.com/token"
dict_secrets["private_key"] = get_secret() #myfunction to get the private_key
my_project='my_google_bigquery_project'
credential_bq = google.oauth2.service_account.Credentials.from_service_account_info(dict_secrets, scopes=["https://www.googleapis.com/auth/cloud-platform"])
client_bq = bigquery.Client(credentials=credential_bq, project=my_project)
ValueError: No key could be detected.
没有
dict_secrets["private_key"]
我收到了不同的错误:
ValueError: The private_key field was not found in the service account info
我哪里错了? 是否存在另一种方法来执行这些操作? 谢谢!
来自文档
响应语法为:
{
'ARN': 'string',
'Name': 'string',
'VersionId': 'string',
'SecretBinary': b'bytes',
'SecretString': 'string',
'VersionStages': [
'string',
],
'CreatedDate': datetime(2015, 1, 1)
}
所以你需要从回复中取出
'SecretString'
-
get_secret_value_response = client.get_secret_value(SecretId = secret_name)
secret_value = get_secret_value_response["SecretString"]
此外,从 Google 服务帐户文档,下载的密钥具有以下格式,其中私钥是公钥/私钥对的私有部分:
{
"type": "service_account",
"project_id": "project-id",
"private_key_id": "key-id",
"private_key": "-----BEGIN PRIVATE KEY-----\nprivate-key\n-----END PRIVATE KEY-----\n",
"client_email": "service-account-email",
"client_id": "client-id",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/service-account-email"
}
:
Cuando almacenes tu AWS Secret asegurate de copiar el contenido JSON Correctamente en la pestaña "Plaint Text" del Secret.