Serverless Architectures with Kubernetes
上QQ阅读APP看书,第一时间看更新

Introduction

In the previous chapter, the architectural evolution of traditional architectures to serverless designs was discussed. In addition, the origin and benefits of serverless were presented to explain its high adoption and success in the industry. In this chapter, the focus will be on the serverless platforms of cloud providers. Let's start with the evolution of cloud technology offerings over the years.

At the start of cloud computing, the primary offering of cloud providers was its provisioned and ready-to-use hardware, namely the infrastructure. Cloud providers manage hardware and networking operations, and therefore, the product they were offering was Infrastructure-as-a-Service (IaaS), as illustrated in the following diagram. All cloud providers are still offering IaaS products as their core functionality, such as Amazon Elastic Compute Cloud (Amazon EC2) in AWS and Google Compute Engine in GCP.

In the following years, cloud providers started to offer platforms where developers could only run their applications. With this abstraction, manual server provisioning, security updates, and server failures became the concerns of the cloud provider. These offerings are known as Platform-as-a-Service (PaaS) since they only focus on running applications and their data on their platforms. Heroku is the most popular PaaS provider, although each cloud provider has its own PaaS products, such as AWS Elastic Beanstalk or Google App Engine. Similar to IaaS, PaaS is still in use in software development.

In the top-level abstraction, the functions of the applications operate as the unit of control in serverless architectures. This known as Function-as-a-Service (FaaS) and is offered by all the significant cloud providers in recent years. The abstraction levels from IaaS to PaaS, and finally to FaaS, can be seen in the following diagram:

Figure 2.1: IaaS to PaaS and FaaS transition

Serverless and the Cloud Evaluation Criteria

In order to analyze the FaaS products on the market, it is beneficial to define some criteria so that we can compare products in a structured way. The following topics are essential for every FaaS platform and need detailed investigation before you choose a cloud provider:

  • Programming languages: Functions are deployed and managed inside the cloud provider environments. Therefore, cloud providers define the programming languages that are supported. It is one of the most significant decision factors since implementing the functions in another language is not feasible in most circumstances.
  • Function triggers: Functions are designed to be triggered by cloud provider services and external methods. The conventional techniques are scheduled calls, on-demand calls, and integration with other cloud services, such as databases, queues, and API gateways.
  • Cost: The most compelling characteristic of the serverless architecture is its cost-effectiveness and the mainstream way of calculating the price, that is, pay per request. It is essential to calculate the actual and projected costs for the feasibility of long-running projects.

Cloud providers are expected to be cost-effective, provide as many programming languages as possible, and support various function triggers. There are also additional criteria, such as monitoring, operations, and in-house knowledge level, but these are not directly related to the serverless products of cloud providers. In the upcoming sections, the three most dominant cloud providers will be discussed in terms of their serverless platforms: Amazon Web Services, Google Cloud Platform, and Microsoft Azure.

AWS Lambda

AWS Lambda is the first FaaS offering, and it also created the serverless hype in the industry. It was made public in 2014 and has been widely adopted in the cloud computing world by all levels of organizations. It made it possible for start-ups to create new products in a short amount of time. It also enabled large enterprises such as Netflix to move event-based triggers to serverless functions. With the opportunity of removing the server operation burden, AWS Lambda and serverless became the next trend in the industry. In this section, we will discuss AWS Lambda for programming language support, trigger types, and cost structure. In addition, our very first serverless function will be deployed.

Note

The official website of AWS Lambda can be found here if you wish to find out more: https://aws.amazon.com/lambda.

AWS Lambda supports the Java, Python, Node.js, C#, Ruby, and Go programming languages when it comes to serverless functions. Furthermore, AWS Lambda provides an API called AWS Lambda Runtime Interface to enable the integration of any language as a custom runtime. Therefore, it could be stated that AWS Lambda natively supports a rich set of popular languages while allowing an extension to other programming languages.

AWS Lambda is designed to have event-triggered functions. This is where the functions process the events that have been retrieved from event sources. Within the AWS ecosystem, various services can be an event source, including the following:

  • Amazon S3 file storage for instances when new files are added
  • Amazon Alexa to implement new skills for voice assistance
  • Amazon CloudWatch Events for the events that occur in the state changes of cloud resources
  • Amazon CodeCommit for when developers push new commits to the code repository

In addition to these services, the essential AWS service for the serverless event source is the Amazon API Gateway. It has the REST API ability to invoke Lambda functions over HTTPS, and it permits the management of multiple Lambda functions for different methods, such as GET, POST, PATCH, and DELETE. In other words, API Gateway creates a layer between the serverless functions and the outside world. This layer also handles the security of the Lambda functions by protecting them against Distributed Denial of Service (DDoS) attacks and defining throttles. The trigger types and the environment are highly configurable for AWS Lambda functions if you want to integrate with other AWS services or make them public via the API Gateway.

For the pricing of AWS Lambda, there are two critical points to take note of: the first one is the request charges and the second one is the compute charges. Request charges are based on the number of function invocations, while compute charges are calculated as GB per second. The compute charge is the multiplication of memory size and execution time:

  • Memory Size (GB): This is the configured allocated memory for the functions.
  • Execution time (ms): This is the realized execution time that the functions will be running for.

In addition, there is a free tier where the first 1 million request charges and 400,000 GB per second of compute charges are waived monthly. A simple calculation, including the free tier, can show how cheap running a serverless function could be.

Let's assume that your function is called 30 million times in a month. You have allocated 128 MB of memory, and on average, the function runs for 200 ms:

Request charges:

Price: $0.20 per 1 M requests

Free tier: 1 M

Monthly request: 30 M

Monthly request charge: 29 M x $0.20 / M = $5.80

Compute charges:

Price: $0.0000166667 per GB per second

Free tier: 400,000 GB per second

Monthly compute: 30 M x 0.2 second x 128 MB / 1024 = 750,000 GB per second

Monthly compute charge: 350,000 x $0.0000166667 = $5.83

Monthly total cost: $5.80 + $5.83 = $11.63

This calculation shows that it is possible to run a serverless AWS Lambda environment where you receive 1 million daily function calls at a monthly cost of $11.63. This indicates both how cheap it is to run serverless workloads and the essential characteristics to consider in serverless economics. In the following exercise, our very first serverless function will be deployed to AWS Lambda and will be invoked to show the operational view of the platform.

Note

In order to complete this exercise, you will need to have an active Amazon Web Services account. You can create an account at https://aws.amazon.com/.

Exercise 4: Creating a Function in AWS Lambda and Invoking It via the AWS Gateway API

In this exercise, we will be creating our first AWS Lambda function and connecting it to AWS Gateway API so that we can invoke over its HTTP endpoint.

To successfully complete this exercise, we need to ensure that the following steps are executed:

  1. Open the AWS Management Console, write Lambda in the Find Services search box, and click Lambda - Run Code without Thinking about Servers. The console will look as follows:
    Figure 2.2: AWS Management Console
  2. Click on Create function in the Lambda functions list, as shown in the following screenshot:
    Figure 2.3: AWS Lambda – functions list
  3. Select Author from scratch in the Create function view. Write hello-from-lambda as the function name and Python 3.7 as the runtime. Click Create function at the bottom of the screen, as shown in the following screenshot:
    Figure 2.4: AWS Lambda – Create function view
  4. You will be directed to the hello-from-lambda function view, which is where you
  5. can edit the Function code, as shown in the following screenshot:
    Figure 2.5: AWS Lambda – hello-from-lambda
  6. Change the lambda_handler function as follows:

    import json

    def lambda_handler(event, context):

        return {

            'statusCode': '200',

            'body': json.dumps({"message": "hello", "platform": "lambda"}),

            'headers': {

                'Content-Type': 'application/json',

            }

        }

  7. Click Save at the top of the screen, as shown in the following screenshot:
    Figure 2.6: AWS Lambda – hello-from-lambda function code
  8. Open the Designer view and click Add trigger, as shown in the following screenshot:
    Figure 2.7: AWS Lambda – hello-from-lambda designer view
  9. Select API Gateway from the triggers list, as shown in the following screenshot:
    Figure 2.8: AWS Lambda – trigger list
  10. Select Create a new API for the API and Open for the Security configurations on the trigger configuration screen, as shown in the following screenshot:
    Figure 2.9: AWS Lambda – Trigger configuration

    On this screen, a new API has been defined in the API Gateway with open security for the hello-from-lambda function. This configuration ensures that an endpoint will be created and that it will be accessible without any authentication.

  11. Click Add at the bottom of the screen.

    You will be redirected to the hello-from-lambda function, with a notification saying The function is now receiving events from the trigger. In the Designer view, the function from Lambda is connected to the API Gateway for triggering and Amazon CloudWatch Logs for logging. In other words, it is now possible to trigger functions via the API Gateway endpoint and check their outputs in CloudWatch, as shown in the following screenshot:

    Figure 2.10: AWS Lambda – trigger added
  12. Get the API Gateway endpoint from the API Gateway section, as shown in the following screenshot:
    Figure 2.11: AWS Lambda – trigger URL
  13. Open the URL in a new tab to trigger the function and get the response, as shown in the following screenshot:
    Figure 2.12: AWS Lambda – function response

    This JSON response indicates that the AWS Lambda function is connected via the API Gateway and working as expected.

  14. Return to the Functions list from Step 2, select hello-from-lambda, and choose Delete from Actions. Then, click Delete in the pop-up window to remove the function from Lambda, as shown in the following screenshot:
Figure 2.13: AWS Lambda – function deletion

In this exercise, the general flow of creating an AWS Lambda function and connecting to the AWS Gateway API for HTTP access was shown. In less than 10 steps, it is possible to have running production-ready services in an AWS Lambda cloud environment. This exercise has shown you how serverless platforms can make software development fast and easy. In the following section, the analysis of cloud provider serverless platforms will continue with Azure Functions by Microsoft.

Azure Functions

Microsoft announced Azure Functions in 2016 as the serverless platform in the Microsoft Azure cloud. Azure Functions extends its cloud platform with event triggers from Azure or external services to run serverless workloads. It differentiates by focusing on the Microsoft supported programming languages and tools that are highly prevalent in the industry. In this section, Azure Functions will be discussed in terms of the supported programming languages, trigger types, and cost. Finally, we will deploy a function that takes parameters from endpoints to Azure Functions to illustrate its operational side.

Note

The official website of Azure Functions can be found here if you wish to find out more: https://azure.microsoft.com/en-us/services/functions/.

The latest version of Azure Functions supports C#, JavaScript in the Node.js runtime, F#, Java, PowerShell, Python, and Typescript, which is transpired into JavaScript. In addition, a language extensibility interface is provided for the communication between the functions runtime and the worker processes over gRPC as a messaging layer. It is valuable to check the generally available, experimental, and extendible programming languages supported by Azure Functions before we start utilizing it.

Note

gRPC is a remote procedure call (RPC) system that was initially developed at Google. It is an open source system that enables cross-platform communication without language or platform limitations.

Azure Functions are designed to be triggered by various types, such as timers, HTTP, file operations, queue messages, and events. In addition, input and output bindings can be specified for functions. These bindings define the input arguments for the functions and output values to send other services. For instance, it is possible to create a scheduled function to read files from Blob Storage and create Cosmos DB documents as outputs. In this example, the function could be defined with a timer trigger, Blob Storage input binding, and Cosmos DB output binding. Triggers and bindings make Azure Functions easily integrate to Azure services and the external world.

There are two differences between the cost calculation method and the current prices of Azure Functions compared to AWS Lambda. The first difference is that the current computation price of Azure Functions is slightly cheaper, at $0.000016/GB per second. The second difference is that Azure Functions calculates using observed memory consumption while the memory limit is preconfigured in AWS Lambda.

In the following exercise, the very first serverless function will be deployed to Azure Functions and will be invoked to show the operational view of the platform.

Note

In order to complete this exercise, you need to have an active Azure account. You can create an account at https://signup.azure.com/.

Exercise 5: Creating a Parameterized Function in Azure Functions

In this exercise, we aim to create a parameterized function in Azure and invoke it over its HTTP endpoint with different parameters.

To successfully complete this exercise, we need to ensure the following steps are executed:

  1. Click on Function App in the left menu of the Azure home page, as shown in the following screenshot:
    Figure 2.14: Azure home page
  2. Click on Create Function App from the Function App list, as shown in the following screenshot:
    Figure 2.15: Function App list
  3. Give the app a unique name, such as hello-from-azure, and select Node.js as the Runtime Stack. Click on Create at the bottom of the page, as shown in the following screenshot:
    Figure 2.16: Creating a Function App
  4. You will be redirected to the Function App list view. Check for a notification at the top of the menu. You will see Deployment to resource group 'hello-from-azure' is in progress, as shown in the following screenshot:
    Figure 2.17: Deployment in progress

    Wait a couple of minutes until the deployment is complete:

    Figure 2.18: Successful deployment
  5. Click on + New Function in the hello-from-azure function app view, as shown in the following screenshot:
    Figure 2.19: hello-from-azure function app
  6. Select In-portal for function creation inside the Azure web portal as a development environment and click Continue, as shown in the following screenshot:
    Figure 2.20: Function development environment
  7. Select Webhook + API and click Create, as shown in the following screenshot:
    Figure 2.21: Function trigger types

    In this view, it is possible to create functions from templates such as webhooks, timers, or collaborative templates from the marketplace.

  8. Write the following function into index.js and click Save:

    module.exports = async function (context, req) {

        context.log('JavaScript HTTP trigger function processed a request.');

        if (req.query.name || (req.body && req.body.name)) {

            context.res = {

                status: 200,

                body: "Hello " + (req.query.name || req.body.name) +", it is your function in Azure!"

            };

        }

        else {

            context.res = {

                status: 400,

                body: "Please pass a name on the query string or in the request body."

            };

        }

    };

    This code exports a function that accepts parameters from the request. The function creates a personalized message and sends it as output to the users. The code should be inserted into the code editor, as shown in the following screenshot:

    Figure 2.22: index.js of the hello-from-azure function
  9. Click on Get function URL and copy the URL inside the popup, as shown in the
  10. following screenshot:
    Figure 2.23: Function URL
  11. Open the URL you copied in Step 7 into a new tab in the browser, as shown in the following screenshot:
    Figure 2.24: Function response without parameter

    Add &name= and your name to the end of the URL and reload the tab, for example, https://hello-from-azure.azurewebsites.net/api/HttpTrigger?code=nNrck...&name=Onur, as shown in the following screenshot:

    Figure 2.25: Function response with parameter

    These responses show that it is possible to validate and pass parameters to functions. Passing parameters and their validation is essential for serverless functions and when considering the possibility of various integration points as triggers and bindings.

  12. Return to the Function App list from Step 2, click ... alongside the new function we've created, and select Delete, as shown in the following screenshot:
Figure 2.26: Deleting a function

Type the name of the function into the pop-up view and click Delete to delete all the resources. In the confirmation view, a warning indicates that deletion of the function application is irreversible, as you can see in the following screenshot:

Figure 2.27: Deleting the function and its resources

In the following section, Google Cloud Functions will be discussed in a similar way, and a more complicated function will be deployed to the cloud provider.

Google Cloud Functions

Google Cloud Functions was made public in 2017 just after AWS Lambda and Azure Functions. Serverless functions were already available for the PaaS product of Google, namely Firebase, before the release of Google Cloud Functions. However, Google Cloud Functions was made available to all the services inside the Google Cloud Platform as its core serverless cloud product. In this section, Google Cloud Functions will be discussed in terms of the supported programming languages, trigger types, and cost. Finally, we will deploy a function that is periodically invoked by cloud services to Google Cloud Functions to illustrate its operational side.

Note

The official website of Google Cloud Functions can be found here if you wish to find out more: https://cloud.google.com/functions/.

Google Cloud Functions (GCF) can be developed in Node.js, Python, and Go. Compared to the other major cloud providers, GCF supports a small subset of languages. In addition, there are no publicly available language extension or APIs supported by GCF. Thus, it is essential to evaluate whether the languages supported by GCF are feasible for the functions you will develop.

Google Cloud Functions are designed to be associated with triggers and events. Events happen within your cloud services, such as database changes, new files in the storage system, or when provisioning new virtual machines. Triggers are the declaration of the services and related events as inputs to functions. It is possible to create triggers as HTTP endpoints, Cloud Pub/Sub queue messages, or storage services such as Cloud Storage and Cloud Firestore. In addition, functions can be connected to the big data and machine learning services that are provided in the Google Cloud Platform.

The cost calculation of Google Cloud Platform is slightly complex compared to other cloud providers. This is because it takes the invocations, computation time, and outbound network data into consideration, while other cloud providers focus only on invocations and compute time:

  • Invocations: Function invocations are charged $0.40 for every one million requests.
  • Compute time: The computation times of the functions are measured from the time of invocation to their completion in 100 ms increments. For instance, if your function takes 240 ms to complete, you will be charged for 300 ms of computation time. There are two units that are used in this calculation – GB per second and GHz per second. 1 GB of memory is provisioned for a function running for 1 second, and the price of 1 GB per second is $0.0000025. Also, 1 GHz of CPU is provisioned for a function running for 1 second, and the price of 1 GHz per second is $0.0000100.
  • Outbound network data: Data that's transferred from the function to the outside is measured in GB and charged at $0.12 for every GB of data.

GCF's free tier provides 2 million invocations, 400,000 GB per second, 200,000 GHz per second of computation time, and 5 GB of outbound network traffic per month. Compared to AWS or Azure, GCP will cost slightly more since it has higher prices and more sophisticated calculation methods.

Let's assume that your function is called 30 million times in a month. You have allocated 128 MB of memory, 200 MHz CPU, and on average, the function runs for 200 ms, similar to the example for AWS Lambda:

Request charges:

Price: $0.40 per 1 M request

Free tier: 2 M

Monthly request: 30 M

Monthly request charge = 28 M x $0.40 / M = $11.2

Compute charges - Memory:

Price: $0.0000025 per GB-second

Free tier: 400,000 GB-Seconds

Monthly compute: 30 M x 0.2 second x 128 MB / 1024 = 750,000 GB-second

Monthly memory charge: 350,000 x $0.0000025 = $0.875

Compute charges - CPU:

Price: $0.0000100 per GHz-second

Free tier: 200,000 GB-Seconds

Monthly compute: 30 M x 0.2 second x 200 MHz / 1000 GHz = 1,200,000 GHz-second

Monthly CPU charge: 1,000,000 x $0.0000100 = $10

Monthly total cost= $11.2 + $0.875 + $10 = $22.075

Since the unit prices are slightly higher than AWS and Azure, the total monthly cost of running the same function is more than $22 in GCP, while it was around $11 for AWS and Azure. Also, any outbound network from the functions to the outside world is critical when it comes to potential extra costs. Therefore, pricing methods and unit prices should be analyzed in depth before you choose a serverless cloud platform.

In the following exercise, our very first serverless function will be deployed to GCF and will be invoked by a scheduled trigger to show the operational view of the platform.

Note

In order to complete this exercise, you need to have an active Google account. You can create an account at https://console.cloud.google.com/start.

Exercise 6: Creating a Scheduled Function in GCF

In this exercise, we aim to create a scheduled function in Google Cloud Platform and check its invocation by using cloud scheduler services.

To successfully complete this exercise, we need to ensure the following steps are executed:

  1. Click on Cloud Functions in the left menu, which can be found in the Compute group on the Google Cloud Platform home page, as shown in the following screenshot:
    Figure 2.28: Google Cloud Platform home page
  2. Click on Create function on the Cloud Functions page, as shown in the following screenshot:
    Figure 2.29: Cloud Functions page
  3. In the function creation form, change the function name to HelloWorld and select 128 MB for the memory allocation. Ensure that HTTP is selected as the trigger method and that Go 1.11 is selected as the runtime, as shown in the following screenshot:
    Figure 2.30: Function creation form
  4. Change function.go using the inline editor inside the browser so that it has the following content:

    package p

    import (

    "fmt"

    "net/http"

    )

    func HelloWorld(w http.ResponseWriter, r *http.Request) {

    fmt.Fprint(w, "Hello World from Google Cloud Functions!")

    return

    }

    This code segment creates a HelloWorld function with a static message printed to the output. The code should be inserted into function.go in the code editor, as shown in the following screenshot:

    Figure 2.31: Function inline editor
  5. Copy the URL in the form below the Trigger selection box to invoke the function, as shown in the following screenshot:
    Figure 2.32: Function trigger URL
  6. Click on the Create button at the end of the form. With this configuration, the code from step 4 will be packaged and deployed to Google Cloud Platform. In addition, a trigger URL will be assigned to the function to be reachable from outside, as shown in the following screenshot:
    Figure 2.33: Function creation

    Wait a couple of minutes until the HelloWorld function in the function list has a green check icon next to it, as shown in the following screenshot:

    Figure 2.34: Function deployment
  7. Open the URL you copied in step 5 into a new tab in your browser, as shown in the following screenshot:
    Figure 2.35: Function response

    The response shows that the function has been successfully deployed and is running as expected.

  8. Click on Cloud Scheduler in the left menu, under TOOLS, as shown in the following screenshot:
    Figure 2.36: Google Cloud Tools Menu
  9. Click on Create job on the Cloud Scheduler page, as shown in the following screenshot:
    Figure 2.37: Cloud Scheduler page
  10. Select a region if you are using Cloud Scheduler for the first time in your Google Cloud project and click Next, as shown in the following screenshot:
    Figure 2.38: Cloud Scheduler – region selection

    Wait for a couple of minutes if you see the following notification:

    We are initializing Cloud Scheduler in your selected region. This usually takes about a minute.

  11. Set the job name as HelloWorldEveryMinute and the frequency as * * * * *, which means the job will be triggered every minute. Select HTTP as the target and paste the URL you copied in step 5 into the URL box, as shown in the following screenshot:
    Figure 2.39: Scheduler job creation
  12. You will be redirected to the Cloud Scheduler list, as shown in the following screenshot:
    Figure 2.40: Cloud Scheduler page

    Wait for a couple of minutes and click the Refresh button. The list will show the Last run timestamp and its result for HelloWorldEveryMinute, as shown in the following screenshot:

    Figure 2.41: Cloud Scheduler page with run information

    This indicates that the cloud scheduler triggered our function at Aug 13, 2019, 3:44:00 PM and that the result was successful.

  13. Return to the function list from step 7 and click for the HelloWorld function. Then, click Logs, as shown in the following screenshot:
    Figure 2.42: Settings menu for the function

    You will be redirected to the logs of the function, where you will see that, every minute, Function execution started and the corresponding success logs are listed, as shown in the following screenshot:

    Figure 2.43: Function logs

    As you can see, the cloud scheduler is invoking the function as planned and that the function is running successfully.

  14. Return to the Cloud Scheduler page from Step 13, choose HelloWorldEveryMinute, click Delete on the menu, and then confirm this in the popup, as shown in the following screenshot:
    Figure 2.44: Cloud Scheduler – job deletion
  15. Return to the Cloud Functions page from step 7, choose HelloWorld, click Delete on the menu, and then confirm this in the popup, as shown in the following screenshot:
Figure 2.45: Cloud Functions – function deletion

In this exercise, we created a Hello World function and deployed it to GCF. In addition, a cloud scheduler job was created to trigger the function with specific intervals such as every minute. Now, the function is connected to another cloud service so that the function can trigger the service. It is essential to integrate functions with other cloud services and evaluate their integration capabilities prior to choosing a cloud FaaS provider.

In the following activity, you will develop a real-life daily stand-up reminder function. You will connect a function and function trigger service you wish to invoke on your specific stand-up meeting time. In addition, this reminder will send a specific message to a cloud-based collaboration tool, namely Slack.

Activity 2: Daily Stand-Up Meeting Reminder Function for Slack

The aim of this activity is to create a real-life function for stand-up meeting reminders in Slack. This reminder function will be invoked at specific times for your team to remind everyone in your team about the next stand-up meeting. The reminder will work with Slack since it is a popular collaboration tool that's been adopted by numerous organizations worldwide.

Note

In order to complete this activity, you need to access a Slack workplace. You can use your existing Slack workspace or create a new one for free at https://slack.com/create.

Once completed, you will have deployed a daily stand-up reminder function to GCF, as shown in the following screenshot:

Figure 2.46: Daily reminder function

In addition, you will need an integration environment for invoking the function at specified meeting times. Stand-up meetings generally take place at a specific time on workdays. Thus, a scheduler job will be connected to trigger your function according to your meeting time, as shown in the following screenshot:

Figure 2.47: Daily reminder scheduler

Finally, when the scheduler invokes the function, you will have reminder messages in your Slack channel, as shown in the following screenshot:

Figure 2.48: Slack message for meeting reminder

Note

In order to complete this activity, you should configure Slack by following the Slack Setup steps.

Slack Setup

Execute the following steps to configure Slack:

  1. In the Slack workspace, click on your username and select Customize Slack.
  2. Click on Configure apps in the open window.
  3. Click on Browse the App Directory to add a new application from the directory.
  4. Find Incoming WebHooks from the search box in App Directory.
  5. Click on Add Configuration for the Incoming WebHooks application.
  6. Fill in the configuration for the incoming webhook with your specific channel name and icon.
  7. Open your Slack workspace and channel. You will see an integration message.

    Note

    Detailed screenshots of the Slack setup steps can be found on page 376.

Execute the following steps to complete this activity:

  1. Create a new function in GCF to call the Slack webhook when it is invoked.

    The code should send a JSON request to the Slack webhook URL with a similar object: {"text": "Time for a stand-up meeting"}. You can implement the code in any language that's supported by GCF. The code snippet is as follows:

    package p

    import (

        "bytes"

        "net/http"

    )

    func Reminder(http.ResponseWriter, *http.Request) {

        url := "https://hooks.slack.com/services/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"

        

        var jsonStr = []byte('{"text": "Time for a stand-up meeting!"}')

        req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))

        

        client := &http.Client{}

        _, err = client.Do(req)

        if err != nil {

            panic(err)

        }

    }

  2. Create a scheduler job in GCP with the trigger URL of the function and specify the schedule based on your stand-up meeting times.

    Check the Slack channel when the time that's been defined with the schedule has arrived for the reminder message.

  3. Delete the schedule job and function from the cloud provider.

    Note

    The solution to this activity can be found on page 376.