Triggering from Cloud Pub/Sub push

You can use Cloud Pub/Sub to push messages to the endpoint of your Cloud Run service, which are subsequently delivered to containers as HTTP requests. You should process the message and then return a response when finished.

Leveraging service accounts and IAM permissions, you can securely and privately use Cloud Pub/Sub with Cloud Run, without having to expose your Cloud Run service publicly. Only the Cloud Pub/Sub subscription that you have set up is able to invoke your service.

Possible use cases include:

This page shows how to enable your service to securely process messages pushed from a Cloud Pub/Sub subscription in the same GCP project.

To integrate your service with Cloud Pub/Sub,

  • Create a Cloud Pub/Sub topic.
  • Add code in your Cloud Run service to respond to the Cloud Pub/Sub messages sent to the topic you created.
  • Create a service account with the required permissions.
  • Create a Cloud Pub/Sub subscription and associate it with the service account. This subscription will send to your service any message that is published to the topic.

Before you start

If you haven't done so already, set up your environment as described in the setup page for Cloud Run or the setup page for Cloud Run on GKE. You'll need to use the gcloud command line and a GCP project to deploy your Cloud Run service to.

Creating a Cloud Pub/Sub topic

Requests to your service are triggered by messages published to a Cloud Pub/Sub topic, so you'll need to create a topic:

Console

  1. Visit the Cloud Pub/Sub topics page in the GCP Console.

    Cloud Pub/Sub topics page

  2. Click Create a topic.

  3. Enter a unique Name for your topic, for example, MyTopic.

Command line

gcloud pubsub topics create TOPIC-NAME

Replace TOPIC-NAME with a topic name unique within your GCP project.

Adding code to handle messages from Cloud Pub/Sub

Your service must extract the message from the request and return an expected success code. The following snippets for Go and Node.js (you can use any language) show how to do this for a simple Hello World message:

Node.js

app.post('/', (req, res) => {

  if (!req.body) {
    const msg = 'no Pub/Sub message received'
    console.error(`error: ${msg}`)
    res.status(400).send(`Bad Request: ${msg}`)
    return
  }
  if (!req.body.message) {
    const msg = 'invalid Pub/Sub message format'
    console.error(`error: ${msg}`)
    res.status(400).send(`Bad Request: ${msg}`)
    return
  }

  const pubSubMessage = req.body.message
  const name = pubSubMessage.data
    ? Buffer.from(pubSubMessage.data, 'base64').toString().trim()
    : 'World'

  console.log(`Hello ${name}!`)
  res.status(204).send()
})

Go

// PubSubMessage is the payload of a Pub/Sub event. Please refer to the docs for
// additional information regarding Pub/Sub events.
type PubSubMessage struct {
	Message struct {
		Data []byte `json:"data,omitempty"`
		ID   string `json:"id"`
	} `json:"message"`
	Subscription string `json:"subscription"`
}

// HelloPubSub consumes a Pub/Sub message.
func HelloPubSub(w http.ResponseWriter, r *http.Request) {
	// Parse the Pub/Sub message.
	var m PubSubMessage

	if err := json.NewDecoder(r.Body).Decode(&m); err != nil {
		log.Printf("json.NewDecoder: %v", err)
		http.Error(w, "Bad Request", http.StatusBadRequest)
		return
	}

	name := string(m.Message.Data)
	if name == "" {
		name = "World"
	}
	log.Printf("Hello %s!", name)
}

Use success codes such as HTTP 200 or 204, to acknowledge complete processing of the Cloud Pub/Sub message. Return error codes such as HTTP 400 or 500 if there is a failure. If you don't return a success code, Cloud Pub/Sub automatically resends the message.

Create a service account for the subscription

You need to create a service account to associate with your Cloud Pub/Sub subscription, and give it the permission to invoke your Cloud Run service. Cloud Pub/Sub messages pushed to your Cloud Run service will carry the identity of this service account.

You can use an existing service account to represent the Cloud Pub/Sub subscription identity, or you can create a new one.

To create a new service account:

Console

  1. Visit the Create service account key page in the GCP Console.

    Create service account page

  2. From the Service account list, select New service account.

  3. In the Service account name field, enter the name you want to use for the service account.

  4. From the Role list, select Cloud Run > Cloud Run Invoker.

  5. Click Create.

Command line

  1. Create the service account:

    gcloud iam service-accounts create SERVICE-ACCOUNT_NAME \
    --display-name "DISPLAYED-SERVICE-ACCOUNT_NAME"

    Replace

    • SERVICE-ACCOUNT_NAME with a lower case name unique within your GCP project, for example my-invoker-service-account-name.
    • DISPLAYED-SERVICE-ACCOUNT-NAME with the name you want to display for this service account, for example, in the console, for example, My Invoker Service Account.
  2. For Cloud Run, give your service account permission to invoke your service:

    gcloud beta run services add-iam-policy-binding SERVICE \
         --member=serviceAccount:SERVICE-ACCOUNT_NAME@PROJECT-ID.iam.gserviceaccount.com \
         --role=roles/run.invoker

    Replace

    • SERVICE with the name of the service you want to subscribe to the Cloud Pub/Sub messages.
    • SERVICE-ACCOUNT_NAME with the name of the service account.
    • PROJECT-ID with your GCP project ID.

If you are using Cloud Run on GKE, you must verify the identity within the container. See the Cloud IAP sample code that demonstrates this.

Create a push subscription and associate it with the service account

You must subscribe your service to receive messages sent to a topic, and you must associate the subscription with the service account you created for your service. You can use either the GCP Console or the gcloud command line:

Console

  1. Go to the Cloud Pub/Sub topics page.

    Cloud Pub/Sub topics page

  2. Click the topic you want to subscribe to.

  3. Click Create Subscription to display the subscription form:

    subscription form

    In the form,

    1. Specify the push delivery type.
    2. For Endpoints URL, specify your service's URL, which is displayed in the service detail page.
    3. In the Service Account dropdown, select the service account that you created with the required permissions.
    4. Set subscription expiration and acknowledgement deadline as desired.
    5. Click Create.
  4. The subscription is complete. Messages posted to the topic will now be pushed into your service.

Command line

  1. Enable your project to create Cloud Pub/Sub authentication tokens:

    gcloud projects add-iam-policy-binding PROJECT-ID \
         --member=serviceAccount:service-PROJECT-NUMBER@gcp-sa-pubsub.iam.gserviceaccount.com \
         --role=roles/iam.serviceAccountTokenCreator

    Replace

    • PROJECT-ID with your GCP project ID.
    • PROJECT-NUMBER with your GCP project number.

      Project ID and project number are listed in the Project info panel in the GCP Console for your project.

  2. Create a Cloud Pub/Sub subscription with the service account that you created with the required permissions:

    gcloud beta pubsub subscriptions create SUBSCRIPTION-ID --topic TOPIC-NAME \
       --push-endpoint=SERVICE-URL/ \
       --push-auth-service-account=SERVICE-ACCOUNT_NAME@PROJECT-ID.iam.gserviceaccount.com

    Replace

    • TOPIC-NAME with the topic you previously created.
    • SERVICE-URL with the HTTPS URL that was provided when you deployed the service. You can find it by using the command gcloud beta run services describe, specifing the name of your service: look for the return line starting with domain.
    • PROJECT-ID with your GCP project ID.

    The --push-account-service-account flag activates the Cloud Pub/Sub push functionality for Authentication and authorization

  3. The subscription is complete. Messages posted to the topic will now be pushed into your service. You can push a test message to the topic using the command:

    gcloud pubsub topics publish TOPIC --message "hello"

    Replace TOPIC with the name of the topic you created.

What's next

Оцените, насколько информация на этой странице была вам полезна:

Оставить отзыв о...

Текущей странице
Cloud Run Documentation