List roles

Demonstrates listing roles.

Explore further

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

Code sample

C++

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM C++ API reference documentation.

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

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

C#

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM C# API reference documentation.

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


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

Go

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM Go API reference documentation.

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

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: %w", err)
	}

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

Java

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM Java API reference documentation.

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


import com.google.cloud.iam.admin.v1.IAMClient;
import com.google.cloud.iam.admin.v1.IAMClient.ListRolesPagedResponse;
import com.google.iam.admin.v1.ListRolesRequest;
import java.io.IOException;

/** List roles in a project. */
public class ListRoles {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace the variable before running the sample.
    String projectId = "your-project-id";

    listRoles(projectId);
  }

  public static void listRoles(String projectId) throws IOException {
    ListRolesRequest listRolesRequest =
        ListRolesRequest.newBuilder().setParent("projects/" + projectId).build();

    // Initialize client for sending requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (IAMClient iamClient = IAMClient.create()) {
      ListRolesPagedResponse listRolesResponse = iamClient.listRoles(listRolesRequest);
      listRolesResponse.iterateAll().forEach(role -> System.out.println(role));
    }
  }
}

Python

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM Python API reference documentation.

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

def list_roles(project_id: str) -> None:
    """Lists roles."""

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

What's next

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