orc*_*man 3 python google-bigquery amazon-sagemaker
在本地运行时,我的Jupyter笔记本可以像这样引用Google BigQuery:
%%bigquery some_bq_table
SELECT *
FROM
`some_bq_dataset.some_bq_table`
Run Code Online (Sandbox Code Playgroud)
这样一来,在以后的笔记本中,我就可以将some_bq_table用作熊猫数据框,如下所示:https ://cloud.google.com/bigquery/docs/visualize-jupyter
我想在AWS SageMaker上运行我的笔记本以测试一些东西。要通过BigQuery进行身份验证,似乎仅有的两种方法是在GCP上(或在本地)使用服务帐户,或使用env var将SDK指向凭据JSON(如此处所述:https://cloud.google.com/ docs / authentication / getting-started)。
例如
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"
Run Code Online (Sandbox Code Playgroud)
有一种简单的方法可以从SageMaker连接到bigquery吗?现在,我最好的主意是将JSON从某处下载到SageMaker实例,然后从python代码设置env var。
例如,我会这样做:
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/home/user/Downloads/[FILE_NAME].json"
Run Code Online (Sandbox Code Playgroud)
但是,这不是很安全-我不喜欢将凭据JSON下载到SageMaker实例的想法(这意味着我必须将凭据上传到某些私有s3存储桶,然后将其存储在SageMaker实例中)。不是世界末日,而是我避免这种情况。
有任何想法吗?
如前所述,GCP当前使用服务帐户,凭据JSON和API令牌进行身份验证。您可以考虑使用AWS Secrets Manager或AWS Systems Manager参数存储来存储GCP凭据,然后在Jupyter笔记本中获取它们,而不是将凭据存储在S3存储桶中。这样可以保护凭据,并且仅在需要时才从Secrets Manager创建凭据文件。
这是我以前用来从SageMaker实例连接到BigQuery的示例代码。
import os
import json
import boto3
from google.cloud.bigquery import magics
from google.oauth2 import service_account
def get_gcp_credentials_from_ssm(param_name):
# read credentials from SSM parameter store
ssm = boto3.client('ssm')
# Get the requested parameter
response = ssm.get_parameters(Names=[param_name], WithDecryption=True)
# Store the credentials in a variable
gcp_credentials = response['Parameters'][0]['Value']
# save credentials temporarily to a file
credentials_file = '/tmp/.gcp/service_credentials.json'
with open(credentials_file, 'w') as outfile:
json.dump(json.loads(gcp_credentials), outfile)
# create google.auth.credentials.Credentials to use for queries
credentials = service_account.Credentials.from_service_account_file(credentials_file)
# remove temporary file
if os.path.exists(credentials_file):
os.remove(credentials_file)
return credentials
# this will set the context credentials to use for queries performed in jupyter
# using bigquery cell magic
magics.context.credentials = get_gcp_credentials_from_ssm('my_gcp_credentials')
Run Code Online (Sandbox Code Playgroud)
请注意,SageMaker执行角色应该有权访问SSM,当然还有其他连接到GCP的必要途径。我不确定这是否是最好的方法。希望有人有更好的方法。
| 归档时间: |
|
| 查看次数: |
189 次 |
| 最近记录: |