Get a role

Demonstrates retrieving a role.

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& name) {
  iam::IAMClient client(iam::MakeIAMConnection());
  google::iam::admin::v1::GetRoleRequest request;
  request.set_name(name);
  auto response = client.GetRole(request);
  if (!response) throw std::move(response).status();
  std::cout << "Role successfully retrieved: " << response->DebugString()
            << "\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 Google.Apis.Auth.OAuth2;
using Google.Apis.Iam.v1;
using Google.Apis.Iam.v1.Data;

public partial class CustomRoles
{
    public static Role GetRole(string name)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var role = service.Roles.Get(name).Execute();
        Console.WriteLine(role.Name);
        Console.WriteLine(String.Join(", ", role.IncludedPermissions));
        return role;
    }
}

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"
)

// getRole gets role metadata.
func getRole(w io.Writer, name string) (*iam.Role, error) {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return nil, fmt.Errorf("iam.NewService: %w", err)
	}

	role, err := service.Roles.Get(name).Do()
	if err != nil {
		return nil, fmt.Errorf("Roles.Get: %w", err)
	}
	fmt.Fprintf(w, "Got role: %v\n", role.Name)
	for _, permission := range role.IncludedPermissions {
		fmt.Fprintf(w, "Got permission: %v\n", permission)
	}
	return role, 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.iam.admin.v1.GetRoleRequest;
import com.google.iam.admin.v1.Role;
import java.io.IOException;

/** Get role metadata. Specifically, printing out role permissions. */
public class GetRole {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace the variable before running the sample.
    String roleId = "a unique identifier (e.g. testViewer)";

    getRole(roleId);
  }

  public static void getRole(String roleId) throws IOException {
    GetRoleRequest getRoleRequest = GetRoleRequest.newBuilder().setName(roleId).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()) {
      Role role = iamClient.getRole(getRoleRequest);
      role.getIncludedPermissionsList().forEach(permission -> System.out.println(permission));
    }
  }
}

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 get_role(name: str) -> None:
    """Gets a role."""

    # pylint: disable=no-member
    role = service.roles().get(name=name).execute()
    print(role["name"])
    for permission in role["includedPermissions"]:
        print(permission)

What's next

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