设置订阅政策

设置订阅 IAM 政策。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

C++

在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 C++ 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub C++ API 参考文档

如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

namespace iam = google::cloud::iam;
namespace pubsub = google::cloud::pubsub;
using google::cloud::StatusCode;
[](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()));

  // In production code, consider an OCC loop to handle concurrent changes
  // to the policy.
  google::iam::v1::GetIamPolicyRequest get;
  get.set_resource(subscription.FullName());
  auto policy = client.GetIamPolicy(get);
  if (!policy) throw std::move(policy).status();

  google::iam::v1::SetIamPolicyRequest set;
  set.set_resource(subscription.FullName());
  *set.mutable_policy() = *std::move(policy);
  // Add all users as viewers.
  auto& b0 = *set.mutable_policy()->add_bindings();
  b0.set_role("roles/pubsub.viewer");
  b0.add_members("domain:google.com");
  // Add a group as an editor.
  auto& b1 = *set.mutable_policy()->add_bindings();
  b1.set_role("roles/editor");
  b1.add_members("group:cloud-logs@google.com");

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

C#

在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 C# 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub C# API 参考文档

如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


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

Go

在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Go 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Go API 参考文档

如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"

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

// addUsers adds all IAM users to a subscription.
func addUsers(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()

	sub := client.Subscription(subID)
	policy, err := sub.IAM().Policy(ctx)
	if err != nil {
		return fmt.Errorf("err getting IAM Policy: %w", err)
	}
	// Other valid prefixes are "serviceAccount:", "user:"
	// See the documentation for more values.
	policy.Add(iam.AllUsers, iam.Viewer)
	policy.Add("group:cloud-logs@google.com", iam.Editor)
	if err := sub.IAM().SetPolicy(ctx, policy); err != nil {
		return fmt.Errorf("SetPolicy: %w", err)
	}
	// NOTE: It may be necessary to retry this operation if IAM policies are
	// being modified concurrently. SetPolicy will return an error if the policy
	// was modified since it was retrieved.
	return nil
}

Java

在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Java 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Java API 参考文档

如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


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

/**
 * 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);
}

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 setSubscriptionPolicy(subscriptionNameOrId: string) {
  // The new IAM policy
  const newPolicy: Policy = {
    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

在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 PHP 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub PHP API 参考文档

如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Python 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Python API 参考文档

如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Ruby API 参考文档

如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

# subscription_id       = "your-subscription-id"
# role                  = "roles/pubsub.publisher"
# service_account_email = "serviceAccount:account_name@project_name.iam.gserviceaccount.com"

pubsub = Google::Cloud::Pubsub.new

subscription = pubsub.subscription subscription_id
subscription.policy do |policy|
  policy.add role, service_account_email
end

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器