Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

Thanks in advance.

like image 563
marcosluis2186 Avatar asked Oct 16 '25 06:10

marcosluis2186


1 Answers

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. Read more here

like image 171
Steren Avatar answered Oct 18 '25 22:10

Steren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!