Publish and receive messages in Pub/Sub by using the gcloud CLI

This page shows you how to do the following operations in Pub/Sub using the Google Cloud CLI:

  • Create a topic and subscription.
  • Publish messages to the topic.
  • Receive messages from the subscription.

For step-by-step guidance on this task directly in Google Cloud console, click Guide me:

Guide me


The following sections take you through the same steps as clicking Guide me.

Before you begin

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Install and initialize the Google Cloud CLI.
  3. Create or select a Google Cloud project.

    • Create a Cloud project:

      gcloud projects create PROJECT_ID
    • Select a Cloud project:

      gcloud config set project PROJECT_ID
  4. Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a project.

  5. Enable the Pub/Sub API.

    gcloud services enable pubsub
  6. Install and initialize the Google Cloud CLI.
  7. Create or select a Google Cloud project.

    • Create a Cloud project:

      gcloud projects create PROJECT_ID
    • Select a Cloud project:

      gcloud config set project PROJECT_ID
  8. Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a project.

  9. Enable the Pub/Sub API.

    gcloud services enable pubsub

Create a topic

Create a topic with the ID my-topic:

gcloud pubsub topics create my-topic

Create a subscription

Create a subscription with the ID my-sub and attach it to my-topic:

gcloud pubsub subscriptions create my-sub --topic=my-topic

Publish messages

Publish a message to my-topic:

gcloud pubsub topics publish my-topic --message="hello"

Receive messages

Receive the message from my-sub:

gcloud pubsub subscriptions pull my-sub --auto-ack

The gcloud CLI prints the message to the command line.

How did it go?

What's next