I created a Cloud Function gen2 using the code from the documentation and doesn't work when using gcloud functions call my-cf
but it works without any issue if I use Scheduler + PubSub to trigger the Cloud Function.
I suspect that I need to build the payload differently than when using gen1. I am using Google Cloud SDK 500.0.0
I am using the following in the requirement file: cloudevents==1.11.0
The main.py
is a copy and paste from the documentation
import base64
from cloudevents.http import CloudEvent
import functions_framework
# Triggered from a message on a Cloud Pub/Sub topic.
@functions_framework.cloud_event
def subscribe(cloud_event: CloudEvent) -> None:
# Print out the data from Pub/Sub, to prove that it worked
print(
"Hello, " + base64.b64decode(cloud_event.data["message"]["data"]).decode() + "!"
)
For deploying the CF, I am a more complex command since I have org policy (VPC-SC, SA, CMEK) but it should be something like that:
PROJECT="xxx"
REGION="europe-west6"
gcloud functions deploy my-cf \
--gen2 \
--runtime=python312 \
--region="$REGION" \
--source=. \
--entry-point="subscribe" \
--trigger-topic="test-cloud-function" \
--verbosity debug
How to run the cloud function with gcloud
is also coming from the documentation:
DATA=$(printf 'Hello!' | base64)
REGION="europe-west6"
gcloud functions call my-cf \
--region="$REGION" \
--data '{"data":"'"$DATA"'"}'
Error message I see when using --data
:
|
<!doctype html>
<html lang=en>
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<br>User-Agent: google-cloud-sdk gcloud/500.0.0 command/gcloud.functions.call invocation-id/dc6a875549ab4a24b1815a87553abb71 environment/GCE environment-version/None client-os/LINUX client-os-ver/6.5.0 client-pltf-arch/x86_64 in<br>[AUTH_TOKEN];br><br>Got data: b'{"data":"SGVsbG8h"}'<br>Got CloudEvent exception: MissingRequiredFields('Failed to find specversion in HTTP request')<br>Got background event conversion exception: EventConversionException('Unable to find CloudEvent equivalent type for ""')</p>
It seems that what is written in the doc is maybe not up to date
Similar issue when using --cloud-event
with the same data as for --data
. Form the documentation, I am not really able to understand the following from the documentation :~:text=can%20be%20specified%3A-,%2D%2Dcloud%2Devent%3DCLOUD_EVENT,-JSON%20encoded%20string:
Use for Cloud Functions 2nd Gen CloudEvent functions. The CloudEvent object will be sent to your function as a binary content mode message with the top-level 'data' field set as the HTTP body and all other JSON fields sent as HTTP headers.
Is everybody know how we should build the payload when using --data
or --cloud-event
? I didn't managed to find a working example.