这个想法是使用服务帐户凭据从 BigQuery 查询数据,如 Authenticating With a Service Account Key File 中所述
自动化过程可以通过一个 bash 脚本(我们称之为“deploy_cloud.sh”)来处理,该脚本将包含所有配置参数,如下所示:
export JOB_NAME="your_job_$(date +%Y%m%d_%H%M%S)"
export BUCKET_NAME=your_job
export CLOUD_FOLDER=test-folder
export JOB_DIR=$BUCKET_NAME/$CLOUD_FOLDER/$JOB_NAME
export CLOUD_SECRET_FOLDER=credentials
export SERVICE_ACC_SECRET=service_account_secret.json
# copy your service account credential to cloud storage
# you can do this step manually in your storage
gsutil cp -r path_to_your_service_account_file/$SERVICE_ACC_SECRET gs://$BUCKET_NAME/$CLOUD_FOLDER/$CLOUD_SECRET_FOLDER/$SERVICE_ACC_SECRET
# define your query params
export YOUR_QUERY_PARAM1="provide_param1_value"
export YOUR_QUERY_PARAM2="provide_param2_value"
export YOUR_QUERY_PARAM3="provide_param3_value"
export YOUR_QUERY_PARAM4="provide_param4_value"
# Then submit your training job
gcloud ml-engine jobs submit training $JOB_NAME \
--job-dir $JOB_DIR \
--runtime-version 1.4 \
--module-name trainer.task \
--package-path ./trainer \
--region $REGION \
--config=trainer/config-gpu.yaml \
-- \
--client-sec gs://$BUCKET_NAME/$CLOUD_FOLDER/$CLOUD_SECRET_FOLDER/$SERVICE_ACC_SECRET \
--query-param1 $YOUR_QUERY_PARAM1 \
--query-param2 $YOUR_QUERY_PARAM2 \
--query-param3 $YOUR_QUERY_PARAM3 \
--query-param4 $YOUR_QUERY_PARAM4
在您的 task.py 文件中,您将需要使用参数解析器来使用这些传递的值并相应地构建您的查询。在您的 task.py 文件中,使用以下代码从存储桶中读取数据并将其写入云实例的本地内存,如下所示:
def read_and_write_client_secret(input_file, output_file):
with file_io.FileIO(input_file, 'r') as f:
secret = json.load(f)
with open(output_file, 'w') as outfile:
json.dump(secret, outfile)
您可以按如下方式调用上述函数(在您的 task.py 中):
read_and_write_client_secret(args_dict['client_sec'], 'temp.json')
考虑到您的参数解析器将所有参数作为字典存储在 args_dict 中。请注意,您的服务帐户文件将在云实例当前/工作目录中写为“temp.json”。
现在您需要在创建 BigQuery 客户端时指定文件位置(包含凭据的“temp.json”),如下所示;
# my_query = build_my_query(args_dict['query_param1'], args_dict['query_param2'], args_dict['query_param3'], args_dict['query_param4'])
bigquery_client = bigquery.Client.from_service_account_json(
'temp.json')
query_job = client.query(my_query)
results = query_job.result() # Waits for job to complete.
# suggestion: extract data from iterator and create a pandas data frame for further processing
现在您的云实例将能够运行您的查询并使用该数据。您可以根据所获得的数据开始机器学习工作。