简体   繁体   English

如何在不使用本地服务帐户密钥文件的情况下从 Cloud Run 服务访问 Google Cloud Storage 存储桶?

[英]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个解决方案

  1. You can set the path of your service account key file in the GOOGLE_APPLICATION_CREDENTIALS environment variable.您可以在 GOOGLE_APPLICATION_CREDENTIALS 环境变量中设置服务帐户密钥文件的路径。

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 .写了一篇关于此的文章和另一篇文章,以使用您自己的用户凭据在本地测试容器,因此没有服务帐户密钥文件

  1. As you could read in the second article mentioned, you can use the ADC (Application Default Credential) in your local environment with the command 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.

相关问题 无法访问 Cloud 中的 Google Cloud Storage 服务帐户密钥文件 - Unable to access Google Cloud Storage service account key file in Cloud 授予服务帐户访问谷歌云存储中的一个存储桶的权限 - Give service account access to one bucket in google cloud storage 如何在没有密钥文件的情况下授予 Cloud Run 服务访问服务帐号凭据的权限? - How can I grant a Cloud Run service access to service account's credentials without the key file? 如何仅授予服务帐户对一个存储桶(Google Cloud)的访问权限? - How to give service account only access to one bucket (Google Cloud)? 如何使用 Cloud Function 服务帐户在 Cloud Function 中创建签名的 Google Cloud Storage URL? - How to create signed Google Cloud Storage URLs in Cloud Function using Cloud Function service account? 我获得存储权限的服务帐户没有对 Google Cloud Storage 存储桶的 storage.objects.list 访问权限 - My service account which was given storage permissions does not have storage.objects.list access to the Google Cloud Storage bucket google cloud run service运行时访问service account ID - Access service account ID at runtime of google cloud run service GCP - 控制对 Google Cloud Storage 服务帐户的访问 - GCP - Controlling access to Service Account for Google Cloud Storage 使用Google Cloud Service帐户 - Using google cloud service account 使用服务帐户从Google Cloud功能访问Google Cloud SQL实例 - Access Google cloud SQL instance from Google cloud function using a service account
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM