簡體   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?

我剛剛部署了一個 Cloud Run REST API 應用程序,它使用 Google Cloud Storage API 從存儲桶中獲取最后一個文件以及該存儲桶中的文件夾。 這是我正在使用的代碼:

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)))

在沒有本地服務帳戶密鑰文件的情況下,如何在 Google Cloud Storage 和 Cloud Run 之間進行服務到服務身份驗證

提前致謝。

在 Cloud Run 上,由於容器內存在容器實例元數據服務器,Python 的 Cloud Storage 客戶端庫將自動獲取 Cloud Run 服務身份的憑證。 在這里閱讀更多

要為 Steren 的精彩解釋提供實現此目的的實用方法,您必須將代碼中的行替換為以下內容

# Existing line
storage_client = storage.Client.from_service_account_json('sa.json')
# New line
storage_client = storage.Client()

通過這一行,服務選擇上下文中提供的服務帳戶。 感謝 Steren 在您使用 Cloud Run 時解釋的元數據服務器。 但在 Cloud Function、App Engine 和 Compute Engine(以及類似的:Dataflow、Dataproc、GKE 等)上也是如此

但是,如何在您的本地環境中執行此操作? 你有2個解決方案

  1. 您可以在 GOOGLE_APPLICATION_CREDENTIALS 環境變量中設置服務帳戶密鑰文件的路徑。

但是,就我個人而言,當你開發時,我絕對不建議使用服務帳戶密鑰文件。 這是一個安全漏洞。 寫了一篇關於此的文章和另一篇文章,以使用您自己的用戶憑據在本地測試容器,因此沒有服務帳戶密鑰文件

  1. 正如您在提到的第二篇文章中所讀到的,您可以在本地環境中通過命令gcloud auth application-default login使用 ADC(應用程序默認憑證)。

多虧了這 2 個解決方案,您將能夠以相同的方式在本地和 Cloud Run(以及其他 GCP 服務)上運行您的代碼,而無需根據運行時上下文使用任何“if”。

我剛剛部署了一個 Cloud Run REST API 應用程序,它使用 Google Cloud Storage API 從存儲桶和存儲桶內的文件夾中獲取最后一個文件。 這是我正在使用的代碼:

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)))

在沒有本地服務帳戶密鑰文件的情況下,如何在 Google Cloud Storage 和 Cloud Run 之間進行服務到服務身份驗證

提前致謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM