1

I need to write a cloud function in GCP, which responds to HTTP requests and has service account access to GCP cloud storage. My function will receive a string and threshold parameters. It will retrieve a csv file from cloud storage, compute similarity between the text string supplied and the entities in the csv file and return the entities that satisfy the threshold requirements.

From Google's cloud function tutorials, I have yet to see anything that gives it cloud storage access, a service account for access therein, etc.

Could anyone link a resource or otherwise explain how to get from A to B?

jbuddy_13
  • 902
  • 2
  • 12
  • 34
  • 1
    Cloud Functions has a service account assigned to each function. Use IAM and add a role that grants the required access to Cloud Storage. https://cloud.google.com/functions/docs/concepts/iam – John Hanley Mar 18 '21 at 17:48

1 Answers1

3

Let the magic happens!

In fact, nothing is magic. With most of Google Cloud products, you have a service account that you can grant the permission that you want. On Cloud Functions, the default service account is the AppEngine default service account with this pattern <projectID>@appspot.gserviceaccount.com.

When you deploy a Cloud FUnctions you can use a custom service account by using this paramenter --service-account=. It's safer because your Cloud Functions can have his own service account, with limited permissions (App Engine default service account is Project Editor by default, which is too wide!!)

So, this service is loaded automatically with your cloud functions and the Google Cloud auth libraries can access it via the Metadata server. The credentials is taken from the runtime context, it's the default credential of the environment

About your code, keep it as simple as that

    from google.cloud import storage

    client = storage.Client() # Use default credentials
    bucket = client.get_bucket('myBucket')
    blobs = bucket.list_blobs()
    for blob in blobs:
        print(blob.size)

On your workstation, if you want to execute the same code, you can use your own credential by running this command gcloud auth application-default login If you prefer using a service account key file (that I strongly don't recommend, but it's not the topic), you can set the environment variable GOOGLE_APPLICATION_CREDENTIALS with the file path as value

guillaume blaquiere
  • 66,369
  • 2
  • 47
  • 76
  • Thank you, kind stranger! I'm curious on your thoughts on this related question: https://stackoverflow.com/questions/66697571/how-to-access-csv-file-from-google-cloud-storage-in-a-google-cloud-function-via – jbuddy_13 Mar 18 '21 at 19:50
  • Sure, I answered it. I think I found your issue, it's not about security/service account – guillaume blaquiere Mar 18 '21 at 20:20