[英]How to access to a Google Cloud Storage bucket from a Cloud Run service without using a local Service Account key file?
I just deployed a Cloud Run REST API application, which uses the Google Cloud Storage API to get the last file from a bucket and a folder inside that bucket.我刚刚部署了一个 Cloud Run REST API 应用程序,它使用 Google Cloud Storage API 从存储桶中获取最后一个文件以及该存储桶中的文件夹。 This is the code I'm using:
这是我正在使用的代码:
import os
import logging
from flask import Flask
from flask import request, jsonify, render_template
from google.oauth2 import service_account
from google.cloud import storage
from bson.json_util import dumps
app = Flask(__name__)
storage_client = storage.Client.from_service_account_json('sa.json')
@app.route('/')
# API Version 1.0
def index():
"""Welcome to Last File API Version 1.0."""
button_text = "Add File"
return render_template('main.html', button_text=button_text)
@app.route("/last_file_m_individual/", methods=["GET"])
def list_m_individual_files():
"""List all files in GCP bucket."""
bucketName = request.args.get('bucketname')
bucketFolder = request.args.get('bucketfolder')
bucket = storage_client.get_bucket(bucketName)
files = bucket.list_blobs(prefix=bucketFolder)
fileList = [file.name for file in files if '.' in file.name]
last_file_pep = fileList[-1]
last_file_p = last_file_pep.split("/")
last_file = last_file_p[-1]
return last_file
@app.errorhandler(500)
def server_error(e):
# Log the error and stacktrace.
logging.exception('An error occurred during a request.')
return 'An internal error occurred.', 500
if __name__ == "__main__":
app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080)))
How can I have a service-to-service authentication between Google Cloud Storage and Cloud Run without having locally the Service Account key file for it ?在没有本地服务帐户密钥文件的情况下,如何在 Google Cloud Storage 和 Cloud Run 之间进行服务到服务身份验证?
Thanks in advance.提前致谢。
On Cloud Run, the Cloud Storage client library for Python will automatically pick up the credentials of the identity of the Cloud Run service thanks to the container instance metadata server present inside the container.在 Cloud Run 上,由于容器内存在容器实例元数据服务器,Python 的 Cloud Storage 客户端库将自动获取 Cloud Run 服务身份的凭证。 Read more here
在这里阅读更多
To provide a practical way to achieve this to the great explanation of Steren, you have to replace the line in your code by the following要为 Steren 的精彩解释提供实现此目的的实用方法,您必须将代码中的行替换为以下内容
# Existing line
storage_client = storage.Client.from_service_account_json('sa.json')
# New line
storage_client = storage.Client()
With this line, the service pick the service account provided in the context.通过这一行,服务选择上下文中提供的服务帐户。 Thanks to the metadata server as explained by Steren when you are on Cloud Run.
感谢 Steren 在您使用 Cloud Run 时解释的元数据服务器。 But it's also true on Cloud Function, App Engine and Compute Engine (and similar: Dataflow, Dataproc, GKE,...)
但在 Cloud Function、App Engine 和 Compute Engine(以及类似的:Dataflow、Dataproc、GKE 等)上也是如此
But, how to do this on your local environment?但是,如何在您的本地环境中执行此操作? You have 2 solutions
你有2个解决方案
But, personally, when you develop, I absolutely don't recommend to use service account key file.但是,就我个人而言,当你开发时,我绝对不建议使用服务帐户密钥文件。 It's a security weakness.
这是一个安全漏洞。 I wrote an article on this and another one to test the containers locally with your own user credential and thus without service account key file .
我写了一篇关于此的文章和另一篇文章,以使用您自己的用户凭据在本地测试容器,因此没有服务帐户密钥文件。
gcloud auth application-default login
.gcloud auth application-default login
使用 ADC(应用程序默认凭证)。 Thanks to this 2 solutions, you will be able to run your code locally and on Cloud Run (and other GCP services) in the same way without any "if" according with the runtime context.多亏了这 2 个解决方案,您将能够以相同的方式在本地和 Cloud Run(以及其他 GCP 服务)上运行您的代码,而无需根据运行时上下文使用任何“if”。
I just deployed a Cloud Run REST API application, which uses the Google Cloud Storage API to get the last file from a bucket and a folder inside that bucket.我刚刚部署了一个 Cloud Run REST API 应用程序,它使用 Google Cloud Storage API 从存储桶和存储桶内的文件夹中获取最后一个文件。 This is the code I'm using:
这是我正在使用的代码:
import os
import logging
from flask import Flask
from flask import request, jsonify, render_template
from google.oauth2 import service_account
from google.cloud import storage
from bson.json_util import dumps
app = Flask(__name__)
storage_client = storage.Client.from_service_account_json('sa.json')
@app.route('/')
# API Version 1.0
def index():
"""Welcome to Last File API Version 1.0."""
button_text = "Add File"
return render_template('main.html', button_text=button_text)
@app.route("/last_file_m_individual/", methods=["GET"])
def list_m_individual_files():
"""List all files in GCP bucket."""
bucketName = request.args.get('bucketname')
bucketFolder = request.args.get('bucketfolder')
bucket = storage_client.get_bucket(bucketName)
files = bucket.list_blobs(prefix=bucketFolder)
fileList = [file.name for file in files if '.' in file.name]
last_file_pep = fileList[-1]
last_file_p = last_file_pep.split("/")
last_file = last_file_p[-1]
return last_file
@app.errorhandler(500)
def server_error(e):
# Log the error and stacktrace.
logging.exception('An error occurred during a request.')
return 'An internal error occurred.', 500
if __name__ == "__main__":
app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080)))
How can I have a service-to-service authentication between Google Cloud Storage and Cloud Run without having locally the Service Account key file for it ?在没有本地服务帐户密钥文件的情况下,如何在 Google Cloud Storage 和 Cloud Run 之间进行服务到服务身份验证?
Thanks in advance.提前致谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.