Direct Triggers

To support quick iteration and debugging, Cloud Functions provides a call command in the command-line interface and testing functionality in the GCP Console UI. This allows you to directly invoke a function to ensure it is behaving as expected. This causes the function to execute immediately, even though it may have been deployed to respond to a specific event.

Using the gcloud command-line interface

To directly invoke a function using the gcloud tool, use the gcloud functions call command and supply any data your function expects as JSON in the --data argument. For example:

gcloud functions call YOUR_FUNCTION_NAME --data '{"name":"Keyboard Cat"}'

where YOUR_FUNCTION_NAME is the name of the function you want to execute. The --data argument is sent to your function as follows:

  • For HTTP functions, the data you supply is sent as the body of a POST request.
  • For background functions, the data is passed directly as the event data to your function. For more information on accessing event data in background functions, see Background function parameters.

Using the GCP Console

To directly invoke a function from the GCP Console, follow these steps:

  1. Go to the Cloud Functions Overview page.

  2. From the list, click the name of the function you want to invoke.

    This takes you to the Function details page.

  3. Click the Testing tab.

  4. In the Triggering event field, enter any data your function expects as JSON.

  5. Click Test the function.

Your function's response appears in the Output field, and logs for the individual execution appear in the Logs field.

Cloud Pub/Sub background function example

This example shows how to directly invoke a background function triggered by Cloud Pub/Sub events:

Node.js 8/10

 * Background Cloud Function to be triggered by Pub/Sub.
 * This function is exported by index.js, and executed when
 * the trigger topic receives a message.
 * @param {object} pubSubEvent The event payload.
 * @param {object} context The event metadata.
exports.helloPubSub = (pubSubEvent, context) => {
  const name =
    ? Buffer.from(, 'base64').toString()
    : 'World';

  console.log(`Hello, ${name}!`);

Node.js 6 (Deprecated)

 * Background Cloud Function to be triggered by Pub/Sub.
 * This function is exported by index.js, and executed when
 * the trigger topic receives a message.
 * @param {object} event The Cloud Functions event.
 * @param {function} callback The callback function.
exports.helloPubSub = (event, callback) => {
  const pubsubMessage =;
  const name =
    ? Buffer.from(, 'base64').toString()
    : 'World';

  console.log(`Hello, ${name}!`);



def hello_pubsub(event, context):
    """Background Cloud Function to be triggered by Pub/Sub.
         event (dict):  The dictionary with data specific to this type of
         event. The `data` field contains the PubsubMessage message. The
         `attributes` field will contain custom attributes if there are any.
         context ( The Cloud Functions event
         metadata. The `event_id` field contains the Pub/Sub message ID. The
         `timestamp` field contains the publish time.
    import base64

    print("""This Function was triggered by messageId {} published at {}
    """.format(context.event_id, context.timestamp))

    if 'data' in event:
        name = base64.b64decode(event['data']).decode('utf-8')
        name = 'World'
    print('Hello {}!'.format(name))


// Package helloworld provides a set of Cloud Functions samples.
package helloworld

import (

// PubSubMessage is the payload of a Pub/Sub event.
type PubSubMessage struct {
	Data []byte `json:"data"`

// HelloPubSub consumes a Pub/Sub message.
func HelloPubSub(ctx context.Context, m PubSubMessage) error {
	name := string(m.Data)
	if name == "" {
		name = "World"
	log.Printf("Hello, %s!", name)
	return nil

To directly invoke the function, you need to send a PubsubMessage, which expects base64-encoded data, as the event data:


DATA=$(printf 'Hello!'|base64) && gcloud functions call helloPubSub --data '{"data":"'$DATA'"}'


DATA=$(printf 'Hello!'|base64) && gcloud functions call hello_pubsub --data '{"data":"'$DATA'"}'


DATA=$(printf 'Hello!'|base64) && gcloud functions call HelloPubSub --data '{"data":"'$DATA'"}'

You can also invoke the function from the GCP Console UI: simply use the same event data in the Triggering event field.

Cloud Pub/Sub HTTP function example

You can trigger subsequent Cloud Function invocations using Cloud Pub/Sub messages. This technique allows you to:

  • Chain sequential function calls together.
  • Distribute (or "fan out") groups of tasks in parallel across multiple Cloud Function instances.

In the following example, an HTTP publish function sends a message to a Pub/Sub topic, and that in turn triggers a subscribe function.

This snippet shows the publish function that publishes a message to a Pub/Sub topic:


 * Publishes a message to a Cloud Pub/Sub Topic.
 * @example
 * gcloud functions call publish --data '{"topic":"[YOUR_TOPIC_NAME]","message":"Hello, world!"}'
 *   - Replace `[YOUR_TOPIC_NAME]` with your Cloud Pub/Sub topic name.
 * @param {object} req Cloud Function request context.
 * @param {object} req.body The request body.
 * @param {string} req.body.topic Topic name on which to publish.
 * @param {string} req.body.message Message to publish.
 * @param {object} res Cloud Function response context.
exports.publish = async (req, res) => {
  if (!req.body.topic || !req.body.message) {
        'Missing parameter(s); include "topic" and "subscription" properties in your request.'

  console.log(`Publishing message to topic ${req.body.topic}`);

  // References an existing topic
  const topic = pubsub.topic(req.body.topic);

  const messageObject = {
    data: {
      message: req.body.message,
  const messageBuffer = Buffer.from(JSON.stringify(messageObject), 'utf8');

  // Publishes a message
  try {
    await topic.publish(messageBuffer);
    res.status(200).send('Message published.');
  } catch (err) {
    return Promise.reject(err);

This snippet shows the subscribe function that is triggered when the message is published to the Pub/Sub topic:


 * Triggered from a message on a Cloud Pub/Sub topic.
 * @param {object} pubsubMessage The Cloud Pub/Sub Message object.
 * @param {string} The "data" property of the Cloud Pub/Sub Message.
exports.subscribe = pubsubMessage => {
  // Print out the data from Pub/Sub, to prove that it worked
  console.log(Buffer.from(, 'base64').toString());

In production, you might use the cURL command-line utility to invoke the publish function, as follows:

curl -X POST  -d "{\"topic\": \"PUBSUB_TOPIC\", \"message\":\"YOUR_MESSAGE\"}" -H "Content-Type: application/json"

But for testing and debugging, you could instead use the gcloud functions call command to call the function directly. The following steps describe how to run the above example using the gcloud functions call command:

  1. Create a Pub/Sub topic, where MY_TOPIC is the name of the new topic you are creating:

    gcloud pubsub topics create MY_TOPIC
  2. Deploy the publish function, where RUNTIME is the name of the runtime you are using, such as nodejs8:

    gcloud functions deploy publish --trigger-http --runtime RUNTIME
  3. Deploy the subscribe function:

    gcloud functions deploy subscribe --trigger-topic MY_TOPIC --runtime RUNTIME
  4. Directly invoke the function using the gcloud functions call command, and supply the required data as JSON in the --data argument:

    gcloud functions call publish --data '{"topic":"MY_TOPIC","message":"Hello World!"}'
  5. Check the logs for the subscribe function. Note that it may take a few minutes for your results to appear in the log:

    gcloud functions logs read subscribe

You should see output resembling the following:

D    ...Function execution started
I    ...{"data":{"message":"Hello World!"}}
D    ...Function execution took 753 ms, finished with status: 'ok'
Оцените, насколько информация на этой странице была вам полезна:

Оставить отзыв о...

Текущей странице
Cloud Functions Documentation