[英]How can I see the service account that the python bigquery client uses?
To create a default bigquery client I use:要创建默认的 bigquery 客户端,我使用:
from google.cloud import bigquery
client = bigquery.Client()
This uses the (default) credentials available in the environment.这使用环境中可用的(默认)凭据。
But how I see then which (default) service account is used?但是我如何查看使用了哪个(默认)服务帐户?
This led me in the right direction:这使我朝着正确的方向前进:
Google BigQuery Python Client using the wrong credentials 使用错误凭据的 Google BigQuery Python 客户端
To see the service-account used you can do:要查看使用的服务帐户,您可以执行以下操作:
client._credentials.service_account_email
However:然而:
This statement above works when you run it on a jupyter notebook (in Vertex AI), but when you run it in a cloud function with print(client._credentials.service_account_email)
then it just logs 'default'
to Cloud Logging.当您在 jupyter 笔记本(在 Vertex AI 中)上运行它时,上面的这条语句有效,但是当您使用
print(client._credentials.service_account_email)
在云函数中运行它时,它只会将'default'
记录到 Cloud Logging。 But the default service account for a Cloud Function should be: <project_id>@appspot.gserviceaccount.com
.但是云函数的默认服务帐户应该是:
<project_id>@appspot.gserviceaccount.com
。
This will also give you the wrong answer:这也会给你错误的答案:
client.get_service_account_email()
The call to client.get_service_account_email()
does not return the credential's service account email address.对
client.get_service_account_email()
的调用不会返回凭据的服务帐户电子邮件地址。 Instead, it returns the BigQuery service account email address used for KMS encryption/decryption.相反,它会返回用于 KMS 加密/解密的 BigQuery 服务帐号电子邮件地址。
While you can interrogate the credentials directly (be it json keys, metadata server, etc), I have occasionally found it valuable to simply query bigquery using the SESSION_USER()
function.虽然您可以直接查询凭据(无论是 json 密钥、元数据服务器等),但我偶尔会发现使用
SESSION_USER()
函数简单地查询 bigquery 很有价值。
Something quick like this should suffice:像这样快速的东西就足够了:
client = bigquery.Client()
query_job = client.query("SELECT SESSION_USER() as whoami")
results = query_job.result()
for row in results:
print("i am {}".format(row.whoami))
Following John Hanley's comment (when running on a Compute Engine) you can query the metadata service to get the email user name:按照 John Hanley 的评论(在 Compute Engine 上运行时),您可以查询元数据服务以获取电子邮件用户名:
https://cloud.google.com/compute/docs/metadata/default-metadata-values https://cloud.google.com/compute/docs/metadata/default-metadata-values
So you can either use linux:所以你可以使用linux:
curl "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/email" -H "Metadata-Flavor: Google"
Or python:或蟒蛇:
import requests
headers = {'Metadata-Flavor': 'Google'}
response = requests.get(
"http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/email",
headers=headers
)
print(response.text)
The default
in the url used is the alias of the actual service account used.使用的 url 中的
default
是实际使用的服务帐户的别名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.