For Authentication for running a GCP Cloud Functio...
# ask-community
m
For Authentication for running a GCP Cloud Function, can I just put the Key for the GCP Service Account that runs the function into a Prefect Secret?
Or do I put the whole json file?
k
How would you do it in Python? You would use the key or json?
m
I've actually been triggering them from Bash with the Cloud Scheduler
Haven't really been using the GCP Python package.
though I guess I'll have to start. Hopefully I can make a PR for a Cloud Function task!
k
Ah I haven’t used it myself to provide feedback here.
m
I think I did it right - I put the JSON file for the Service Account in
GCP_CREDENTIALS
in Prefect.
Now I just need to write the actual Task!
Oh, hrm, looks like Cloud Functions aren't part of the Python package? I guess I'll have to hit it from Requests.
z
Sweet! Thanks for sharing 🙂
m
MVP:
Copy code
import prefect
from prefect import task, Flow, Parameter
from prefect.tasks.secrets.base import PrefectSecret
from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession
import requests
import json


@task
def trigger_cloud_fn(secret: PrefectSecret, url: str):
    credentials = service_account.IDTokenCredentials.from_service_account_info(
        secret, target_audience=url
    )
    authed_session = AuthorizedSession(credentials)
    body = json.dumps(dict())
    response = <http://authed_session.post|authed_session.post>(url=url, json=body)
    return response


with Flow("run-cloud-fn") as flow:
    cloud_fn_url = Parameter("cloud_fn_url", required=True)
    gcp_secret = PrefectSecret("GCP_CREDENTIALS")
    trigger_cloud_fn(gcp_secret, cloud_fn_url)

flow.register(project_name="tester")