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.
- Create a service account to authenticate your Cloud Tasks requests.
- Deploy a Cloud Run function to receive Cloud Tasks requests and send an email using the SendGrid API.
- Create a Cloud Tasks queue.
- Deploy the client code that lets a user 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_IDparameter 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 methodto be used and theURLof the target.Setting the
Content-Typeheader toapplication/jsonso 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 verifies the OpenID Connect (OIDC) bearer
token from Cloud Tasks and checks that the recipient address is in
the ALLOWED_RECIPIENT_EMAILS environment variable. The function then escapes
user-supplied fields in the HTML postcard and sends the email by using 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.gitChange to the directory that contains the sample code:
cd nodejs-docs-samples/cloud-tasks/tutorial-gcf/
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 lets Cloud Tasks
create and add an OIDC token
to authenticate the request.
In the Google Cloud console, go to the Service accounts page.
Click Create service account.
In the Service account name field, enter a name, and then click Create and continue.
Click Done. You grant this service account permission to invoke the
sendEmailfunction after deploying the function.Note the service account's email address to use for the
SERVICE_ACCOUNT_EMAILenvironment variable in the following sections.
For more information, see Create service accounts.
Deploying the Cloud Run function
Navigate to the
function/directory:cd function/Deploy the function with its required environment variables:
gcloud functions deploy sendEmail --runtime nodejs22 --trigger-http \ --no-allow-unauthenticated \ --set-env-vars SENDGRID_API_KEY=SENDGRID_API_KEY \ --set-env-vars SERVICE_ACCOUNT_EMAIL=SERVICE_ACCOUNT_EMAIL \ --set-env-vars "^;^ALLOWED_RECIPIENT_EMAILS=ALLOWED_RECIPIENT_EMAILS"
Replace the following:
SENDGRID_API_KEY: your SendGrid API key.SERVICE_ACCOUNT_EMAIL: the email address of the service account that you created earlier. ThesendEmailfunction verifies this email address in the OIDC token.ALLOWED_RECIPIENT_EMAILS: a comma-separated list of permitted recipient email addresses, for example,user1@example.com,user2@example.com.
This command uses the following flags:
--runtime: specifies the Node.js runtime for the function.--trigger-http: specifies the Cloud Run functions trigger type.--no-allow-unauthenticated: requires authentication to invoke the function.--set-env-vars: sets the required environment variables. Because theALLOWED_RECIPIENT_EMAILSenvironment variable can contain commas, the command uses^;^as an alternate delimiter. For more information about delimiter escaping, seegcloud topic escaping.
Retrieve the HTTPS URL of the deployed function:
gcloud functions describe sendEmail
In the command output, note the HTTPS URL from the
httpsTrigger.urlfield for 1st gen functions, or theserviceConfig.urifield for 2nd gen functions. You need this URL for the next step and for theapp.yamlfile.To output only the URL, append
--format="value(httpsTrigger.url)"for 1st gen functions, or--format="value(serviceConfig.uri)"for 2nd gen functions.To verify the OIDC token
audienceclaim, update the function with theFUNCTION_URLenvironment variable:gcloud functions deploy sendEmail \ --update-env-vars FUNCTION_URL=FUNCTION_URL
Replace
FUNCTION_URLwith the HTTPS URL returned bygcloud functions describe sendEmail.Grant the Cloud Tasks service account permission to invoke
sendEmail:- In the Google Cloud console, go to the Cloud Run functions page.
Select the
sendEmailfunction.If you don't see permissions information for
sendEmail, click Show info panel.Click Add principal.
In the New principals field, enter the email address of the service account that you created earlier. Don't use the
allAuthenticatedUsersprincipal because that grants invocation access to any authenticated Google Account.Select a role:
- First generation (1st gen) functions: select Cloud Functions Invoker (
roles/cloudfunctions.invoker). - Second generation (2nd gen) functions: select Cloud Run Invoker (
roles/run.invoker).
- First generation (1st gen) functions: select Cloud Functions Invoker (
Click Save.
Creating a Cloud Tasks queue
Create a queue using the following
gcloudcommand:gcloud tasks queues create my-queue --location=LOCATION
Replace
LOCATIONwith 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
LOCATIONwith the location of the queue.
Deploying the endpoint and the task creator to App Engine
Navigate to
app/directory:cd ../app/Update variables in the
app.yamlwith your values:To find your queue location, use the following command:
gcloud tasks queues describe my-queue --location=LOCATION
Replace
LOCATIONwith the location of the queue.Use the function URL you previously retrieved.
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 programmatically.
- Learn more about configuring your Cloud Tasks queue.