Getting Started with Serverless on Google Cloud Platform (GCP)
Serverless helps you to develop and deploy your code without worrying about underlying infrastructure since you don’t need to manage any infrastructure for your code. It will help you to improve productivity and focus on development.
Cloud functions are light-weight functions which can be executed based on various events like HTTP, GCS buckets etc. In this tutorial, we will discuss how we can create a simple Cloud Function and trigger based on GCS bucket events like “Create” and “Delete”.
Let’s get Started.
- Login to “https://console.cloud.google.com/” and search for “cloud function”.
- Click on “Create Function”
- Create Function page will appear requesting for Function details. Please provide name of the function and memory you would like to allocate to the cloud function.
- Since we would like to trigger this function upon creation of an object in GCS bucket please select trigger as “Cloud Storage”, Event Type as “Finalize/Create”, Bucket as “Bucket on which you would like to trigger this function on the creation of an object.”
- You can use a different method to write your code. We will use Inline editor to write our code. We are using python language in this example. However, you can use node.js as well.
- Select “runtime” which you would like to use. We will use Python in this tutorial.
- For python, we can write the code in file “main.py” and if there are any dependencies we can specify that in “requirement.txt” file.
PFB sample code which we would like invokes upon creation on any object in GCS bucket as above.
def hello_gcs(event, context):
"""Triggered by a change to a Cloud Storage bucket.
Args:
event (dict): Event payload.
context (google.cloud.functions.Context): Metadata for the event.
"""
file = event
print(f”Processing file: {file[‘name’]}.”)
print(“Size of the File (in Bytes) : {0}”.format(file[‘size’]))
print(“Storage Class : {0}”.format(file[‘storageClass’]))
Above code will print the Name, Size and Storage Class of the File.
- Specify the Name of the function which needs to be executed. “hello_gcs” in this example.
- Save function.
Note: It will take a minute or so to create and deploy the function.
- You can check the created function under “Cloud Functions” in google console.
- Now upload any file in the above bucket.
- In order to check the function output, you can select the function and click on “View logs” to check the logs for triggered function.
- You could see in Logs that “function Execution started” and printed the information about the file like Name, Size and Storage Class.
Note: We have now successfully created and Triggered Google Cloud Function.
- In order to trigger the Cloud function on the deletion of an object from GCS bucket, you can create another function and select the event type as “delete” while creating the function and follow the above steps to trigger and verify the function.
Hope you have enjoyed the tutorial.