View grantable roles

Demonstrates viewing the roles that you can grant on a specific resource.

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& resource) {
  iam::IAMClient client(iam::MakeIAMConnection());
  int count = 0;
  for (auto& role : client.QueryGrantableRoles(resource)) {
    if (!role) throw std::move(role).status();
    std::cout << "Role successfully retrieved: " << role->name() << "\n";
    ++count;
  }
  if (count == 0) {
    std::cout << "No grantable roles found in resource: " << resource << "\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> ViewGrantableRoles(string fullResourceName)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var request = new QueryGrantableRolesRequest
        {
            FullResourceName = fullResourceName
        };
        var response = service.Roles.QueryGrantableRoles(request).Execute();
        foreach (var role in response.Roles)
        {
            Console.WriteLine("Title: " + role.Title);
            Console.WriteLine("Name: " + role.Name);
            Console.WriteLine("Description: " + role.Description);
            Console.WriteLine();
        }
        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"
)

// viewGrantableRoles lists roles grantable on a resource.
func viewGrantableRoles(w io.Writer, fullResourceName string) ([]*iam.Role, error) {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return nil, fmt.Errorf("iam.NewService: %w", err)
	}

	request := &iam.QueryGrantableRolesRequest{
		FullResourceName: fullResourceName,
	}
	response, err := service.Roles.QueryGrantableRoles(request).Do()
	if err != nil {
		return nil, fmt.Errorf("Roles.QueryGrantableRoles: %w", err)
	}
	for _, role := range response.Roles {
		fmt.Fprintf(w, "Found grantable role: %v\n", role.Name)
	}
	return response.Roles, err
}

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.

QueryGrantableRolesRequest request = new QueryGrantableRolesRequest();
request.setFullResourceName(fullResourceName);

QueryGrantableRolesResponse response = service.roles().queryGrantableRoles(request).execute();

for (Role role : response.getRoles()) {
  System.out.println("Title: " + role.getTitle());
  System.out.println("Name: " + role.getName());
  System.out.println("Description: " + role.getDescription());
  System.out.println();
}

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 view_grantable_roles(full_resource_name: str) -> None:
    roles = (
        service.roles()
        .queryGrantableRoles(body={"fullResourceName": full_resource_name})
        .execute()
    )

    for role in roles["roles"]:
        if "title" in role:
            print("Title: " + role["title"])
        print("Name: " + role["name"])
        if "description" in role:
            print("Description: " + role["description"])
        print(" ")

What's next

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