Access control with Identity and Access Management

This document describes the access control options available to you in Pub/Sub.

Overview

Pub/Sub uses Identity and Access Management (IAM) for access control.

IAM allows you to grant specific rolesto users, groups, and service accounts, giving them the necessary permissionsto perform their tasks. You can grant these IAM roles using the Google Cloud console or the IAM API.

In Pub/Sub, access control can be configured at the project level and at the individual resource level. Here are some examples for using Pub/Sub access control:

  • Grant access on a per-resource basis, rather than for the whole Cloud project.

  • Grant access with limited capabilities, such as to only publish messages to a topic, or to only consume messages from a subscription, but not to delete the topic or subscription.

  • Grant access to all Pub/Sub resources within a project to a group of developers.

If you have view-only access to a single resource such as a topic or a subscription, you cannot view the resource using the Google Cloud console. Instead, you can use Google Cloud CLI to view the resource.

For a detailed description of IAM and its features, see the IAM documentation . In particular, see Granting, changing, and revoking access to resources .

Types of roles in Pub/Sub

Similar to other Google Cloud products, Pub/Sub supports three types of roles:

  • Basic roles: Basic roles are highly permissive roles that existed prior to the introduction of IAM. For more information about basic roles, see Basic roles .

  • Predefined roles: Predefined roles give granular access to specific Google Cloud resources. For more information about predefined roles, see Predefined roles . The Pub/Sub predefined roles are included in a later part of this section.

  • Custom roles: Custom roles help you enforce the principle of least privilege. For more information about custom roles, see Custom roles .

Required Pub/Sub permissions

The following sections lists Pub/Sub permissions required for accessing different Pub/Sub resources.

Required permissions for topics

The following table outlines the required permissions for each Pub/Sub API method related to topics. It shows which IAM permission is needed to call each method, along with a description of what the method does.

Method Description Required permission
Creates the given topic with the given name. pubsub.topics.create on the containing Cloud project
Deletes the topic with the given name. pubsub.topics.delete on the requested topic
Gets the configuration of a topic. pubsub.topics.get on the requested topic
Gets the IAM access control policy for a topic. pubsub.topics.getIamPolicy on the requested topic
Lists all topics. pubsub.topics.list on the requested Cloud project
Updates an existing topic. pubsub.topics.update on the requested topic
Adds one or more messages to the topic. pubsub.topics.publish on the requested topic
Sets the IAM access control policy for a topic. pubsub.topics.setIamPolicy on the requested topic
Returns permissions that a caller has on the specified resource. None

Required permissions for subscriptions

The following table outlines the required permissions for each Pub/Sub API method related to subscriptions. It shows which IAM permission is needed to call each method, along with a description of what the method does.

Method Description Required permission
Acknowledges the messages associated with the ack_ids in the AcknowledgeRequest. pubsub.subscriptions.consume on the requested subscription
Creates a subscription to a given topic. pubsub.subscriptions.create on the containing Cloud project and pubsub.topics.attachSubscription on the requested topic. For creating a Subscription S in Project A that is attached to a Topic T in Project B, the appropriate permissions must be granted on both Project A and on Topic T. In this case, user identity info can be captured in Project B's audit logs.
Deletes an existing subscription. pubsub.subscriptions.delete on the requested subscription
Detaches a subscription from this topic. pubsub.subscriptions.detach on the subscription
Gets the configuration details of a subscription. pubsub.subscriptions.get on the requested subscription
Gets the IAM access control policy for a subscription. pubsub.subscriptions.getIamPolicy on the requested subscription
Lists matching subscriptions. pubsub.subscriptions.list on the requested Cloud project
Modifies the ack deadline for a specific message. pubsub.subscriptions.consume on the requested subscription
Modifies the pushConfig for a specified subscription. pubsub.subscriptions.update on the requested subscription
Updates an existing subscription. pubsub.subscriptions.update on the requested subscription
Pulls messages from the server. pubsub.subscriptions.consume on the requested subscription
Seeks an existing subscription to a point in time or a snapshot. pubsub.subscriptions.consume on the requested subscription and pubsub.snapshots.seek on the requested snapshot, if any.
Sets the IAM access control policy for a subscription. pubsub.subscriptions.setIamPolicy on the requested subscription
Returns permissions that a caller has on the specified resource. None

Required permissions for schemas

The following table outlines the required permissions for each Pub/Sub API method related to schemas. It shows which IAM permission is needed to call each method, along with a description of what the method does.

Method Description Required permission
Commits a new schema revision. pubsub.schemas.commit on the requested schema
Creates a schema. pubsub.schemas.create on the containing Cloud project
Deletes a schema. pubsub.schemas.delete on the requested schema
Deletes a specific schema revision. pubsub.schemas.delete on the requested schema
Gets a schema. pubsub.schemas.get on the requested schema
Gets the IAM access control policy for a schema. pubsub.schemas.getIamPolicy on the requested schema
Lists schemas in a project. pubsub.schemas.list on the requested Cloud project
Lists all schema revisions for the named schema. pubsub.schemas.listRevisions on the requested schema
Creates a new schema revision from a previous revision. pubsub.schemas.rollback on the requested schema
Validates a schema definition. pubsub.schemas.validate on the containing Cloud project
Validates a message against a schema. pubsub.schemas.validate on the containing Cloud project

Required permissions for snapshots

The following table outlines the required permissions for each Pub/Sub API method related to snapshots. It shows which IAM permission is needed to call each method, along with a description of what the method does.

REST method Description Required permission
Creates a snapshot from the requested subscription. pubsub.snapshots.create on the containing Cloud project and pubsub.subscriptions.consume permission on the source subscription.
Removes an existing snapshot. pubsub.snapshots.delete on the requested snapshot
Gets the IAM access control policy for a snapshot. pubsub.snapshots.getIamPolicy on the requested snapshot
Lists the existing snapshots. pubsub.snapshots.list on the requested Cloud project
Updates an existing snapshot. pubsub.snapshots.update on the requested snapshot
Sets the IAM access control policy for a snapshot. pubsub.snapshots.setIamPolicy on the requested snapshot
Returns permissions that a caller has on the specified resource. None

Available Pub/Sub roles

The following table lists all Pub/Sub roles and the permissions associated with each role:

Role
Permissions

( roles/ pubsub.admin )

Provides full access to topics and subscriptions.

Lowest-level resources where you can grant this role:

  • Schema
  • Snapshot
  • Subscription
  • Topic

pubsub.*

  • pubsub. messageTransforms. validate
  • pubsub.schemas.attach
  • pubsub.schemas.commit
  • pubsub.schemas.create
  • pubsub.schemas.delete
  • pubsub.schemas.get
  • pubsub.schemas.getIamPolicy
  • pubsub.schemas.list
  • pubsub.schemas.listRevisions
  • pubsub.schemas.rollback
  • pubsub.schemas.setIamPolicy
  • pubsub.schemas.validate
  • pubsub.snapshots.create
  • pubsub.snapshots.delete
  • pubsub.snapshots.get
  • pubsub.snapshots.getIamPolicy
  • pubsub.snapshots.list
  • pubsub.snapshots.seek
  • pubsub.snapshots.setIamPolicy
  • pubsub.snapshots.update
  • pubsub.subscriptions.consume
  • pubsub.subscriptions.create
  • pubsub.subscriptions.delete
  • pubsub.subscriptions.get
  • pubsub. subscriptions. getIamPolicy
  • pubsub.subscriptions.list
  • pubsub. subscriptions. setIamPolicy
  • pubsub.subscriptions.update
  • pubsub. topics. attachSubscription
  • pubsub.topics.create
  • pubsub.topics.delete
  • pubsub. topics. detachSubscription
  • pubsub.topics.get
  • pubsub.topics.getIamPolicy
  • pubsub.topics.list
  • pubsub.topics.publish
  • pubsub.topics.setIamPolicy
  • pubsub.topics.update
  • pubsub.topics.updateTag

resourcemanager.projects.get

serviceusage.quotas.get

serviceusage.services.get

serviceusage.services.list

( roles/ pubsub.editor )

Provides access to modify topics and subscriptions, and access to publish and consume messages.

Lowest-level resources where you can grant this role:

  • Schema
  • Snapshot
  • Subscription
  • Topic

pubsub. messageTransforms. validate

pubsub.schemas.attach

pubsub.schemas.commit

pubsub.schemas.create

pubsub.schemas.delete

pubsub.schemas.get

pubsub.schemas.list

pubsub.schemas.listRevisions

pubsub.schemas.rollback

pubsub.schemas.validate

pubsub.snapshots.create

pubsub.snapshots.delete

pubsub.snapshots.get

pubsub.snapshots.list

pubsub.snapshots.seek

pubsub.snapshots.update

pubsub.subscriptions.consume

pubsub.subscriptions.create

pubsub.subscriptions.delete

pubsub.subscriptions.get

pubsub.subscriptions.list

pubsub.subscriptions.update

pubsub. topics. attachSubscription

pubsub.topics.create

pubsub.topics.delete

pubsub. topics. detachSubscription

pubsub.topics.get

pubsub.topics.list

pubsub.topics.publish

pubsub.topics.update

pubsub.topics.updateTag

resourcemanager.projects.get

serviceusage.quotas.get

serviceusage.services.get

serviceusage.services.list

( roles/ pubsub.publisher )

Provides access to publish messages to a topic.

Lowest-level resources where you can grant this role:

  • Topic

pubsub.topics.publish

( roles/ pubsub.serviceAgent )

Grants Cloud Pub/Sub Service Account access to manage resources.

iam.serviceAccounts.get

iam. serviceAccounts. getAccessToken

iam. serviceAccounts. getOpenIdToken

iam. serviceAccounts. implicitDelegation

iam.serviceAccounts.list

iam.serviceAccounts.signBlob

iam.serviceAccounts.signJwt

resourcemanager.projects.get

resourcemanager.projects.list

serviceusage.services.use

( roles/ pubsub.subscriber )

Provides access to consume messages from a subscription and to attach subscriptions to a topic.

Lowest-level resources where you can grant this role:

  • Snapshot
  • Subscription
  • Topic

pubsub.snapshots.seek

pubsub.subscriptions.consume

pubsub. topics. attachSubscription

( roles/ pubsub.viewer )

Provides access to view topics and subscriptions.

Lowest-level resources where you can grant this role:

  • Schema
  • Snapshot
  • Subscription
  • Topic

pubsub. messageTransforms. validate

pubsub.schemas.get

pubsub.schemas.list

pubsub.schemas.listRevisions

pubsub.schemas.validate

pubsub.snapshots.get

pubsub.snapshots.list

pubsub.subscriptions.get

pubsub.subscriptions.list

pubsub.topics.get

pubsub.topics.list

resourcemanager.projects.get

serviceusage.quotas.get

serviceusage.services.get

serviceusage.services.list

Controlling access through the Google Cloud console

You can use the Google Cloud console to manage access control for your topics and projects.

To set access controls at the project level, follow these steps:

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

    Go to IAM

  2. Select your project.

  3. Click Add.

  4. Type in one or more principal names.

  5. In the Select a rolelist, select the role you want to grant.

  6. Click Save.

  7. Verify that the principal is listed with the role that you granted.

To set access controls for topics and subscriptions, follow these steps:

  1. In the Google Cloud console, go to the Pub/Sub Topicslist.

    Go to Topics

  2. If needed, select your Pub/Sub-enabled project.

  3. Perform one of the following steps:

    • To set roles for one or more topics, select the topics.

    • To set roles for a subscription attached to a topic, click the topic ID. In the Topic detailspage, click the subscription ID. The Subscription detailspage appears.

  4. If the info panel is hidden, click Show info panel.

  5. In the Permissionstab, click Add principal.

  6. Type in one or more principal names.

  7. In the Select a rolelist, select the role you want to grant.

  8. Click Save.

Controlling access through the IAM API

The Pub/Sub IAM API lets you set and get policies on individual topics and subscriptions in a project, and test a user's permissions for a given resource. As with the regular Pub/Sub methods, you can invoke the IAM API methods through the client libraries, or the API Explorer, or directly over HTTP.

Note that you cannot use the Pub/Sub IAM API to manage policies at the Google Cloud project level.

The following sections give examples for how to set and get a policy, and how to test what permissions a caller has for a given resource.

Get a policy

The getIamPolicy() method allows you to get an existing policy . This method returns a JSON object containing the policy associated with the resource.

Here is some sample code to get a policy for a subscription :

C#

Before trying this sample, follow the C# setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub C# API reference documentation .

  using 
  
  Google.Cloud.Iam.V1 
 
 ; 
 using 
  
  Google.Cloud.PubSub.V1 
 
 ; 
 public 
  
 class 
  
 GetSubscriptionIamPolicySample 
 { 
  
 public 
  
 Policy 
  
 GetSubscriptionIamPolicy 
 ( 
 string 
  
 projectId 
 , 
  
 string 
  
 subscriptionId 
 ) 
  
 { 
  
  PublisherServiceApiClient 
 
  
 publisher 
  
 = 
  
  PublisherServiceApiClient 
 
 . 
  Create 
 
 (); 
  
  SubscriptionName 
 
  
 subscriptionName 
  
 = 
  
  SubscriptionName 
 
 . 
  FromProjectSubscription 
 
 ( 
 projectId 
 , 
  
 subscriptionId 
 ); 
  
  Policy 
 
  
 policy 
  
 = 
  
 publisher 
 . 
  IAMPolicyClient 
 
 . 
 GetIamPolicy 
 ( 
 new 
  
  GetIamPolicyRequest 
 
  
 { 
  
 ResourceAsResourceName 
  
 = 
  
 subscriptionName 
  
 }); 
  
 return 
  
 policy 
 ; 
  
 } 
 } 
 

gcloud

Get the subscription policy:

gcloud  
pubsub  
subscriptions  
get-iam-policy  
\  
projects/ ${ 
 PROJECT 
 } 
/subscriptions/ ${ 
 SUBSCRIPTION 
 } 
  
\  
--format  
json

Output:

  
 { 
  
 "etag" 
 : 
  
 "BwUjMhCsNvY=" 
 , 
  
 "bindings" 
 : 
  
 [ 
  
 { 
  
 "role" 
 : 
  
 "roles/pubsub.admin" 
 , 
  
 "members" 
 : 
  
 [ 
  
 "user:user-1@gmail.com" 
  
 ] 
  
 }, 
  
 { 
  
 "role" 
 : 
  
 "roles/pubsub.editor" 
 , 
  
 "members" 
 : 
  
 [ 
  
 "serviceAccount:service-account-2@appspot.gserviceaccount.com" 
 , 
  
 "user:user-3@gmail.com" 
  
 ] 
  
 } 
  
 ] 
  
 } 

Go

The following sample uses the major version of the Go Pub/Sub client library (v2). If you are still using the v1 library, see the migration guide to v2 . To see a list of v1 code samples, see the deprecated code samples .

Before trying this sample, follow the Go setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Go API reference documentation .

  import 
  
 ( 
  
 "context" 
  
 "fmt" 
  
 "io" 
  
 "cloud.google.com/go/iam/apiv1/iampb" 
  
 "cloud.google.com/go/pubsub/v2" 
 ) 
 func 
  
 getIAMPolicy 
 ( 
 w 
  
 io 
 . 
 Writer 
 , 
  
 projectID 
 , 
  
 subscription 
  
 string 
 ) 
  
 error 
  
 { 
  
 // projectID := "my-project-id" 
  
 // subscription := "projects/my-project/subscriptions/my-sub" 
  
 ctx 
  
 := 
  
 context 
 . 
 Background 
 () 
  
 client 
 , 
  
 err 
  
 := 
  
 pubsub 
 . 
 NewClient 
 ( 
 ctx 
 , 
  
 projectID 
 ) 
  
 if 
  
 err 
  
 != 
  
 nil 
  
 { 
  
 return 
  
 fmt 
 . 
 Errorf 
 ( 
 "pubsub.NewClient: %w" 
 , 
  
 err 
 ) 
  
 } 
  
 defer 
  
 client 
 . 
 Close 
 () 
  
 req 
  
 := 
  
& iampb 
 . 
  GetIamPolicyRequest 
 
 { 
  
 Resource 
 : 
  
 subscription 
 , 
  
 } 
  
 policy 
 , 
  
 err 
  
 := 
  
 client 
 . 
 SubscriptionAdminClient 
 . 
  GetIamPolicy 
 
 ( 
 ctx 
 , 
  
 req 
 ) 
  
 if 
  
 err 
  
 != 
  
 nil 
  
 { 
  
 return 
  
 fmt 
 . 
 Errorf 
 ( 
 "Policy: %w" 
 , 
  
 err 
 ) 
  
 } 
  
 for 
  
 _ 
 , 
  
 b 
  
 := 
  
 range 
  
 policy 
 . 
 Bindings 
  
 { 
  
 for 
  
 _ 
 , 
  
 m 
  
 := 
  
 range 
  
 b 
 . 
 Members 
  
 { 
  
 fmt 
 . 
 Fprintf 
 ( 
 w 
 , 
  
 "role: %s, member: %s\n" 
 , 
  
 b 
 . 
 Role 
 , 
  
 m 
 ) 
  
 } 
  
 } 
  
 return 
  
 nil 
 } 
 

Java

Before trying this sample, follow the Java setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Java API reference documentation .

  import 
  
 com.google.cloud.pubsub.v1. SubscriptionAdminClient 
 
 ; 
 import 
  
 com.google.iam.v1. GetIamPolicyRequest 
 
 ; 
 import 
  
 com.google.iam.v1. Policy 
 
 ; 
 import 
  
 com.google.pubsub.v1. ProjectSubscriptionName 
 
 ; 
 import 
  
 java.io.IOException 
 ; 
 public 
  
 class 
 GetSubscriptionPolicyExample 
  
 { 
  
 public 
  
 static 
  
 void 
  
 main 
 ( 
 String 
 ... 
  
 args 
 ) 
  
 throws 
  
 Exception 
  
 { 
  
 // TODO(developer): Replace these variables before running the sample. 
  
 String 
  
 projectId 
  
 = 
  
 "your-project-id" 
 ; 
  
 String 
  
 subscriptionId 
  
 = 
  
 "your-subscription-id" 
 ; 
  
 getSubscriptionPolicyExample 
 ( 
 projectId 
 , 
  
 subscriptionId 
 ); 
  
 } 
  
 public 
  
 static 
  
 void 
  
 getSubscriptionPolicyExample 
 ( 
 String 
  
 projectId 
 , 
  
 String 
  
 subscriptionId 
 ) 
  
 throws 
  
 IOException 
  
 { 
  
 try 
  
 ( 
  SubscriptionAdminClient 
 
  
 subscriptionAdminClient 
  
 = 
  
  SubscriptionAdminClient 
 
 . 
 create 
 ()) 
  
 { 
  
  ProjectSubscriptionName 
 
  
 subscriptionName 
  
 = 
  
  ProjectSubscriptionName 
 
 . 
 of 
 ( 
 projectId 
 , 
  
 subscriptionId 
 ); 
  
  GetIamPolicyRequest 
 
  
 getIamPolicyRequest 
  
 = 
  
  GetIamPolicyRequest 
 
 . 
 newBuilder 
 (). 
 setResource 
 ( 
 subscriptionName 
 . 
  toString 
 
 ()). 
 build 
 (); 
  
  Policy 
 
  
 policy 
  
 = 
  
 subscriptionAdminClient 
 . 
 getIamPolicy 
 ( 
 getIamPolicyRequest 
 ); 
  
 System 
 . 
 out 
 . 
 println 
 ( 
 "Subscription policy: " 
  
 + 
  
 policy 
 ); 
  
 } 
  
 } 
 } 
 

Node.js

Before trying this sample, follow the Node.js setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Node.js API reference documentation .

  /** 
 * TODO(developer): Uncomment this variable before running the sample. 
 */ 
 // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; 
 // Imports the Google Cloud client library 
 const 
  
 { 
 PubSub 
 } 
  
 = 
  
 require 
 ( 
 ' @google-cloud/pubsub 
' 
 ); 
 // Creates a client; cache this for further use 
 const 
  
 pubSubClient 
  
 = 
  
 new 
  
  PubSub 
 
 (); 
 async 
  
 function 
  
 getSubscriptionPolicy 
 ( 
 subscriptionNameOrId 
 ) 
  
 { 
  
 // Retrieves the IAM policy for the subscription 
  
 const 
  
 [ 
 policy 
 ] 
  
 = 
  
 await 
  
 pubSubClient 
  
 . 
 subscription 
 ( 
 subscriptionNameOrId 
 ) 
  
 . 
 iam 
 . 
  getPolicy 
 
 (); 
  
 console 
 . 
 log 
 ( 
 `Policy for subscription: 
 ${ 
  JSON 
 
 . 
 stringify 
 ( 
 policy 
 . 
 bindings 
 ) 
 } 
 .` 
 ); 
 } 
 

Node.js

Before trying this sample, follow the Node.js setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Node.js API reference documentation .

  /** 
 * TODO(developer): Uncomment this variable before running the sample. 
 */ 
 // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; 
 // Imports the Google Cloud client library 
 import 
  
 { 
 PubSub 
 , 
  
 Policy 
 } 
  
 from 
  
 '@google-cloud/pubsub' 
 ; 
 // Creates a client; cache this for further use 
 const 
  
 pubSubClient 
  
 = 
  
 new 
  
 PubSub 
 (); 
 async 
  
 function 
  
 getSubscriptionPolicy 
 ( 
 subscriptionNameOrId 
 : 
  
 string 
 ) 
  
 { 
  
 // Retrieves the IAM policy for the subscription 
  
 const 
  
 [ 
 policy 
 ] 
 : 
  
 [ 
 Policy 
 ] 
  
 = 
  
 await 
  
 pubSubClient 
  
 . 
 subscription 
 ( 
 subscriptionNameOrId 
 ) 
  
 . 
 iam 
 . 
 getPolicy 
 (); 
  
 console 
 . 
 log 
 ( 
 `Policy for subscription: 
 ${ 
 JSON 
 . 
 stringify 
 ( 
 policy 
 . 
 bindings 
 ) 
 } 
 .` 
 ); 
 } 
 

PHP

Before trying this sample, follow the PHP setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub PHP API reference documentation .

  use Google\Cloud\PubSub\PubSubClient; 
 /** 
 * Prints the policy for a PubSub subscription. 
 * 
 * @param string $projectId  The Google project ID. 
 * @param string $subscriptionName  The Pub/Sub subscription name. 
 */ 
 function get_subscription_policy($projectId, $subscriptionName) 
 { 
 $pubsub = new PubSubClient([ 
 'projectId' => $projectId, 
 ]); 
 $subscription = $pubsub->subscription($subscriptionName); 
 $policy = $subscription->iam()->policy(); 
 print_r($policy); 
 } 
 

Python

Before trying this sample, follow the Python setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Python API reference documentation .

  from 
  
 google.cloud 
  
 import 
 pubsub_v1 
 # TODO(developer): Choose an existing subscription. 
 # project_id = "your-project-id" 
 # subscription_id = "your-subscription-id" 
 client 
 = 
 pubsub_v1 
 . 
  SubscriberClient 
 
 () 
 subscription_path 
 = 
 client 
 . 
 subscription_path 
 ( 
 project_id 
 , 
 subscription_id 
 ) 
 policy 
 = 
 client 
 . 
 get_iam_policy 
 ( 
 request 
 = 
 { 
 "resource" 
 : 
 subscription_path 
 }) 
 print 
 ( 
 "Policy for subscription 
 {} 
 :" 
 . 
 format 
 ( 
 subscription_path 
 )) 
 for 
 binding 
 in 
 policy 
 . 
 bindings 
 : 
 print 
 ( 
 "Role: 
 {} 
 , Members: 
 {} 
 " 
 . 
 format 
 ( 
 binding 
 . 
 role 
 , 
 binding 
 . 
 members 
 )) 
 client 
 . 
  close 
 
 () 
 

Ruby

The following sample uses Ruby Pub/Sub client library v3. If you are still using the v2 library, see the migration guide to v3 . To see a list of Ruby v2 code samples, see the deprecated code samples .

Before trying this sample, follow the Ruby setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Ruby API reference documentation .

  # subscription_id = "your-subscription-id" 
 pubsub 
  
 = 
  
 Google 
 :: 
 Cloud 
 :: 
  PubSub 
 
 . 
  new 
 
 policy 
  
 = 
  
 pubsub 
 . 
  iam 
 
 . 
 get_iam_policy 
  
 \ 
  
 resource 
 : 
  
 pubsub 
 . 
 subscription_path 
 ( 
 subscription_id 
 ) 
 puts 
  
 "Subscription policy:" 
 puts 
  
 policy 
 . 
 bindings 
 . 
 first 
 . 
 role 
 
Here is some sample code to get a policy for a topic :

C#

Before trying this sample, follow the C# setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub C# API reference documentation .

  using 
  
  Google.Cloud.Iam.V1 
 
 ; 
 using 
  
  Google.Cloud.PubSub.V1 
 
 ; 
 public 
  
 class 
  
 GetTopicIamPolicySample 
 { 
  
 public 
  
 Policy 
  
 GetTopicIamPolicy 
 ( 
 string 
  
 projectId 
 , 
  
 string 
  
 topicId 
 ) 
  
 { 
  
  PublisherServiceApiClient 
 
  
 publisher 
  
 = 
  
  PublisherServiceApiClient 
 
 . 
  Create 
 
 (); 
  
  TopicName 
 
  
 topicName 
  
 = 
  
  TopicName 
 
 . 
  FromProjectTopic 
 
 ( 
 projectId 
 , 
  
 topicId 
 ); 
  
  Policy 
 
  
 policy 
  
 = 
  
 publisher 
 . 
  IAMPolicyClient 
 
 . 
 GetIamPolicy 
 ( 
 new 
  
  GetIamPolicyRequest 
 
  
 { 
  
 ResourceAsResourceName 
  
 = 
  
 topicName 
  
 }); 
  
 return 
  
 policy 
 ; 
  
 } 
 } 
 

gcloud

Get the topic policy

gcloud  
pubsub  
topics  
get-iam-policy  
\  
projects/ ${ 
 PROJECT 
 } 
/topics/ ${ 
 TOPIC 
 } 
  
\  
--format  
json

Output:

 { 
  
 "etag" 
 : 
  
 "BwUjMhCsNvY=" 
 , 
  
 "bindings" 
 : 
  
 [ 
 { 
 "role":" roles/pubsub.viewer", 
 "members": [ 
 "user:user-1@gmail.com" 
  
 ] 
  
 } 
  
 ] 
 } 

Go

The following sample uses the major version of the Go Pub/Sub client library (v2). If you are still using the v1 library, see the migration guide to v2 . To see a list of v1 code samples, see the deprecated code samples .

Before trying this sample, follow the Go setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Go API reference documentation .

  import 
  
 ( 
  
 "context" 
  
 "fmt" 
  
 "io" 
  
 "cloud.google.com/go/iam/apiv1/iampb" 
  
 "cloud.google.com/go/pubsub/v2" 
 ) 
 func 
  
 getIAMPolicy 
 ( 
 w 
  
 io 
 . 
 Writer 
 , 
  
 projectID 
 , 
  
 topicID 
  
 string 
 ) 
  
 error 
  
 { 
  
 // projectID := "my-project-id" 
  
 // topicID := "my-topic" 
  
 ctx 
  
 := 
  
 context 
 . 
 Background 
 () 
  
 client 
 , 
  
 err 
  
 := 
  
 pubsub 
 . 
 NewClient 
 ( 
 ctx 
 , 
  
 projectID 
 ) 
  
 if 
  
 err 
  
 != 
  
 nil 
  
 { 
  
 return 
  
 fmt 
 . 
 Errorf 
 ( 
 "pubsub.NewClient: %w" 
 , 
  
 err 
 ) 
  
 } 
  
 defer 
  
 client 
 . 
 Close 
 () 
  
 req 
  
 := 
  
& iampb 
 . 
  GetIamPolicyRequest 
 
 { 
  
 Resource 
 : 
  
 fmt 
 . 
 Sprintf 
 ( 
 "projects/%s/topics/%s" 
 , 
  
 projectID 
 , 
  
 topicID 
 ), 
  
 } 
  
 policy 
 , 
  
 err 
  
 := 
  
 client 
 . 
 TopicAdminClient 
 . 
  GetIamPolicy 
 
 ( 
 ctx 
 , 
  
 req 
 ) 
  
 if 
  
 err 
  
 != 
  
 nil 
  
 { 
  
 return 
  
 fmt 
 . 
 Errorf 
 ( 
 "Policy: %w" 
 , 
  
 err 
 ) 
  
 } 
  
 for 
  
 _ 
 , 
  
 b 
  
 := 
  
 range 
  
 policy 
 . 
 Bindings 
  
 { 
  
 for 
  
 _ 
 , 
  
 m 
  
 := 
  
 range 
  
 b 
 . 
 Members 
  
 { 
  
 fmt 
 . 
 Fprintf 
 ( 
 w 
 , 
  
 "role: %s, member: %s\n" 
 , 
  
 b 
 . 
 Role 
 , 
  
 m 
 ) 
  
 } 
  
 } 
  
 return 
  
 nil 
 } 
 

Java

Before trying this sample, follow the Java setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Java API reference documentation .

  import 
  
 com.google.cloud.pubsub.v1. TopicAdminClient 
 
 ; 
 import 
  
 com.google.iam.v1. GetIamPolicyRequest 
 
 ; 
 import 
  
 com.google.iam.v1. Policy 
 
 ; 
 import 
  
 com.google.pubsub.v1. TopicName 
 
 ; 
 import 
  
 java.io.IOException 
 ; 
 public 
  
 class 
 GetTopicPolicyExample 
  
 { 
  
 public 
  
 static 
  
 void 
  
 main 
 ( 
 String 
 ... 
  
 args 
 ) 
  
 throws 
  
 Exception 
  
 { 
  
 // TODO(developer): Replace these variables before running the sample. 
  
 String 
  
 projectId 
  
 = 
  
 "your-project-id" 
 ; 
  
 String 
  
 topicId 
  
 = 
  
 "your-topic-id" 
 ; 
  
 getTopicPolicyExample 
 ( 
 projectId 
 , 
  
 topicId 
 ); 
  
 } 
  
 public 
  
 static 
  
 void 
  
 getTopicPolicyExample 
 ( 
 String 
  
 projectId 
 , 
  
 String 
  
 topicId 
 ) 
  
 throws 
  
 IOException 
  
 { 
  
 try 
  
 ( 
  TopicAdminClient 
 
  
 topicAdminClient 
  
 = 
  
  TopicAdminClient 
 
 . 
 create 
 ()) 
  
 { 
  
  TopicName 
 
  
 topicName 
  
 = 
  
  TopicName 
 
 . 
 of 
 ( 
 projectId 
 , 
  
 topicId 
 ); 
  
  GetIamPolicyRequest 
 
  
 getIamPolicyRequest 
  
 = 
  
  GetIamPolicyRequest 
 
 . 
 newBuilder 
 (). 
 setResource 
 ( 
 topicName 
 . 
  toString 
 
 ()). 
 build 
 (); 
  
  Policy 
 
  
 policy 
  
 = 
  
 topicAdminClient 
 . 
 getIamPolicy 
 ( 
 getIamPolicyRequest 
 ); 
  
 System 
 . 
 out 
 . 
 println 
 ( 
 "Topic policy: " 
  
 + 
  
 policy 
 ); 
  
 } 
  
 } 
 } 
 

Node.js

Before trying this sample, follow the Node.js setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Node.js API reference documentation .

  /** 
 * TODO(developer): Uncomment this variable before running the sample. 
 */ 
 // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; 
 // Imports the Google Cloud client library 
 const 
  
 { 
 PubSub 
 } 
  
 = 
  
 require 
 ( 
 ' @google-cloud/pubsub 
' 
 ); 
 // Creates a client; cache this for further use 
 const 
  
 pubSubClient 
  
 = 
  
 new 
  
  PubSub 
 
 (); 
 async 
  
 function 
  
 getTopicPolicy 
 ( 
 topicNameOrId 
 ) 
  
 { 
  
 // Retrieves the IAM policy for the topic 
  
 const 
  
 [ 
 policy 
 ] 
  
 = 
  
 await 
  
 pubSubClient 
 . 
 topic 
 ( 
 topicNameOrId 
 ). 
 iam 
 . 
  getPolicy 
 
 (); 
  
 console 
 . 
 log 
 ( 
 'Policy for topic: %j.' 
 , 
  
 policy 
 . 
 bindings 
 ); 
 } 
 

PHP

Before trying this sample, follow the PHP setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub PHP API reference documentation .

  use Google\Cloud\PubSub\PubSubClient; 
 /** 
 * Prints the policy for a Pub/Sub topic. 
 * 
 * @param string $projectId  The Google project ID. 
 * @param string $topicName  The Pub/Sub topic name. 
 */ 
 function get_topic_policy($projectId, $topicName) 
 { 
 $pubsub = new PubSubClient([ 
 'projectId' => $projectId, 
 ]); 
 $topic = $pubsub->topic($topicName); 
 $policy = $topic->iam()->policy(); 
 print_r($policy); 
 } 
 

Python

Before trying this sample, follow the Python setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Python API reference documentation .

  from 
  
 google.cloud 
  
 import 
 pubsub_v1 
 # TODO(developer): Choose an existing topic. 
 # project_id = "your-project-id" 
 # topic_id = "your-topic-id" 
 client 
 = 
 pubsub_v1 
 . 
  PublisherClient 
 
 () 
 topic_path 
 = 
 client 
 . 
 topic_path 
 ( 
 project_id 
 , 
 topic_id 
 ) 
 policy 
 = 
 client 
 . 
 get_iam_policy 
 ( 
 request 
 = 
 { 
 "resource" 
 : 
 topic_path 
 }) 
 print 
 ( 
 "Policy for topic 
 {} 
 :" 
 . 
 format 
 ( 
 topic_path 
 )) 
 for 
 binding 
 in 
 policy 
 . 
 bindings 
 : 
 print 
 ( 
 "Role: 
 {} 
 , Members: 
 {} 
 " 
 . 
 format 
 ( 
 binding 
 . 
 role 
 , 
 binding 
 . 
 members 
 )) 
 

Ruby

The following sample uses Ruby Pub/Sub client library v3. If you are still using the v2 library, see the migration guide to v3 . To see a list of Ruby v2 code samples, see the deprecated code samples .

Before trying this sample, follow the Ruby setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Ruby API reference documentation .

  # topic_id = "your-topic-id" 
 pubsub 
  
 = 
  
 Google 
 :: 
 Cloud 
 :: 
  PubSub 
 
 . 
  new 
 
 policy 
  
 = 
  
 pubsub 
 . 
  iam 
 
 . 
 get_iam_policy 
  
 resource 
 : 
  
 pubsub 
 . 
 topic_path 
 ( 
 topic_id 
 ) 
 puts 
  
 "Topic policy:" 
 puts 
  
 policy 
 . 
 bindings 
 . 
 first 
 . 
 role 
 

Set a policy

The setIamPolicy() method lets you attach a policy to a resource. The setIamPolicy() method takes a SetIamPolicyRequest , which contains the policy to be set and the resource to which the policy is attached. It returns the resulting policy.

Here is some sample code to set a policy for a subscription :

C#

Before trying this sample, follow the C# setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub C# API reference documentation .

  using 
  
  Google.Cloud.Iam.V1 
 
 ; 
 using 
  
  Google.Cloud.PubSub.V1 
 
 ; 
 public 
  
 class 
  
 SetSubscriptionIamPolicySample 
 { 
  
 public 
  
 Policy 
  
 SetSubscriptionIamPolicy 
 ( 
 string 
  
 projectId 
 , 
  
 string 
  
 subscriptionId 
 , 
  
 string 
  
 role 
 , 
  
 string 
  
 member 
 ) 
  
 { 
  
  PublisherServiceApiClient 
 
  
 publisher 
  
 = 
  
  PublisherServiceApiClient 
 
 . 
  Create 
 
 (); 
  
 string 
  
 roleToBeAddedToPolicy 
  
 = 
  
 $"roles/{role}" 
 ; 
  
  Policy 
 
  
 policy 
  
 = 
  
 new 
  
  Policy 
 
  
 { 
  
 Bindings 
  
 = 
  
 { 
  
 new 
  
  Binding 
 
  
 { 
  
 Role 
  
 = 
  
 roleToBeAddedToPolicy 
 , 
  
 Members 
  
 = 
  
 { 
  
 member 
  
 } 
  
 } 
  
 } 
  
 }; 
  
  SetIamPolicyRequest 
 
  
 request 
  
 = 
  
 new 
  
  SetIamPolicyRequest 
 
  
 { 
  
 ResourceAsResourceName 
  
 = 
  
  SubscriptionName 
 
 . 
  FromProjectSubscription 
 
 ( 
 projectId 
 , 
  
 subscriptionId 
 ), 
  
 Policy 
  
 = 
  
 policy 
  
 }; 
  
  Policy 
 
  
 response 
  
 = 
  
 publisher 
 . 
  IAMPolicyClient 
 
 . 
 SetIamPolicy 
 ( 
 request 
 ); 
  
 return 
  
 response 
 ; 
  
 } 
 } 
 

gcloud

1. Save the policy for the subscription.

gcloud  
pubsub  
subscriptions  
get-iam-policy  
\  
projects/ ${ 
 PROJECT 
 } 
/subscriptions/ ${ 
 SUBSCRIPTION 
 } 
  
\  
--format  
json  
>  
subscription_policy.json

2. Open subscription_policy.json and update bindings by giving appropriate roles to appropriate principals. For more information about working with subscription_policy.json files, see Policy in the IAM documentation.

  
 { 
  
 "etag" 
 : 
  
 "BwUjMhCsNvY=" 
 , 
  
 "bindings" 
 : 
  
 [ 
  
 { 
  
 "role" 
 : 
  
 "roles/pubsub.admin" 
 , 
  
 "members" 
 : 
  
 [ 
  
 "user:user-1@gmail.com" 
  
 ] 
  
 }, 
  
 { 
  
 "role" 
 : 
  
 "roles/pubsub.editor" 
 , 
  
 "members" 
 : 
  
 [ 
  
 "serviceAccount:service-account-2@appspot.gserviceaccount.com" 
  
 ] 
  
 } 
  
 ] 
  
 } 

3. Apply the new subscription policy.

gcloud  
pubsub  
subscriptions  
set-iam-policy  
\  
projects/ ${ 
 PROJECT 
 } 
/subscriptions/ ${ 
 SUBSCRIPTION 
 } 
  
\  
subscription_policy.json

Go

The following sample uses the major version of the Go Pub/Sub client library (v2). If you are still using the v1 library, see the migration guide to v2 . To see a list of v1 code samples, see the deprecated code samples .

Before trying this sample, follow the Go setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Go API reference documentation .

  import 
  
 ( 
  
 "context" 
  
 "fmt" 
  
 "io" 
  
 "cloud.google.com/go/iam/apiv1/iampb" 
  
 "cloud.google.com/go/pubsub/v2" 
 ) 
 func 
  
 addUsersToSubscription 
 ( 
 w 
  
 io 
 . 
 Writer 
 , 
  
 projectID 
 , 
  
 subID 
  
 string 
 ) 
  
 error 
  
 { 
  
 // projectID := "my-project-id" 
  
 // subID := "my-sub" 
  
 ctx 
  
 := 
  
 context 
 . 
 Background 
 () 
  
 client 
 , 
  
 err 
  
 := 
  
 pubsub 
 . 
 NewClient 
 ( 
 ctx 
 , 
  
 projectID 
 ) 
  
 if 
  
 err 
  
 != 
  
 nil 
  
 { 
  
 return 
  
 fmt 
 . 
 Errorf 
 ( 
 "pubsub.NewClient: %w" 
 , 
  
 err 
 ) 
  
 } 
  
 defer 
  
 client 
 . 
 Close 
 () 
  
 subName 
  
 := 
  
 fmt 
 . 
 Sprintf 
 ( 
 "projects/%s/subscriptions/%s" 
 , 
  
 projectID 
 , 
  
 subID 
 ) 
  
 req 
  
 := 
  
& iampb 
 . 
  GetIamPolicyRequest 
 
 { 
  
 Resource 
 : 
  
 subName 
 , 
  
 } 
  
 policy 
 , 
  
 err 
  
 := 
  
 client 
 . 
 SubscriptionAdminClient 
 . 
  GetIamPolicy 
 
 ( 
 ctx 
 , 
  
 req 
 ) 
  
 if 
  
 err 
  
 != 
  
 nil 
  
 { 
  
 return 
  
 fmt 
 . 
 Errorf 
 ( 
 "error calling GetIamPolicy: %w" 
 , 
  
 err 
 ) 
  
 } 
  
 b 
  
 := 
  
& iampb 
 . 
  Binding 
 
 { 
  
 Role 
 : 
  
 "roles/editor" 
 , 
  
 // Other valid prefixes are "serviceAccount:", "user:" 
  
 // See the documentation for more values. 
  
 Members 
 : 
  
 [] 
 string 
 { 
 "group:cloud-logs@google.com" 
 }, 
  
 } 
  
 policy 
 . 
 Bindings 
  
 = 
  
 append 
 ( 
 policy 
 . 
 Bindings 
 , 
  
 b 
 ) 
  
 setRequest 
  
 := 
  
& iampb 
 . 
  SetIamPolicyRequest 
 
 { 
  
 Resource 
 : 
  
 subName 
 , 
  
 Policy 
 : 
  
 policy 
 , 
  
 } 
  
 _ 
 , 
  
 err 
  
 = 
  
 client 
 . 
 SubscriptionAdminClient 
 . 
  SetIamPolicy 
 
 ( 
 ctx 
 , 
  
 setRequest 
 ) 
  
 if 
  
 err 
  
 != 
  
 nil 
  
 { 
  
 return 
  
 fmt 
 . 
 Errorf 
 ( 
 "error calling SetIamPolicy: %w" 
 , 
  
 err 
 ) 
  
 } 
  
 fmt 
 . 
 Fprintln 
 ( 
 w 
 , 
  
 "Added roles to subscription." 
 ) 
  
 return 
  
 nil 
 } 
 

Java

Before trying this sample, follow the Java setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Java API reference documentation .

  import 
  
 com.google.cloud.pubsub.v1. SubscriptionAdminClient 
 
 ; 
 import 
  
 com.google.iam.v1. Binding 
 
 ; 
 import 
  
 com.google.iam.v1. GetIamPolicyRequest 
 
 ; 
 import 
  
 com.google.iam.v1. Policy 
 
 ; 
 import 
  
 com.google.iam.v1. SetIamPolicyRequest 
 
 ; 
 import 
  
 com.google.pubsub.v1. ProjectSubscriptionName 
 
 ; 
 import 
  
 java.io.IOException 
 ; 
 public 
  
 class 
 SetSubscriptionPolicyExample 
  
 { 
  
 public 
  
 static 
  
 void 
  
 main 
 ( 
 String 
 ... 
  
 args 
 ) 
  
 throws 
  
 Exception 
  
 { 
  
 // TODO(developer): Replace these variables before running the sample. 
  
 String 
  
 projectId 
  
 = 
  
 "your-project-id" 
 ; 
  
 String 
  
 subscriptionId 
  
 = 
  
 "your-subscription-id" 
 ; 
  
 setSubscriptionPolicyExample 
 ( 
 projectId 
 , 
  
 subscriptionId 
 ); 
  
 } 
  
 public 
  
 static 
  
 void 
  
 setSubscriptionPolicyExample 
 ( 
 String 
  
 projectId 
 , 
  
 String 
  
 subscriptionId 
 ) 
  
 throws 
  
 IOException 
  
 { 
  
 try 
  
 ( 
  SubscriptionAdminClient 
 
  
 subscriptionAdminClient 
  
 = 
  
  SubscriptionAdminClient 
 
 . 
 create 
 ()) 
  
 { 
  
  ProjectSubscriptionName 
 
  
 subscriptionName 
  
 = 
  
  ProjectSubscriptionName 
 
 . 
 of 
 ( 
 projectId 
 , 
  
 subscriptionId 
 ); 
  
  GetIamPolicyRequest 
 
  
 getIamPolicyRequest 
  
 = 
  
  GetIamPolicyRequest 
 
 . 
 newBuilder 
 (). 
 setResource 
 ( 
 subscriptionName 
 . 
  toString 
 
 ()). 
 build 
 (); 
  
  Policy 
 
  
 oldPolicy 
  
 = 
  
 subscriptionAdminClient 
 . 
 getIamPolicy 
 ( 
 getIamPolicyRequest 
 ); 
  
 // Create new role -> members binding 
  
  Binding 
 
  
 binding 
  
 = 
  
  Binding 
 
 . 
 newBuilder 
 () 
  
 . 
 setRole 
 ( 
 "roles/pubsub.editor" 
 ) 
  
 . 
  addMembers 
 
 ( 
 "domain:google.com" 
 ) 
  
 . 
 build 
 (); 
  
 // Add new binding to updated policy 
  
  Policy 
 
  
 updatedPolicy 
  
 = 
  
  Policy 
 
 . 
 newBuilder 
 ( 
 oldPolicy 
 ). 
  addBindings 
 
 ( 
 binding 
 ). 
 build 
 (); 
  
  SetIamPolicyRequest 
 
  
 setIamPolicyRequest 
  
 = 
  
  SetIamPolicyRequest 
 
 . 
 newBuilder 
 () 
  
 . 
 setResource 
 ( 
 subscriptionName 
 . 
  toString 
 
 ()) 
  
 . 
  setPolicy 
 
 ( 
 updatedPolicy 
 ) 
  
 . 
 build 
 (); 
  
  Policy 
 
  
 newPolicy 
  
 = 
  
 subscriptionAdminClient 
 . 
 setIamPolicy 
 ( 
 setIamPolicyRequest 
 ); 
  
 System 
 . 
 out 
 . 
 println 
 ( 
 "New subscription policy: " 
  
 + 
  
 newPolicy 
 ); 
  
 } 
  
 } 
 } 
 

Node.js

Before trying this sample, follow the Node.js setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Node.js API reference documentation .

  /** 
 * TODO(developer): Uncomment this variable before running the sample. 
 */ 
 // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; 
 // Imports the Google Cloud client library 
 const 
  
 { 
 PubSub 
 } 
  
 = 
  
 require 
 ( 
 ' @google-cloud/pubsub 
' 
 ); 
 // Creates a client; cache this for further use 
 const 
  
 pubSubClient 
  
 = 
  
 new 
  
  PubSub 
 
 (); 
 async 
  
 function 
  
 setSubscriptionPolicy 
 ( 
 subscriptionNameOrId 
 ) 
  
 { 
  
 // The new IAM policy 
  
 const 
  
 newPolicy 
  
 = 
  
 { 
  
 bindings 
 : 
  
 [ 
  
 { 
  
 // Add a group as editors 
  
 role 
 : 
  
 'roles/pubsub.editor' 
 , 
  
 members 
 : 
  
 [ 
 'group:cloud-logs@google.com' 
 ], 
  
 }, 
  
 { 
  
 // Add all users as viewers 
  
 role 
 : 
  
 'roles/pubsub.viewer' 
 , 
  
 members 
 : 
  
 [ 
 'allUsers' 
 ], 
  
 }, 
  
 ], 
  
 }; 
  
 // Updates the IAM policy for the subscription 
  
 const 
  
 [ 
 updatedPolicy 
 ] 
  
 = 
  
 await 
  
 pubSubClient 
  
 . 
 subscription 
 ( 
 subscriptionNameOrId 
 ) 
  
 . 
 iam 
 . 
  setPolicy 
 
 ( 
 newPolicy 
 ); 
  
 console 
 . 
 log 
 ( 
 'Updated policy for subscription: %j' 
 , 
  
 updatedPolicy 
 . 
 bindings 
 ); 
 } 
 

PHP

  use Google\Cloud\PubSub\PubSubClient; 
 /** 
 * Adds a user to the policy for a Pub/Sub subscription. 
 * 
 * @param string $projectId  The Google project ID. 
 * @param string $subscriptionName  The Pub/Sub subscription name. 
 * @param string $userEmail  The user email to add to the policy. 
 */ 
 function set_subscription_policy($projectId, $subscriptionName, $userEmail) 
 { 
 $pubsub = new PubSubClient([ 
 'projectId' => $projectId, 
 ]); 
 $subscription = $pubsub->subscription($subscriptionName); 
 $policy = $subscription->iam()->policy(); 
 $policy['bindings'][] = [ 
 'role' => 'roles/pubsub.subscriber', 
 'members' => ['user:' . $userEmail] 
 ]; 
 $subscription->iam()->setPolicy($policy); 
 printf( 
 'User %s added to policy for %s' . PHP_EOL, 
 $userEmail, 
 $subscriptionName 
 ); 
 } 
 

Python

Before trying this sample, follow the Python setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Python API reference documentation .

  from 
  
 google.cloud 
  
 import 
 pubsub_v1 
 # TODO(developer): Choose an existing subscription. 
 # project_id = "your-project-id" 
 # subscription_id = "your-subscription-id" 
 client 
 = 
 pubsub_v1 
 . 
  SubscriberClient 
 
 () 
 subscription_path 
 = 
 client 
 . 
 subscription_path 
 ( 
 project_id 
 , 
 subscription_id 
 ) 
 policy 
 = 
 client 
 . 
 get_iam_policy 
 ( 
 request 
 = 
 { 
 "resource" 
 : 
 subscription_path 
 }) 
 # Add all users as viewers. 
 policy 
 . 
 bindings 
 . 
 add 
 ( 
 role 
 = 
 "roles/pubsub.viewer" 
 , 
 members 
 = 
 [ 
 "domain:google.com" 
 ]) 
 # Add a group as an editor. 
 policy 
 . 
 bindings 
 . 
 add 
 ( 
 role 
 = 
 "roles/editor" 
 , 
 members 
 = 
 [ 
 "group:cloud-logs@google.com" 
 ]) 
 # Set the policy 
 policy 
 = 
 client 
 . 
 set_iam_policy 
 ( 
 request 
 = 
 { 
 "resource" 
 : 
 subscription_path 
 , 
 "policy" 
 : 
 policy 
 } 
 ) 
 print 
 ( 
 "IAM policy for subscription 
 {} 
 set: 
 {} 
 " 
 . 
 format 
 ( 
 subscription_id 
 , 
 policy 
 )) 
 client 
 . 
  close 
 
 () 
 

Ruby

The following sample uses Ruby Pub/Sub client library v3. If you are still using the v2 library, see the migration guide to v3 . To see a list of Ruby v2 code samples, see the deprecated code samples .

Before trying this sample, follow the Ruby setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Ruby API reference documentation .

  # subscription_id       = "your-subscription-id" 
 # role                  = "roles/pubsub.subscriber" 
 # service_account_email = 
 # "serviceAccount:account_name@project_name.iam.gserviceaccount.com" 
 pubsub 
  
 = 
  
 Google 
 :: 
 Cloud 
 :: 
  PubSub 
 
 . 
  new 
 
 bindings 
  
 = 
  
 Google 
 :: 
 Iam 
 :: 
  V1 
 
 :: 
 Binding 
 . 
  new 
 
  
 \ 
  
 role 
 : 
  
 role 
 , 
  
 members 
 : 
  
 [ 
 service_account_email 
 ] 
 pubsub 
 . 
  iam 
 
 . 
 set_iam_policy 
  
 resource 
 : 
  
 pubsub 
 . 
 subscription_path 
 ( 
 subscription_id 
 ), 
  
 policy 
 : 
  
 { 
  
 bindings 
 : 
  
 [ 
 bindings 
 ] 
  
 } 
 

Here is some sample code to set a policy for a topic :

C#

Before trying this sample, follow the C# setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub C# API reference documentation .

  using 
  
  Google.Cloud.Iam.V1 
 
 ; 
 using 
  
  Google.Cloud.PubSub.V1 
 
 ; 
 public 
  
 class 
  
 SetTopicIamPolicySample 
 { 
  
 public 
  
 Policy 
  
 SetTopicIamPolicy 
 ( 
 string 
  
 projectId 
 , 
  
 string 
  
 topicId 
 , 
  
 string 
  
 role 
 , 
  
 string 
  
 member 
 ) 
  
 { 
  
  PublisherServiceApiClient 
 
  
 publisher 
  
 = 
  
  PublisherServiceApiClient 
 
 . 
  Create 
 
 (); 
  
 string 
  
 roleToBeAddedToPolicy 
  
 = 
  
 $"roles/{role}" 
 ; 
  
  Policy 
 
  
 policy 
  
 = 
  
 new 
  
  Policy 
 
  
 { 
  
 Bindings 
  
 = 
  
 { 
  
 new 
  
  Binding 
 
  
 { 
  
 Role 
  
 = 
  
 roleToBeAddedToPolicy 
 , 
  
 Members 
  
 = 
  
 { 
  
 member 
  
 } 
  
 } 
  
 } 
  
 }; 
  
  SetIamPolicyRequest 
 
  
 request 
  
 = 
  
 new 
  
  SetIamPolicyRequest 
 
  
 { 
  
 ResourceAsResourceName 
  
 = 
  
  TopicName 
 
 . 
  FromProjectTopic 
 
 ( 
 projectId 
 , 
  
 topicId 
 ), 
  
 Policy 
  
 = 
  
 policy 
  
 }; 
  
  Policy 
 
  
 response 
  
 = 
  
 publisher 
 . 
  IAMPolicyClient 
 
 . 
 SetIamPolicy 
 ( 
 request 
 ); 
  
 return 
  
 response 
 ; 
  
 } 
 } 
 

gcloud

1. Save the policy for the topic.

gcloud  
pubsub  
topics  
get-iam-policy  
\  
projects/ ${ 
 PROJECT 
 } 
/topics/ ${ 
 TOPIC 
 } 
  
\  
--format  
json  
>  
topic_policy.json

2. Open topic_policy.json and update bindings by giving appropriate roles to appropriate principals. For more information about working with subscription_policy.json files, see Policy in the IAM documentation.

  
 { 
  
 "etag" 
 : 
  
 "BwUjMhCsNvY=" 
 , 
  
 "bindings" 
 : 
  
 [ 
 { 
 "role": "roles/pubsub.editor", 
 "members": [ 
 "user:user-1@gmail.com", 
 "user:user-2@gmail.com" 
  
 ] 
  
 } 
  
 ] 
  
 } 

3. Apply the new topic policy.

gcloud  
pubsub  
topics  
set-iam-policy  
\  
projects/ ${ 
 PROJECT 
 } 
/topics/ ${ 
 TOPIC 
 } 
  
\  
topic_policy.json

Go

The following sample uses the major version of the Go Pub/Sub client library (v2). If you are still using the v1 library, see the migration guide to v2 . To see a list of v1 code samples, see the deprecated code samples .

Before trying this sample, follow the Go setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Go API reference documentation .

  import 
  
 ( 
  
 "context" 
  
 "fmt" 
  
 "io" 
  
 "cloud.google.com/go/iam/apiv1/iampb" 
  
 "cloud.google.com/go/pubsub/v2" 
 ) 
 func 
  
 addUsersToTopic 
 ( 
 w 
  
 io 
 . 
 Writer 
 , 
  
 projectID 
 , 
  
 topicID 
  
 string 
 ) 
  
 error 
  
 { 
  
 // projectID := "my-project-id" 
  
 // topicID := "my-topic" 
  
 ctx 
  
 := 
  
 context 
 . 
 Background 
 () 
  
 client 
 , 
  
 err 
  
 := 
  
 pubsub 
 . 
 NewClient 
 ( 
 ctx 
 , 
  
 projectID 
 ) 
  
 if 
  
 err 
  
 != 
  
 nil 
  
 { 
  
 return 
  
 fmt 
 . 
 Errorf 
 ( 
 "pubsub.NewClient: %w" 
 , 
  
 err 
 ) 
  
 } 
  
 defer 
  
 client 
 . 
 Close 
 () 
  
 topicName 
  
 := 
  
 fmt 
 . 
 Sprintf 
 ( 
 "projects/%s/topics/%s" 
 , 
  
 projectID 
 , 
  
 topicID 
 ) 
  
 req 
  
 := 
  
& iampb 
 . 
  GetIamPolicyRequest 
 
 { 
  
 Resource 
 : 
  
 topicName 
 , 
  
 } 
  
 policy 
 , 
  
 err 
  
 := 
  
 client 
 . 
 TopicAdminClient 
 . 
  GetIamPolicy 
 
 ( 
 ctx 
 , 
  
 req 
 ) 
  
 if 
  
 err 
  
 != 
  
 nil 
  
 { 
  
 return 
  
 fmt 
 . 
 Errorf 
 ( 
 "error calling GetIamPolicy: %w" 
 , 
  
 err 
 ) 
  
 } 
  
 b 
  
 := 
  
& iampb 
 . 
  Binding 
 
 { 
  
 Role 
 : 
  
 "roles/editor" 
 , 
  
 // Other valid prefixes are "serviceAccount:", "user:" 
  
 // See the documentation for more values. 
  
 Members 
 : 
  
 [] 
 string 
 { 
 "group:cloud-logs@google.com" 
 }, 
  
 } 
  
 policy 
 . 
 Bindings 
  
 = 
  
 append 
 ( 
 policy 
 . 
 Bindings 
 , 
  
 b 
 ) 
  
 setRequest 
  
 := 
  
& iampb 
 . 
  SetIamPolicyRequest 
 
 { 
  
 Resource 
 : 
  
 topicName 
 , 
  
 Policy 
 : 
  
 policy 
 , 
  
 } 
  
 _ 
 , 
  
 err 
  
 = 
  
 client 
 . 
 TopicAdminClient 
 . 
  SetIamPolicy 
 
 ( 
 ctx 
 , 
  
 setRequest 
 ) 
  
 if 
  
 err 
  
 != 
  
 nil 
  
 { 
  
 return 
  
 fmt 
 . 
 Errorf 
 ( 
 "error calling SetIamPolicy: %w" 
 , 
  
 err 
 ) 
  
 } 
  
 fmt 
 . 
 Fprintln 
 ( 
 w 
 , 
  
 "Added roles to topic." 
 ) 
  
 return 
  
 nil 
 } 
 

Java

Before trying this sample, follow the Java setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Java API reference documentation .

  import 
  
 com.google.cloud.pubsub.v1. TopicAdminClient 
 
 ; 
 import 
  
 com.google.iam.v1. Binding 
 
 ; 
 import 
  
 com.google.iam.v1. GetIamPolicyRequest 
 
 ; 
 import 
  
 com.google.iam.v1. Policy 
 
 ; 
 import 
  
 com.google.iam.v1. SetIamPolicyRequest 
 
 ; 
 import 
  
 com.google.pubsub.v1. TopicName 
 
 ; 
 import 
  
 java.io.IOException 
 ; 
 public 
  
 class 
 SetTopicPolicyExample 
  
 { 
  
 public 
  
 static 
  
 void 
  
 main 
 ( 
 String 
 ... 
  
 args 
 ) 
  
 throws 
  
 Exception 
  
 { 
  
 // TODO(developer): Replace these variables before running the sample. 
  
 String 
  
 projectId 
  
 = 
  
 "your-project-id" 
 ; 
  
 String 
  
 topicId 
  
 = 
  
 "your-topic-id" 
 ; 
  
 setTopicPolicyExample 
 ( 
 projectId 
 , 
  
 topicId 
 ); 
  
 } 
  
 public 
  
 static 
  
 void 
  
 setTopicPolicyExample 
 ( 
 String 
  
 projectId 
 , 
  
 String 
  
 topicId 
 ) 
  
 throws 
  
 IOException 
  
 { 
  
 try 
  
 ( 
  TopicAdminClient 
 
  
 topicAdminClient 
  
 = 
  
  TopicAdminClient 
 
 . 
 create 
 ()) 
  
 { 
  
  TopicName 
 
  
 topicName 
  
 = 
  
  TopicName 
 
 . 
 of 
 ( 
 projectId 
 , 
  
 topicId 
 ); 
  
  GetIamPolicyRequest 
 
  
 getIamPolicyRequest 
  
 = 
  
  GetIamPolicyRequest 
 
 . 
 newBuilder 
 (). 
 setResource 
 ( 
 topicName 
 . 
  toString 
 
 ()). 
 build 
 (); 
  
  Policy 
 
  
 oldPolicy 
  
 = 
  
 topicAdminClient 
 . 
 getIamPolicy 
 ( 
 getIamPolicyRequest 
 ); 
  
 // Create new role -> members binding 
  
  Binding 
 
  
 binding 
  
 = 
  
  Binding 
 
 . 
 newBuilder 
 () 
  
 . 
 setRole 
 ( 
 "roles/pubsub.editor" 
 ) 
  
 . 
  addMembers 
 
 ( 
 "domain:google.com" 
 ) 
  
 . 
 build 
 (); 
  
 // Add new binding to updated policy 
  
  Policy 
 
  
 updatedPolicy 
  
 = 
  
  Policy 
 
 . 
 newBuilder 
 ( 
 oldPolicy 
 ). 
  addBindings 
 
 ( 
 binding 
 ). 
 build 
 (); 
  
  SetIamPolicyRequest 
 
  
 setIamPolicyRequest 
  
 = 
  
  SetIamPolicyRequest 
 
 . 
 newBuilder 
 () 
  
 . 
 setResource 
 ( 
 topicName 
 . 
  toString 
 
 ()) 
  
 . 
  setPolicy 
 
 ( 
 updatedPolicy 
 ) 
  
 . 
 build 
 (); 
  
  Policy 
 
  
 newPolicy 
  
 = 
  
 topicAdminClient 
 . 
 setIamPolicy 
 ( 
 setIamPolicyRequest 
 ); 
  
 System 
 . 
 out 
 . 
 println 
 ( 
 "New topic policy: " 
  
 + 
  
 newPolicy 
 ); 
  
 } 
  
 } 
 } 
 

Node.js

Before trying this sample, follow the Node.js setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Node.js API reference documentation .

  /** 
 * TODO(developer): Uncomment this variable before running the sample. 
 */ 
 // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; 
 // Imports the Google Cloud client library 
 const 
  
 { 
 PubSub 
 } 
  
 = 
  
 require 
 ( 
 ' @google-cloud/pubsub 
' 
 ); 
 // Creates a client; cache this for further use 
 const 
  
 pubSubClient 
  
 = 
  
 new 
  
  PubSub 
 
 (); 
 async 
  
 function 
  
 setTopicPolicy 
 ( 
 topicNameOrId 
 ) 
  
 { 
  
 // The new IAM policy 
  
 const 
  
 newPolicy 
  
 = 
  
 { 
  
 bindings 
 : 
  
 [ 
  
 { 
  
 // Add a group as editors 
  
 role 
 : 
  
 'roles/pubsub.editor' 
 , 
  
 members 
 : 
  
 [ 
 'group:cloud-logs@google.com' 
 ], 
  
 }, 
  
 { 
  
 // Add all users as viewers 
  
 role 
 : 
  
 'roles/pubsub.viewer' 
 , 
  
 members 
 : 
  
 [ 
 'allUsers' 
 ], 
  
 }, 
  
 ], 
  
 }; 
  
 // Updates the IAM policy for the topic 
  
 const 
  
 [ 
 updatedPolicy 
 ] 
  
 = 
  
 await 
  
 pubSubClient 
  
 . 
 topic 
 ( 
 topicNameOrId 
 ) 
  
 . 
 iam 
 . 
  setPolicy 
 
 ( 
 newPolicy 
 ); 
  
 console 
 . 
 log 
 ( 
 'Updated policy for topic: %j' 
 , 
  
 updatedPolicy 
 . 
 bindings 
 ); 
 } 
 

PHP

  use Google\Cloud\PubSub\PubSubClient; 
 /** 
 * Adds a user to the policy for a Pub/Sub topic. 
 * 
 * @param string $projectId  The Google project ID. 
 * @param string $topicName  The Pub/Sub topic name. 
 * @param string $userEmail  The user email to add to the policy. 
 */ 
 function set_topic_policy($projectId, $topicName, $userEmail) 
 { 
 $pubsub = new PubSubClient([ 
 'projectId' => $projectId, 
 ]); 
 $topic = $pubsub->topic($topicName); 
 $policy = $topic->iam()->policy(); 
 $policy['bindings'][] = [ 
 'role' => 'roles/pubsub.publisher', 
 'members' => ['user:' . $userEmail] 
 ]; 
 $topic->iam()->setPolicy($policy); 
 printf( 
 'User %s added to policy for %s' . PHP_EOL, 
 $userEmail, 
 $topicName 
 ); 
 } 
 

Python

Before trying this sample, follow the Python setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Python API reference documentation .

  from 
  
 google.cloud 
  
 import 
 pubsub_v1 
 # TODO(developer): Choose an existing topic. 
 # project_id = "your-project-id" 
 # topic_id = "your-topic-id" 
 client 
 = 
 pubsub_v1 
 . 
  PublisherClient 
 
 () 
 topic_path 
 = 
 client 
 . 
 topic_path 
 ( 
 project_id 
 , 
 topic_id 
 ) 
 policy 
 = 
 client 
 . 
 get_iam_policy 
 ( 
 request 
 = 
 { 
 "resource" 
 : 
 topic_path 
 }) 
 # Add all users as viewers. 
 policy 
 . 
 bindings 
 . 
 add 
 ( 
 role 
 = 
 "roles/pubsub.viewer" 
 , 
 members 
 = 
 [ 
 "domain:google.com" 
 ]) 
 # Add a group as a publisher. 
 policy 
 . 
 bindings 
 . 
 add 
 ( 
 role 
 = 
 "roles/pubsub.publisher" 
 , 
 members 
 = 
 [ 
 "group:cloud-logs@google.com" 
 ] 
 ) 
 # Set the policy 
 policy 
 = 
 client 
 . 
 set_iam_policy 
 ( 
 request 
 = 
 { 
 "resource" 
 : 
 topic_path 
 , 
 "policy" 
 : 
 policy 
 }) 
 print 
 ( 
 "IAM policy for topic 
 {} 
 set: 
 {} 
 " 
 . 
 format 
 ( 
 topic_id 
 , 
 policy 
 )) 
 

Ruby

The following sample uses Ruby Pub/Sub client library v3. If you are still using the v2 library, see the migration guide to v3 . To see a list of Ruby v2 code samples, see the deprecated code samples .

Before trying this sample, follow the Ruby setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Ruby API reference documentation .

  # topic_id              = "your-topic-id" 
 # role                  = "roles/pubsub.publisher" 
 # service_account_email = 
 # "serviceAccount:account_name@project_name.iam.gserviceaccount.com" 
 pubsub 
  
 = 
  
 Google 
 :: 
 Cloud 
 :: 
  PubSub 
 
 . 
  new 
 
 bindings 
  
 = 
  
 Google 
 :: 
 Iam 
 :: 
  V1 
 
 :: 
 Binding 
 . 
  new 
 
  
 \ 
  
 role 
 : 
  
 role 
 , 
  
 members 
 : 
  
 [ 
 service_account_email 
 ] 
 pubsub 
 . 
  iam 
 
 . 
 set_iam_policy 
  
 resource 
 : 
  
 pubsub 
 . 
 topic_path 
 ( 
 topic_id 
 ), 
  
 policy 
 : 
  
 { 
  
 bindings 
 : 
  
 [ 
 bindings 
 ] 
  
 } 
 

Test permissions

You can use the testIamPermissions() method to check which of the given permissions can be added or removed for the given resource. It takes as parameters a resource name and a set of permissions, and returns the subset of permissions.

Here is some sample code to test permissions for a subscription :

C#

Before trying this sample, follow the C# setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub C# API reference documentation .

  using 
  
  Google.Cloud.Iam.V1 
 
 ; 
 using 
  
  Google.Cloud.PubSub.V1 
 
 ; 
 public 
  
 class 
  
 TestSubscriptionIamPermissionsSample 
 { 
  
 public 
  
 TestIamPermissionsResponse 
  
 TestSubscriptionIamPermissionsResponse 
 ( 
 string 
  
 projectId 
 , 
  
 string 
  
 subscriptionId 
 ) 
  
 { 
  
  TestIamPermissionsRequest 
 
  
 request 
  
 = 
  
 new 
  
  TestIamPermissionsRequest 
 
  
 { 
  
 ResourceAsResourceName 
  
 = 
  
  SubscriptionName 
 
 . 
  FromProjectSubscription 
 
 ( 
 projectId 
 , 
  
 subscriptionId 
 ), 
  
 Permissions 
  
 = 
  
 { 
  
 "pubsub.subscriptions.get" 
 , 
  
 "pubsub.subscriptions.update" 
  
 } 
  
 }; 
  
  PublisherServiceApiClient 
 
  
 publisher 
  
 = 
  
  PublisherServiceApiClient 
 
 . 
  Create 
 
 (); 
  
  TestIamPermissionsResponse 
 
  
 response 
  
 = 
  
 publisher 
 . 
  IAMPolicyClient 
 
 . 
 TestIamPermissions 
 ( 
 request 
 ); 
  
 return 
  
 response 
 ; 
  
 } 
 } 
 

gcloud

gcloud iam list-testable-permissions \
   https://pubsub.googleapis.com/v1/projects/${PROJECT}/subscriptions/${SUBSCRIPTION} \
   --format json

Output:

[
    {
     "name": "pubsub.subscriptions.consume",
     "stage": "GA"
   },
   {
     "name": "pubsub.subscriptions.delete",
     "stage": "GA"
   },
   {
     "name": "pubsub.subscriptions.get",
     "stage": "GA"
   },
   {
     "name": "pubsub.subscriptions.getIamPolicy",
     "stage": "GA"
    },
   {
     "name": "pubsub.subscriptions.setIamPolicy",
     "stage": "GA"
   },
   {
     "name": "pubsub.subscriptions.update",
     "stage": "GA"
   }
 ]

Go

The following sample uses the major version of the Go Pub/Sub client library (v2). If you are still using the v1 library, see the migration guide to v2 . To see a list of v1 code samples, see the deprecated code samples .

Before trying this sample, follow the Go setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Go API reference documentation .

  import 
  
 ( 
  
 "context" 
  
 "fmt" 
  
 "io" 
  
 "cloud.google.com/go/iam/apiv1/iampb" 
  
 "cloud.google.com/go/pubsub/v2" 
 ) 
 func 
  
 testPermissions 
 ( 
 w 
  
 io 
 . 
 Writer 
 , 
  
 projectID 
 , 
  
 subID 
  
 string 
 ) 
  
 ([] 
 string 
 , 
  
 error 
 ) 
  
 { 
  
 // projectID := "my-project-id" 
  
 // subID := "my-sub" 
  
 ctx 
  
 := 
  
 context 
 . 
 Background 
 () 
  
 client 
 , 
  
 err 
  
 := 
  
 pubsub 
 . 
 NewClient 
 ( 
 ctx 
 , 
  
 projectID 
 ) 
  
 if 
  
 err 
  
 != 
  
 nil 
  
 { 
  
 return 
  
 nil 
 , 
  
 fmt 
 . 
 Errorf 
 ( 
 "pubsub.NewClient: %w" 
 , 
  
 err 
 ) 
  
 } 
  
 req 
  
 := 
  
& iampb 
 . 
  TestIamPermissionsRequest 
 
 { 
  
 Resource 
 : 
  
 fmt 
 . 
 Sprintf 
 ( 
 "projects/%s/subscriptions/%s" 
 , 
  
 projectID 
 , 
  
 subID 
 ), 
  
 Permissions 
 : 
  
 [] 
 string 
 { 
  
 "pubsub.subscriptions.consume" 
 , 
  
 "pubsub.subscriptions.update" 
 , 
  
 }, 
  
 } 
  
 resp 
 , 
  
 err 
  
 := 
  
 client 
 . 
 SubscriptionAdminClient 
 . 
  TestIamPermissions 
 
 ( 
 ctx 
 , 
  
 req 
 ) 
  
 if 
  
 err 
  
 != 
  
 nil 
  
 { 
  
 return 
  
 nil 
 , 
  
 fmt 
 . 
 Errorf 
 ( 
 "error calling TestIamPermissions: %w" 
 , 
  
 err 
 ) 
  
 } 
  
 for 
  
 _ 
 , 
  
 perm 
  
 := 
  
 range 
  
 resp 
 . 
 Permissions 
  
 { 
  
 fmt 
 . 
 Fprintf 
 ( 
 w 
 , 
  
 "Allowed: %v\n" 
 , 
  
 perm 
 ) 
  
 } 
  
 return 
  
 resp 
 . 
 Permissions 
 , 
  
 nil 
 } 
 

Java

Before trying this sample, follow the Java setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Java API reference documentation .

  import 
  
 com.google.cloud.pubsub.v1. SubscriptionAdminClient 
 
 ; 
 import 
  
 com.google.iam.v1. TestIamPermissionsRequest 
 
 ; 
 import 
  
 com.google.iam.v1. TestIamPermissionsResponse 
 
 ; 
 import 
  
 com.google.pubsub.v1. ProjectSubscriptionName 
 
 ; 
 import 
  
 java.io.IOException 
 ; 
 import 
  
 java.util.LinkedList 
 ; 
 import 
  
 java.util.List 
 ; 
 public 
  
 class 
 TestSubscriptionPermissionsExample 
  
 { 
  
 public 
  
 static 
  
 void 
  
 main 
 ( 
 String 
 ... 
  
 args 
 ) 
  
 throws 
  
 Exception 
  
 { 
  
 // TODO(developer): Replace these variables before running the sample. 
  
 String 
  
 projectId 
  
 = 
  
 "your-project-id" 
 ; 
  
 String 
  
 subscriptionId 
  
 = 
  
 "your-subscription-id" 
 ; 
  
 testSubscriptionPermissionsExample 
 ( 
 projectId 
 , 
  
 subscriptionId 
 ); 
  
 } 
  
 public 
  
 static 
  
 void 
  
 testSubscriptionPermissionsExample 
 ( 
 String 
  
 projectId 
 , 
  
 String 
  
 subscriptionId 
 ) 
  
 throws 
  
 IOException 
  
 { 
  
 try 
  
 ( 
  SubscriptionAdminClient 
 
  
 subscriptionAdminClient 
  
 = 
  
  SubscriptionAdminClient 
 
 . 
 create 
 ()) 
  
 { 
  
  ProjectSubscriptionName 
 
  
 subscriptionName 
  
 = 
  
  ProjectSubscriptionName 
 
 . 
 of 
 ( 
 projectId 
 , 
  
 subscriptionId 
 ); 
  
 List<String> 
  
 permissions 
  
 = 
  
 new 
  
 LinkedList 
<> (); 
  
 permissions 
 . 
 add 
 ( 
 "pubsub.subscriptions.consume" 
 ); 
  
 permissions 
 . 
 add 
 ( 
 "pubsub.subscriptions.update" 
 ); 
  
  TestIamPermissionsRequest 
 
  
 testIamPermissionsRequest 
  
 = 
  
  TestIamPermissionsRequest 
 
 . 
 newBuilder 
 () 
  
 . 
 setResource 
 ( 
 subscriptionName 
 . 
  toString 
 
 ()) 
  
 . 
 addAllPermissions 
 ( 
 permissions 
 ) 
  
 . 
 build 
 (); 
  
  TestIamPermissionsResponse 
 
  
 testedPermissionsResponse 
  
 = 
  
 subscriptionAdminClient 
 . 
 testIamPermissions 
 ( 
 testIamPermissionsRequest 
 ); 
  
 System 
 . 
 out 
 . 
 println 
 ( 
 "Tested:\n" 
  
 + 
  
 testedPermissionsResponse 
 ); 
  
 } 
  
 } 
 } 
 

Node.js

Before trying this sample, follow the Node.js setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Node.js API reference documentation .

  /** 
 * TODO(developer): Uncomment this variable before running the sample. 
 */ 
 // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; 
 // Imports the Google Cloud client library 
 const 
  
 { 
 PubSub 
 } 
  
 = 
  
 require 
 ( 
 ' @google-cloud/pubsub 
' 
 ); 
 // Creates a client; cache this for further use 
 const 
  
 pubSubClient 
  
 = 
  
 new 
  
  PubSub 
 
 (); 
 async 
  
 function 
  
 testSubscriptionPermissions 
 ( 
 subscriptionNameOrId 
 ) 
  
 { 
  
 const 
  
 permissionsToTest 
  
 = 
  
 [ 
  
 'pubsub.subscriptions.consume' 
 , 
  
 'pubsub.subscriptions.update' 
 , 
  
 ]; 
  
 // Tests the IAM policy for the specified subscription 
  
 const 
  
 [ 
 permissions 
 ] 
  
 = 
  
 await 
  
 pubSubClient 
  
 . 
 subscription 
 ( 
 subscriptionNameOrId 
 ) 
  
 . 
 iam 
 . 
  testPermissions 
 
 ( 
 permissionsToTest 
 ); 
  
 console 
 . 
 log 
 ( 
 'Tested permissions for subscription: %j' 
 , 
  
 permissions 
 ); 
 } 
 

PHP

Before trying this sample, follow the PHP setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub PHP API reference documentation .

  use Google\Cloud\PubSub\PubSubClient; 
 /** 
 * Prints the permissions of a subscription. 
 * 
 * @param string $projectId  The Google project ID. 
 * @param string $subscriptionName  The Pub/Sub subscription name. 
 */ 
 function test_subscription_permissions($projectId, $subscriptionName) 
 { 
 $pubsub = new PubSubClient([ 
 'projectId' => $projectId, 
 ]); 
 $subscription = $pubsub->subscription($subscriptionName); 
 $permissions = $subscription->iam()->testPermissions([ 
 'pubsub.subscriptions.consume', 
 'pubsub.subscriptions.update' 
 ]); 
 foreach ($permissions as $permission) { 
 printf('Permission: %s' . PHP_EOL, $permission); 
 } 
 } 
 

Python

Before trying this sample, follow the Python setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Python API reference documentation .

  from 
  
 google.cloud 
  
 import 
 pubsub_v1 
 # TODO(developer): Choose an existing subscription. 
 # project_id = "your-project-id" 
 # subscription_id = "your-subscription-id" 
 client 
 = 
 pubsub_v1 
 . 
  SubscriberClient 
 
 () 
 subscription_path 
 = 
 client 
 . 
 subscription_path 
 ( 
 project_id 
 , 
 subscription_id 
 ) 
 permissions_to_check 
 = 
 [ 
 "pubsub.subscriptions.consume" 
 , 
 "pubsub.subscriptions.update" 
 , 
 ] 
 allowed_permissions 
 = 
 client 
 . 
 test_iam_permissions 
 ( 
 request 
 = 
 { 
 "resource" 
 : 
 subscription_path 
 , 
 "permissions" 
 : 
 permissions_to_check 
 } 
 ) 
 print 
 ( 
 "Allowed permissions for subscription 
 {} 
 : 
 {} 
 " 
 . 
 format 
 ( 
 subscription_path 
 , 
 allowed_permissions 
 ) 
 ) 
 client 
 . 
  close 
 
 () 
 

Ruby

The following sample uses Ruby Pub/Sub client library v3. If you are still using the v2 library, see the migration guide to v3 . To see a list of Ruby v2 code samples, see the deprecated code samples .

Before trying this sample, follow the Ruby setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Ruby API reference documentation .

  # subscription_id = "your-subscription-id" 
 pubsub 
  
 = 
  
 Google 
 :: 
 Cloud 
 :: 
  PubSub 
 
 . 
  new 
 
 subscription_admin 
  
 = 
  
 pubsub 
 . 
  subscription_admin 
 
 permissions 
  
 = 
  
 [ 
 "pubsub.subscriptions.consume" 
 , 
  
 "pubsub.subscriptions.update" 
 ] 
 response 
  
 = 
  
 pubsub 
 . 
  iam 
 
 . 
 test_iam_permissions 
  
 \ 
  
 resource 
 : 
  
 pubsub 
 . 
 subscription_path 
 ( 
 subscription_id 
 ), 
  
 permissions 
 : 
  
 permissions 
 puts 
  
 "Permission to consume" 
  
 \ 
  
 if 
  
 response 
 . 
 permissions 
 . 
 include? 
  
 "pubsub.subscriptions.consume" 
 puts 
  
 "Permission to update" 
  
 \ 
  
 if 
  
 response 
 . 
 permissions 
 . 
 include? 
  
 "pubsub.subscriptions.update" 
 

Here is some sample code to test permissions for a topic :

C#

Before trying this sample, follow the C# setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub C# API reference documentation .

  using 
  
  Google.Cloud.Iam.V1 
 
 ; 
 using 
  
  Google.Cloud.PubSub.V1 
 
 ; 
 public 
  
 class 
  
 TestTopicIamPermissionsSample 
 { 
  
 public 
  
 TestIamPermissionsResponse 
  
 TestTopicIamPermissions 
 ( 
 string 
  
 projectId 
 , 
  
 string 
  
 topicId 
 ) 
  
 { 
  
  TestIamPermissionsRequest 
 
  
 request 
  
 = 
  
 new 
  
  TestIamPermissionsRequest 
 
  
 { 
  
 ResourceAsResourceName 
  
 = 
  
  TopicName 
 
 . 
  FromProjectTopic 
 
 ( 
 projectId 
 , 
  
 topicId 
 ), 
  
 Permissions 
  
 = 
  
 { 
  
 "pubsub.topics.get" 
 , 
  
 "pubsub.topics.update" 
  
 } 
  
 }; 
  
  PublisherServiceApiClient 
 
  
 publisher 
  
 = 
  
  PublisherServiceApiClient 
 
 . 
  Create 
 
 (); 
  
  TestIamPermissionsResponse 
 
  
 response 
  
 = 
  
 publisher 
 . 
  IAMPolicyClient 
 
 . 
 TestIamPermissions 
 ( 
 request 
 ); 
  
 return 
  
 response 
 ; 
  
 } 
 } 
 

gcloud

gcloud iam list-testable-permissions \
   https://pubsub.googleapis.com/v1/projects/${PROJECT}/topics/${TOPIC} \
   --format json

Output

[
   {
     "name": "pubsub.topics.attachSubscription",
     "stage": "GA"
   },
   {
     "name": "pubsub.topics.delete",
     "stage": "GA"
   },
   {
     "name": "pubsub.topics.detachSubscription",
     "stage": "GA"
   },
   {
     "name": "pubsub.topics.get",
     "stage": "GA"
   },
   {
     "name": "pubsub.topics.getIamPolicy",
     "stage": "GA"
   },
   {
     "name": "pubsub.topics.publish",
     "stage": "GA"
   },
   {
     "name": "pubsub.topics.setIamPolicy",
     "stage": "GA"
   },
   {
     "name": "pubsub.topics.update",
     "stage": "GA"
   }
 ]

Go

The following sample uses the major version of the Go Pub/Sub client library (v2). If you are still using the v1 library, see the migration guide to v2 . To see a list of v1 code samples, see the deprecated code samples .

Before trying this sample, follow the Go setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Go API reference documentation .

  import 
  
 ( 
  
 "context" 
  
 "fmt" 
  
 "io" 
  
 "cloud.google.com/go/iam/apiv1/iampb" 
  
 "cloud.google.com/go/pubsub/v2" 
 ) 
 func 
  
 testPermissions 
 ( 
 w 
  
 io 
 . 
 Writer 
 , 
  
 projectID 
 , 
  
 topicID 
  
 string 
 ) 
  
 ([] 
 string 
 , 
  
 error 
 ) 
  
 { 
  
 // projectID := "my-project-id" 
  
 // topicID := "my-topic" 
  
 ctx 
  
 := 
  
 context 
 . 
 Background 
 () 
  
 client 
 , 
  
 err 
  
 := 
  
 pubsub 
 . 
 NewClient 
 ( 
 ctx 
 , 
  
 projectID 
 ) 
  
 if 
  
 err 
  
 != 
  
 nil 
  
 { 
  
 return 
  
 nil 
 , 
  
 fmt 
 . 
 Errorf 
 ( 
 "pubsub.NewClient: %w" 
 , 
  
 err 
 ) 
  
 } 
  
 req 
  
 := 
  
& iampb 
 . 
  TestIamPermissionsRequest 
 
 { 
  
 Resource 
 : 
  
 fmt 
 . 
 Sprintf 
 ( 
 "projects/%s/topics/%s" 
 , 
  
 projectID 
 , 
  
 topicID 
 ), 
  
 Permissions 
 : 
  
 [] 
 string 
 { 
  
 "pubsub.topics.publish" 
 , 
  
 "pubsub.topics.update" 
 , 
  
 }, 
  
 } 
  
 resp 
 , 
  
 err 
  
 := 
  
 client 
 . 
 TopicAdminClient 
 . 
  TestIamPermissions 
 
 ( 
 ctx 
 , 
  
 req 
 ) 
  
 if 
  
 err 
  
 != 
  
 nil 
  
 { 
  
 return 
  
 nil 
 , 
  
 fmt 
 . 
 Errorf 
 ( 
 "error calling TestIamPermissions: %w" 
 , 
  
 err 
 ) 
  
 } 
  
 for 
  
 _ 
 , 
  
 perm 
  
 := 
  
 range 
  
 resp 
 . 
 Permissions 
  
 { 
  
 fmt 
 . 
 Fprintf 
 ( 
 w 
 , 
  
 "Allowed: %v\n" 
 , 
  
 perm 
 ) 
  
 } 
  
 return 
  
 resp 
 . 
 Permissions 
 , 
  
 nil 
 } 
 

Java

Before trying this sample, follow the Java setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Java API reference documentation .

  import 
  
 com.google.cloud.pubsub.v1. TopicAdminClient 
 
 ; 
 import 
  
 com.google.iam.v1. TestIamPermissionsRequest 
 
 ; 
 import 
  
 com.google.iam.v1. TestIamPermissionsResponse 
 
 ; 
 import 
  
 com.google.pubsub.v1. ProjectTopicName 
 
 ; 
 import 
  
 java.io.IOException 
 ; 
 import 
  
 java.util.LinkedList 
 ; 
 import 
  
 java.util.List 
 ; 
 public 
  
 class 
 TestTopicPermissionsExample 
  
 { 
  
 public 
  
 static 
  
 void 
  
 main 
 ( 
 String 
 ... 
  
 args 
 ) 
  
 throws 
  
 Exception 
  
 { 
  
 // TODO(developer): Replace these variables before running the sample. 
  
 String 
  
 projectId 
  
 = 
  
 "your-project-id" 
 ; 
  
 String 
  
 topicId 
  
 = 
  
 "your-topic-id" 
 ; 
  
 testTopicPermissionsExample 
 ( 
 projectId 
 , 
  
 topicId 
 ); 
  
 } 
  
 public 
  
 static 
  
 void 
  
 testTopicPermissionsExample 
 ( 
 String 
  
 projectId 
 , 
  
 String 
  
 topicId 
 ) 
  
 throws 
  
 IOException 
  
 { 
  
 try 
  
 ( 
  TopicAdminClient 
 
  
 topicAdminClient 
  
 = 
  
  TopicAdminClient 
 
 . 
 create 
 ()) 
  
 { 
  
  ProjectTopicName 
 
  
 topicName 
  
 = 
  
  ProjectTopicName 
 
 . 
 of 
 ( 
 projectId 
 , 
  
 topicId 
 ); 
  
 List<String> 
  
 permissions 
  
 = 
  
 new 
  
 LinkedList 
<> (); 
  
 permissions 
 . 
 add 
 ( 
 "pubsub.topics.attachSubscription" 
 ); 
  
 permissions 
 . 
 add 
 ( 
 "pubsub.topics.publish" 
 ); 
  
 permissions 
 . 
 add 
 ( 
 "pubsub.topics.update" 
 ); 
  
  TestIamPermissionsRequest 
 
  
 testIamPermissionsRequest 
  
 = 
  
  TestIamPermissionsRequest 
 
 . 
 newBuilder 
 () 
  
 . 
 setResource 
 ( 
 topicName 
 . 
  toString 
 
 ()) 
  
 . 
 addAllPermissions 
 ( 
 permissions 
 ) 
  
 . 
 build 
 (); 
  
  TestIamPermissionsResponse 
 
  
 testedPermissionsResponse 
  
 = 
  
 topicAdminClient 
 . 
 testIamPermissions 
 ( 
 testIamPermissionsRequest 
 ); 
  
 System 
 . 
 out 
 . 
 println 
 ( 
 "Tested:\n" 
  
 + 
  
 testedPermissionsResponse 
 ); 
  
 } 
  
 } 
 } 
 

Node.js

Before trying this sample, follow the Node.js setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Node.js API reference documentation .

  /** 
 * TODO(developer): Uncomment this variable before running the sample. 
 */ 
 // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; 
 // Imports the Google Cloud client library 
 const 
  
 { 
 PubSub 
 } 
  
 = 
  
 require 
 ( 
 ' @google-cloud/pubsub 
' 
 ); 
 // Creates a client; cache this for further use 
 const 
  
 pubSubClient 
  
 = 
  
 new 
  
  PubSub 
 
 (); 
 async 
  
 function 
  
 testTopicPermissions 
 ( 
 topicNameOrId 
 ) 
  
 { 
  
 const 
  
 permissionsToTest 
  
 = 
  
 [ 
  
 'pubsub.topics.attachSubscription' 
 , 
  
 'pubsub.topics.publish' 
 , 
  
 'pubsub.topics.update' 
 , 
  
 ]; 
  
 // Tests the IAM policy for the specified topic 
  
 const 
  
 [ 
 permissions 
 ] 
  
 = 
  
 await 
  
 pubSubClient 
  
 . 
 topic 
 ( 
 topicNameOrId 
 ) 
  
 . 
 iam 
 . 
  testPermissions 
 
 ( 
 permissionsToTest 
 ); 
  
 console 
 . 
 log 
 ( 
 'Tested permissions for topic: %j' 
 , 
  
 permissions 
 ); 
 } 
 

PHP

Before trying this sample, follow the PHP setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub PHP API reference documentation .

  use Google\Cloud\PubSub\PubSubClient; 
 /** 
 * Prints the permissions of a topic. 
 * 
 * @param string $projectId  The Google project ID. 
 * @param string $topicName  The Pub/Sub topic name. 
 */ 
 function test_topic_permissions($projectId, $topicName) 
 { 
 $pubsub = new PubSubClient([ 
 'projectId' => $projectId, 
 ]); 
 $topic = $pubsub->topic($topicName); 
 $permissions = $topic->iam()->testPermissions([ 
 'pubsub.topics.attachSubscription', 
 'pubsub.topics.publish', 
 'pubsub.topics.update' 
 ]); 
 foreach ($permissions as $permission) { 
 printf('Permission: %s' . PHP_EOL, $permission); 
 } 
 } 
 

Python

Before trying this sample, follow the Python setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Python API reference documentation .

  from 
  
 google.cloud 
  
 import 
 pubsub_v1 
 # TODO(developer): Choose an existing topic. 
 # project_id = "your-project-id" 
 # topic_id = "your-topic-id" 
 client 
 = 
 pubsub_v1 
 . 
  PublisherClient 
 
 () 
 topic_path 
 = 
 client 
 . 
 topic_path 
 ( 
 project_id 
 , 
 topic_id 
 ) 
 permissions_to_check 
 = 
 [ 
 "pubsub.topics.publish" 
 , 
 "pubsub.topics.update" 
 ] 
 allowed_permissions 
 = 
 client 
 . 
 test_iam_permissions 
 ( 
 request 
 = 
 { 
 "resource" 
 : 
 topic_path 
 , 
 "permissions" 
 : 
 permissions_to_check 
 } 
 ) 
 print 
 ( 
 "Allowed permissions for topic 
 {} 
 : 
 {} 
 " 
 . 
 format 
 ( 
 topic_path 
 , 
 allowed_permissions 
 ) 
 ) 
 

Ruby

The following sample uses Ruby Pub/Sub client library v3. If you are still using the v2 library, see the migration guide to v3 . To see a list of Ruby v2 code samples, see the deprecated code samples .

Before trying this sample, follow the Ruby setup instructions in Quickstart: Using Client Libraries . For more information, see the Pub/Sub Ruby API reference documentation .

  # topic_id = "your-topic-id" 
 pubsub 
  
 = 
  
 Google 
 :: 
 Cloud 
 :: 
  PubSub 
 
 . 
  new 
 
 topic_admin 
  
 = 
  
 pubsub 
 . 
  topic_admin 
 
 permissions 
  
 = 
  
 [ 
 "pubsub.topics.attachSubscription" 
 , 
  
 "pubsub.topics.publish" 
 , 
  
 "pubsub.topics.update" 
 ] 
 response 
  
 = 
  
 pubsub 
 . 
  iam 
 
 . 
 test_iam_permissions 
  
 \ 
  
 resource 
 : 
  
 pubsub 
 . 
 topic_path 
 ( 
 topic_id 
 ), 
  
 permissions 
 : 
  
 permissions 
 puts 
  
 "Permission to attach subscription" 
  
 \ 
  
 if 
  
 permissions 
 . 
 include? 
  
 "pubsub.topics.attachSubscription" 
 puts 
  
 "Permission to publish" 
  
 \ 
  
 if 
  
 response 
 . 
 permissions 
 . 
 include? 
  
 "pubsub.topics.publish" 
 puts 
  
 "Permission to update" 
  
 \ 
  
 if 
  
 response 
 . 
 permissions 
 . 
 include? 
  
 "pubsub.topics.update" 
 

Cross-project communication

Pub/Sub IAM is useful for fine-tuning access in cross-project communication.

Suppose a service account in Cloud Project A wants to publish messages to a topic in Cloud Project B. First, enable the Pub/Sub API in Project A.

Second, grant the service account Editpermission in Cloud Project B. However, this approach is often too coarse. You can use the IAM API to achieve a more fine-grained level of access.

Cross-project communication

For example, this snippet uses the setIamPolicy() method in project-b and a prepared topic_policy.json file to grant the service account foobar@ project-a .iam.gserviceaccount.com of project-a the publisher role on the topic projects/ project-b /topics/ topic-b :

gcloud pubsub topics set-iam-policy \
    projects/ project-b 
/topics/ topic-b 
\
    topic_policy.json
Output:
Updated IAM policy for topic topic-b 
.
bindings:
- members:
  - serviceAccount:foobar@ project-a 
.iam.gserviceaccount.com
  role: roles/pubsub.publisher
etag: BwWGrQYX6R4=

Partial availability behavior

Authorization checks depend on the IAM subsystem. In order to offer consistently low response latency for data operations (publishing and message consumption), the system may fall back on cached IAM policies. For information about when your changes will take effect, see the IAM documentation .

What's Next

Design a Mobile Site
View Site in Mobile | Classic
Share by: