Cloud Functions: Qwik Start - Command Line

LAB 4

Overview

Cloud Functions is a serverless execution environment for building and connecting cloud services. With Cloud Functions you write simple, single-purpose functions that are attached to events emitted from your cloud infrastructure and services. Your Cloud Function is triggered when an event being watched is fired. Your code executes in a fully managed environment. There is no need to provision any infrastructure or worry about managing any servers.

Lab

Create a Function

create a simple function named helloWorld which writes a message to the Cloud Functions logs. It is triggered by cloud function events and accepts a callback function used to signal completion of the function.

For this lab the cloud function event is a cloud pub/sub topic event. A pub/sub is a messaging service where the senders of messages are decoupled from the receivers of messages. When a message is sent or posted, a subscription is required for a receiver to be alerted and receive the message. For more information about pub/subs, see Google Cloud Pub/Sub: A Google-Scale Messaging Service.

First create a directory, move into it and create an index.js file.

mkdir gcf_hello_world
cd gcf_hello_world
touch index.js

Then, enter the following into the file.

/**
* 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} data The event payload.
* @param {object} context The event metadata.
*/
exports.helloWorld = (data, context) => {
const pubSubMessage = data;
const name = pubSubMessage.data
    ? Buffer.from(pubSubMessage.data, 'base64').toString() : "Hello World";
console.log(`My Cloud Function: ${name}`);
};

Create a cloud storage Bucket

The following command creates a new bucket.

gsutil mb -p [PROJECT_ID] gs://[BUCKET_NAME]

gsutil mb -p qwiklabs-gcp-00-5cd73182d144 gs://neewashere

Deploy the Function

When deploying a new function, you must specify --trigger-topic, --trigger-bucket, or --trigger-http.

gcloud functions deploy helloWorld \
  --stage-bucket [BUCKET_NAME] \
  --trigger-topic hello_world \
  --runtime nodejs8
  
  gcloud functions deploy helloWorld \
  --stage-bucket neewashere \
  --trigger-topic hello_world \
  --runtime nodejs8

Verify the status of the function:

gcloud functions describe helloWorld

Test the Function

Enter the following command to create a message test of the function

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

View Logs

Check the logs to see your messages in the log history with the following command

gcloud functions logs read helloWorld

Last updated