Create Cloud Storage subscriptions

This document describes how to create a Cloud Storage subscription. You can use the Google Cloud console, the Google Cloud CLI, the client library, or the Pub/Sub API to create a Cloud Storage subscription.

Before you begin

Before reading this document, ensure that you're familiar with the following:

Required roles and permissions

To get the permissions that you need to create a Cloud Storage subscription, ask your administrator to grant you the Pub/Sub Editor (roles/pubsub.editor) IAM role on the project. For more information about granting roles, see Manage access to projects, folders, and organizations.

This predefined role contains the permissions required to create a Cloud Storage subscription. To see the exact permissions that are required, expand the Required permissions section:

Required permissions

The following permissions are required to create a Cloud Storage subscription:

  • pubsub.subscriptions.create on the project
  • pubsub.topics.attachSubscription on the topic

You might also be able to get these permissions with custom roles or other predefined roles.

Cross-project subscriptions

If you create a subscription in one project for a topic in another project, you must have pubsub.subscriptions.create permission on the project in which you are creating the subscription, and pubsub.topics.attachSubscription permission on the topic.

Grant IAM roles to the service account

Pub/Sub uses an Identity and Access Management (IAM) service account to access Google Cloud resources. By default, it uses the Pub/Sub service agent (service-PROJECT_NUMBER@gcp-sa-pubsub.iam.gserviceaccount.com).

To enable Pub/Sub to write to Cloud Storage, the service account requires the following roles:

  • Storage Object Creator (roles/storage.objectCreator)
  • Storage Legacy Bucket Reader (roles/storage.legacyBucketReader)

You can give the service account permissions either for the project or the Cloud Storage bucket, as follows:

Project

  1. In the Google Cloud console, go to the Buckets page.

    Go to Buckets

  2. Select Include Google-provided role grants.

  3. Find the row for the Cloud Pub/Sub service account and click Edit principal.

  4. Click Add another role and select the Storage Object Creator role. Repeat this step for the Storage Legacy Bucket Reader role.

For more information, see Grant an IAM role by using the console.

Cloud Storage bucket

  1. In the Google Cloud console, go to Buckets.

    Go to Buckets

  2. Click the name of the Cloud Storage bucket to which you want to grant permission.

  3. In the Bucket details page, click the Permissions tab.

  4. In the Permissions pane, click the View by principals tab.

  5. Click Grant access.

  6. In the New principals field, enter the service account identifier, in the following format:

    service-PROJECT_NUMBER@gcp-sa-pubsub.iam.gserviceaccount.com.

  7. In the Assign roles list, select Storage Object Creator.

  8. Click Add another role and select Storage Legacy Bucket Reader.

  9. Click Save. The principal is granted the roles on the resource.

Use a custom service account

By granting the Storage Object Creator and Storage Legacy Bucket Reader roles to the Cloud Pub/Sub service account, any user who has permission to create a subscription in your project can write to the Cloud Storage bucket. If you want to provide more granular permissions, configure a user-managed service account instead.

The following permissions are required to configure a user-managed service account to write to Cloud Storage:

  • The user-managed service account must have the Storage Object Creator and Storage Legacy Bucket Reader roles.

  • The Cloud Pub/Sub service account must have the iam.serviceAccounts.getAccessToken permission on the user-managed service account.

  • The user creating the subscription must have the iam.serviceAccounts.actAs permission on the user-managed service account.

When you create the subscription, specify the user-managed service account as the subscription service account.

Cloud Storage subscription properties

Cloud Storage subscriptions support all of the common subscription properties. The following sections describe properties that are specific to Cloud Storage subscriptions.

Bucket name

A Cloud Storage bucket must already exist before you create a Cloud Storage subscription.

The messages are sent as batches and stored in the Cloud Storage bucket. A single batch or file is stored as an object in the bucket.

The Cloud Storage bucket must have Requester Pays disabled.

To create a Cloud Storage bucket, see Create buckets.

Filename prefix, suffix, and datetime

The output Cloud Storage files generated by the Cloud Storage subscription are stored as objects in the Cloud Storage bucket. The name of the object stored in the Cloud Storage bucket is of the following format: <file-prefix><UTC-date-time>_<uuid><file-suffix>.

The following list includes details of the file format and the fields that you can customize:

  • <file-prefix> is the custom filename prefix. This is an optional field.

  • <UTC-date-time> is a customizable auto-generated string based on the time the object is created.

  • <uuid> is an auto-generated random string for the object.

  • <file-suffix> is the custom filename suffix. This is an optional field. The filename suffix cannot end in "/".

  • You can change the filename prefix and suffix:

    • For example, if the value of the filename prefix is prod_ and the value of the filename suffix is _archive, a sample object name is prod_2023-09-25T04:10:00+00:00_uN1QuE_archive.

    • If you don't specify the filename prefix and suffix, the object name stored in the Cloud Storage bucket is of the format: <UTC-date-time>_<uuid>.

    • Cloud Storage object naming requirements also apply to the filename prefix and suffix. For more information, see About Cloud Storage objects.

  • You can change how the date and time are displayed in the filename:

    • Required datetime matchers that you can use only once: year (YYYY or YY), month (MM), day (DD), hour (hh), minute (mm), second (ss). For example, YY-YYYY or MMM is invalid.

    • Optional matchers that you can use only once: datetime separator (T) and timezone offset (Z or +00:00).

    • Optional elements that you can use multiple times: hyphen (-), underscore (_), colon (:), and forward slash (/).

    • For example, if the value of the filename datetime format is YYYY-MM-DD/hh_mm_ssZ, a sample object name is prod_2023-09-25/04_10_00Z_uNiQuE_archive.

    • If the filename datetime format ends in a character which is not a matcher, that character will replace the separator between <UTC-date-time> and <uuid>. For example, if the value of the filename datetime format is YYYY-MM-DDThh_mm_ss-, a sample object name is prod_2023-09-25T04_10_00-uNiQuE_archive.

File batching

Cloud Storage subscriptions let you decide when you want to create a new output file that is stored as an object in the Cloud Storage bucket. Pub/Sub writes an output file when one of the specified batching conditions are met. The following are the Cloud Storage batching conditions:

  • Storage batch max duration. This is a required setting. Pub/Sub writes a new output file if the specified value for max duration is exceeded. The duration is measured from when Pub/Sub begins writing to a new file to the time the file is finalized. For example, if you set the max duration to 5 minutes, Pub/Sub finalizes the file at most 5 minutes after Pub/Sub began writing to the file. A new file can be created before the max duration has passed. If you don't specify the value, a default value of 5 minutes is applied. The following are the applicable values for max duration:

    • Minimum value = 1 minute
    • Default value = 5 minutes
    • Maximum value = 10 minutes
  • Storage batch max bytes. This is an optional setting. The Cloud Storage subscription writes a new output file if the specified value of max bytes is exceeded. The following are the applicable values for max bytes:

    • Minimum value = 1 KB
    • Maximum value = 10 GiB
  • Storage batch max messages. This is an optional setting. The Cloud Storage subscription writes a new output file if the specified number of max messages is exceeded. The following are the applicable values for max messages:

    • Minimum value = 1000

For example, you can configure max duration as 6 minutes and max bytes as 2 GB. If at the 4th minute, the output file reaches a file size of 2 GB, Pub/Sub finalizes the previous file and starts writing to a new file.

A Cloud Storage subscription might write to multiple files in a Cloud Storage bucket simultaneously. If you have configured your subscription to create a new file every 6th minute, you might observe multiple Cloud Storage files being created every 6 minutes.

In some situations, Pub/Sub might start writing to a new file earlier than the time configured by the file batching conditions. A file might also exceed the Max bytes value if the subscription receives messages larger than the Max bytes value.

File format

When you create a Cloud Storage subscription, you can specify the format of the output files that are to be stored in a Cloud Storage bucket as Text or Avro.

  • Text: The messages are stored as plain text. A newline character separates a message from the previous message in the file. Only message payloads are stored, not attributes or other metadata.

  • Avro: The messages are stored in Apache Avro binary format. When you select Avro, you can enable the following additional properties:

    • Write metadata: This option lets you store the message metadata along with the message. Metadata such as subscription_name, message_id, publish_time, and attributes fields are written to top-level fields in the output Avro object while all other message properties other than data (for example, an ordering_key, if present) are added as entries in the attributes map.

      If write metadata is disabled, only the message payload is written to the output Avro object. Here is the Avro schema for the output messages with write metadata disabled:

      {
        "type": "record",
        "namespace": "com.google.pubsub",
        "name": "PubsubMessage",
        "fields": [
          { "name": "data", "type": "bytes" }
        ]
      }
      

      Here is the Avro schema for the output messages with write metadata enabled:

      {
        "type": "record",
        "namespace": "com.google.pubsub",
        "name": "PubsubMessageWithMetadata",
        "fields": [
          { "name": "subscription_name", "type": "string" },
          { "name": "message_id", "type": "string"  },
          { "name": "publish_time", "type": {
              "type": "long",
              "logicalType": "timestamp-micros"
            }
          },
          { "name": "attributes", "type": { "type": "map", "values": "string" } },
          { "name": "data", "type": "bytes" }
        ]
      }
      
    • Use topic schema: This option lets Pub/Sub use the schema of the Pub/Sub topic to which the subscription is attached when writing Avro files.

      When you use this option, remember to check the following additional requirements:

      • The topic schema must be in Apache Avro format.

      • If both use topic schema and write metadata are enabled, the topic schema must have a Record object at its root. Pub/Sub will expand the Record's list of fields to include the metadata fields. As a result, the Record cannot contain any fields with the same name as the metadata fields (subscription_name, message_id, publish_time, or attributes).

Service account

You have the following options to write messages to a Cloud Storage bucket:

  • Configure a custom service account so that only users who have the iam.serviceAccounts.actAs permission on the service account can create a subscription that writes to the bucket. An example role that includes the iam.serviceAccounts.actAs permission is the Service Account User (roles/iam.serviceAccountUser) role.

  • Use the default Pub/Sub service agent that lets any user with the ability to create subscriptions in the project to create a subscription that writes to the bucket. The Pub/Sub service agent is the default setting when you don't specify a custom service account.

Create a Cloud Storage subscription

Console

  1. In the Google Cloud console, go to the Subscriptions page.

    Go to Subscriptions

  2. Click Create subscription.

  3. For the Subscription ID field, enter a name.

    For information about how to name a subscription, see Guidelines to name a topic or a subscription.

  4. Choose or create a topic from the drop-down menu.

    The subscription receives messages from the topic.

    For information about how to create a topic, see Create and manage topics.

  5. Select Delivery type as Write to Cloud Storage.

  6. For the Cloud Storage bucket, click Browse.

    • You can select an existing bucket from any appropriate project.

    • You can also click the create icon and follow the instructions on the screen to create a new bucket.

      After you create the bucket, select the bucket for the Cloud Storage subscription.

      For more information about how to create a bucket, see Create buckets.

    When you specify the bucket, Pub/Sub checks for the appropriate permissions on the bucket for the Pub/Sub service agent. If there are permissions issues, you see a message similar to the following: Unable to verify if the Pub/Sub service agent has write permissions on this bucket. You may be lacking permissions to view or set permissions.

  7. If you get permission issues, click Set Permission and follow the on-screen instructions.

    Alternatively, follow the instructions in Assign Cloud Storage roles to the Pub/Sub service agent.

  8. For File format, select Text or Avro.

    If you select Avro, you can also optionally specify if you want to store the message metadata in the output.

    For more information about the two options including the message metadata option for the Avro format, see File format.

  9. Optional: You can specify the File name prefix, suffix, and datetime for all your files that are to be written to the Cloud Storage bucket. A file is stored as an object in the bucket.

    For more information about how to set the file prefix, suffix, and datetime, see Filename prefix, suffix, and datetime.

  10. For File batching, specify a maximum time to elapse before creating a new file.

    You can also optionally set the maximum file size or maximum number of messages for the files.

    For more information about both file batching options, see File batching.

  11. We strongly recommend that you enable Dead lettering to handle message failures.

    For more information, see Dead letter topic.

  12. You can keep the other settings as their defaults and click Create.

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. To create a Cloud Storage subscription, run the gcloud pubsub subscriptions create command.
    gcloud pubsub subscriptions create SUBSCRIPTION_ID \
        --topic=TOPIC_ID \
        --cloud-storage-bucket=BUCKET_NAME \
        --cloud-storage-file-prefix=CLOUD_STORAGE_FILE_PREFIX \
        --cloud-storage-file-suffix=CLOUD_STORAGE_FILE_SUFFIX \
        --cloud-storage-file-datetime-format=CLOUD_STORAGE_FILE_DATETIME_FORMAT