列出角色

演示了商家信息角色。

包含此代码示例的文档页面

如需查看上下文中使用的代码示例,请参阅以下文档:

代码示例

C#

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM C# API 参考文档


using System;
using System.Collections.Generic;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Iam.v1;
using Google.Apis.Iam.v1.Data;

public partial class CustomRoles
{
    public static IList<Role> ListRoles(string projectId)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var response = service.Projects.Roles.List("projects/" + projectId)
            .Execute();
        foreach (var role in response.Roles)
        {
            Console.WriteLine(role.Name);
        }
        return response.Roles;
    }
}

C++

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM C++ API 参考文档

namespace iam = ::google::cloud::iam;
[](std::string const& project) {
  iam::IAMClient client(iam::MakeIAMConnection());
  int count = 0;
  google::iam::admin::v1::ListRolesRequest request;
  request.set_parent(project);
  for (auto const& role : client.ListRoles(request)) {
    if (!role) throw std::runtime_error(role.status().message());
    std::cout << "Roles successfully retrieved: " << role->name() << "\n";
    ++count;
  }
  if (count == 0) {
    std::cout << "No roles found in project: " << project << "\n";
  }
}

Go

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Go API 参考文档

import (
	"context"
	"fmt"
	"io"

	iam "google.golang.org/api/iam/v1"
)

// listRoles lists a project's roles.
func listRoles(w io.Writer, projectID string) ([]*iam.Role, error) {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return nil, fmt.Errorf("iam.NewService: %v", err)
	}

	response, err := service.Projects.Roles.List("projects/" + projectID).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.Roles.List: %v", err)
	}
	for _, role := range response.Roles {
		fmt.Fprintf(w, "Listing role: %v\n", role.Name)
	}
	return response.Roles, nil
}

Python

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Python API 参考文档

def list_roles(project_id):
    """Lists roles."""

    # pylint: disable=no-member
    roles = service.roles().list(
        parent='projects/' + project_id).execute()['roles']
    for role in roles:
        print(role['name'])

后续步骤

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