Create a custom role

Demonstrates creating a custom 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& parent, std::string const& role_id,
   std::vector<std::string> const& included_permissions) {
  iam::IAMClient client(iam::MakeIAMConnection());
  google::iam::admin::v1::CreateRoleRequest request;
  request.set_parent("projects/" + parent);
  request.set_role_id(role_id);
  google::iam::admin::v1::Role role;
  role.set_stage(google::iam::admin::v1::Role::GA);
  for (auto const& permission : included_permissions) {
    *role.add_included_permissions() = permission;
  }
  *request.mutable_role() = role;
  auto response = client.CreateRole(request);
  if (!response) throw std::move(response).status();
  std::cout << "Role successfully created: " << 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 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 Role CreateRole(string name, string projectId, string title,
        string description, IList<string> permissions, string stage)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var role = new Role
        {
            Title = title,
            Description = description,
            IncludedPermissions = permissions,
            Stage = stage
        };
        var request = new CreateRoleRequest
        {
            Role = role,
            RoleId = name
        };
        role = service.Projects.Roles.Create(request,
            "projects/" + projectId).Execute();
        Console.WriteLine("Created role: " + role.Name);
        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"
)

// createRole creates a custom role.
func createRole(w io.Writer, projectID, name, title, description, stage string, permissions []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.CreateRoleRequest{
		Role: &iam.Role{
			Title:               title,
			Description:         description,
			IncludedPermissions: permissions,
			Stage:               stage,
		},
		RoleId: name,
	}
	role, err := service.Projects.Roles.Create("projects/"+projectID, request).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.Roles.Create: %w", err)
	}
	fmt.Fprintf(w, "Created role: %v", role.Name)
	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.CreateRoleRequest;
import com.google.iam.admin.v1.Role;
import com.google.iam.admin.v1.Role.RoleLaunchStage;
import java.io.IOException;
import java.util.Arrays;

/** Create role. */
public class CreateRole {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace the variables before running the sample.
    String projectId = "your-project-id";
    String roleId = "a unique identifier (e.g. testViewer)";
    String title = "a title for your role (e.g. IAM Role Viewer)";
    String description = "a description of the role";
    Iterable<String> includedPermissions =
        Arrays.asList("roles/iam.roleViewer", "roles/logging.viewer");

    createRole(projectId, title, description, includedPermissions, roleId);
  }

  public static void createRole(
      String projectId,
      String title,
      String description,
      Iterable<String> includedPermissions,
      String roleId)
      throws IOException {
    Role.Builder roleBuilder =
        Role.newBuilder()
            .setTitle(title)
            .setDescription(description)
            .addAllIncludedPermissions(includedPermissions)
            // See launch stage enums at
            // https://cloud.google.com/iam/docs/reference/rpc/google.iam.admin.v1#rolelaunchstage
            .setStage(RoleLaunchStage.BETA);
    CreateRoleRequest createRoleRequest =
        CreateRoleRequest.newBuilder()
            .setParent("projects/" + projectId)
            .setRoleId(roleId)
            .setRole(roleBuilder)
            .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 result = iamClient.createRole(createRoleRequest);
      System.out.println("Created role: " + result.getName());
    }
  }
}

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 create_role(
    name: str, project: str, title: str, description: str, permissions: str, stage: str
) -> dict:
    """Creates a role."""

    # pylint: disable=no-member
    role = (
        service.projects()
        .roles()
        .create(
            parent="projects/" + project,
            body={
                "roleId": name,
                "role": {
                    "title": title,
                    "description": description,
                    "includedPermissions": permissions,
                    "stage": stage,
                },
            },
        )
        .execute()
    )

    print("Created role: " + role["name"])
    return role

What's next

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