This tutorial shows you how to use Cloud Tasks within an App Engine application to trigger a Cloud Run function and send a scheduled email.
Objectives
- Understand the code in each of the components.
- Create a SendGrid account.
- Download the source code.
- Deploy a Cloud Run function to receive Cloud Tasks requests and send an email via the SendGrid API.
- Create a Cloud Tasks queue.
- Create a service account to authenticate your Cloud Tasks requests.
- Deploy the client code that allows a user to send an email.
Costs
Cloud Tasks, Cloud Run functions, and App Engine have a free tier, so as long as you are running the tutorial within the free tier of the given products it should not result in additional costs. For more information, see Pricing.
Before you begin
Select or create a Google Cloud project.
Initialize an App Engine application in your project:
On the Welcome to App Engine page click Create Application.
Select a region for your application. This location will serve as the
LOCATION_ID
parameter for your Cloud Tasks requests, so make a note of it. Note that two locations, called europe-west and us-central in App Engine commands, are called, respectively, europe-west1 and us-central1 in Cloud Tasks commands.Select Node.js for the language and Standard for the environment.
If the Enable billing popup appears, select your billing account. If you do not currently have a billing account, click Create billing account and follow the wizard.
On the Get started page, click Next. You'll take care of this later.
Enable the Cloud Run functions and Cloud Tasks APIs.
Install and initialize the gcloud CLI.
Understanding the code
This section walks you through the app's code and explains how it works.
Creating the task
The index page is served using handlers in the app.yaml
. The variables needed for task creation are passed in as environment variables.
This code creates the endpoint /send-email
. This endpoint handles form submissions from the index page and passes that data to the task creation code.
This code actually creates the task and sends it on to the Cloud Tasks queue. The code builds the task by:
Specifying the target type as
HTTP Request
.Specifying the
HTTP method
to be used and theURL
of the target.Setting the
Content-Type
header toapplication/json
so downstream applications can parse the structured payload.Adding a service account email so that Cloud Tasks can provide credentials to the request target, which requires authentication. The service account is created separately.
Checking to make sure the user input for date is within the 30 days maximum and adding it to the request as field
scheduleTime
.
Creating the email
This code creates the Cloud Run function that is the target for the Cloud Tasks request. It uses the request body to construct an email and send it via the SendGrid API.
Preparing the application
Setting up SendGrid
Create a SendGrid account.
- You can either do this manually via the SendGrid website
- or you can use the Google Cloud Launcher, which will create an account for you and integrate billing. See Creating a SendGrid account using Cloud Launcher.
Create a SendGrid API key:
Log in to your SendGrid account.
In the left hand navigation open Settings and click API Keys.
Click Create API Key and select restricted access. Under the Mail Send header, select Full Access.
Copy the API Key when it is displayed (you will only see this once, make sure you paste it somewhere so you can use it later on).
Downloading the source code
Clone the sample app repository to your local machine:
git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git
Change to the directory that contains the sample code:
cd cloud-tasks/
Deploying the Cloud Run function
Navigate to the
function/
directory:cd function/
Deploy the function:
gcloud functions deploy sendEmail --runtime nodejs14 --trigger-http \ --no-allow-unauthenticated \ --set-env-vars SENDGRID_API_KEY=SENDGRID_API_KEY \
Replace
SENDGRID_API_KEY
with your API key.This command uses flags:
--trigger-http
to specify the Cloud Run functions trigger type.--no-allow-unauthenticated
to specify the function invocation requires authentication.--set-env-var
to set your SendGrid credentials
Set access control for the function to only allow authenticated users.
Select the
sendEmail
function in the Cloud Run functions UI.If you don't see permissions info for
sendEmail
, click SHOW INFO PANEL in the upper right hand corner.Click the Add principals button above.
Set New principals to
allAuthenticatedUsers
.Set the Role.
- First generation (1st gen) functions: set the role to
Cloud Function Invoker
- Second generation (2nd gen) functions: set the role to
Cloud Run Invoker
- First generation (1st gen) functions: set the role to
Click SAVE.
Creating a Cloud Tasks queue
Create a queue using the following
gcloud
command:gcloud tasks queues create my-queue --location=LOCATION
Replace
LOCATION
with your preferred location for the queue, for example,us-west2
. If you do not specify the location, the gcloud CLI picks the default.Verify that it was created successfully:
gcloud tasks queues describe my-queue --location=LOCATION
Replace
LOCATION
with the location of the queue.
Creating a service account
The Cloud Tasks request must provide credentials in the Authorization
header for the Cloud Run function to authenticate the request. This service account allows Cloud Tasks to create and add an OIDC token for that purpose.
In the Service accounts UI, click +CREATE SERVICE ACCOUNT.
Add a service account name(friendly display name) and select create.
Set the Role and click Continue.
- First generation (1st gen) functions: set the role to
Cloud Function Invoker
- Second generation (2nd gen) functions: set the role to
Cloud Run Invoker
- First generation (1st gen) functions: set the role to
Select Done.
Deploying the endpoint and the task creator to App Engine
Navigate to
app/
directory:cd ../app/
Update variables in the
app.yaml
with your values:To find your queue location, use the following command:
gcloud tasks queues describe my-queue --location=LOCATION
Replace
LOCATION
with the location of the queue.To find your function URL, use the following command:
gcloud functions describe sendEmail
Deploy the application to the App Engine standard environment, using the following command:
gcloud app deploy
Open the application to send a postcard as an email:
gcloud app browse
Clean up
After you finish the tutorial, you can clean up the resources that you created so that they stop using quota and incurring charges. The following sections describe how to delete or turn off these resources.
Deleting Resources
You can clean up the resources that you created on Google Cloud so they won't take up quota and you won't be billed for them in the future. The following sections describe how to delete or turn off these resources.
Delete the Cloud Run function
Go to the Cloud Run functions page in the Google Cloud console.
Click the checkboxes next to your functions.
Click the Delete button at the top of the page and confirm your delete.
Delete the Cloud Tasks queue
Open the Cloud Tasks queues page in the console.
Select the name of the queue you want to delete and click Delete queue.
Confirm the action.
Deleting the project
The easiest way to eliminate billing is to delete the project that you created for the tutorial.
To delete the project:
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.
What's next
- Learn more about creating HTTP target tasks.
- Learn more about configuring your Cloud Tasks queue.