Get subscription policy

Gets the IAM policy associated with a subscription.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C++

Before trying this sample, follow the C++ setup instructions in the Pub/Sub quickstart using client libraries. For more information, see the Pub/Sub C++ API reference documentation.

To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

namespace iam = google::cloud::iam;
namespace pubsub = google::cloud::pubsub;
[](std::string project_id, std::string subscription_id) {
  auto const subscription =
      pubsub::Subscription(std::move(project_id), std::move(subscription_id));
  auto client = iam::IAMPolicyClient(
      iam::MakeIAMPolicyConnection(pubsub::IAMPolicyOptions()));
  google::iam::v1::GetIamPolicyRequest request;
  request.set_resource(subscription.FullName());

  auto response = client.GetIamPolicy(request);
  if (!response) throw std::move(response).status();
  std::cout << "Policy for subscription " << subscription.FullName() << ": "
            << response->DebugString() << "\n";
}

C#

Before trying this sample, follow the C# setup instructions in the Pub/Sub quickstart using client libraries. For more information, see the Pub/Sub C# API reference documentation.

To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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;
    }
}

Go

Before trying this sample, follow the Go setup instructions in the Pub/Sub quickstart using client libraries. For more information, see the Pub/Sub Go API reference documentation.

To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/iam"
	"cloud.google.com/go/pubsub"
)

func policy(w io.Writer, projectID, subID string) (*iam.Policy, 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)
	}
	defer client.Close()

	policy, err := client.Subscription(subID).IAM().Policy(ctx)
	if err != nil {
		return nil, fmt.Errorf("Subscription: %w", err)
	}
	for _, role := range policy.Roles() {
		fmt.Fprintf(w, "%q: %q\n", role, policy.Members(role))
	}
	return policy, nil
}

Java

Before trying this sample, follow the Java setup instructions in the Pub/Sub quickstart using client libraries. For more information, see the Pub/Sub Java API reference documentation.

To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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

/**
 * 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

/**
 * 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 the Pub/Sub quickstart using client libraries. For more information, see the Pub/Sub PHP API reference documentation.

To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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 the Pub/Sub quickstart using client libraries. For more information, see the Pub/Sub Python API reference documentation.

To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

Before trying this sample, follow the Ruby setup instructions in the Pub/Sub quickstart using client libraries. For more information, see the Pub/Sub Ruby API reference documentation.

To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

# subscription_id = "your-subscription-id"

pubsub = Google::Cloud::Pubsub.new

subscription = pubsub.subscription subscription_id
policy       = subscription.policy

puts "Subscription policy:"
puts policy.roles

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.