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.

from typing import List, Optional

from google.api_core.exceptions import AlreadyExists, FailedPrecondition
from google.cloud.iam_admin_v1 import CreateRoleRequest, IAMClient, Role


def create_role(
    project_id: str, role_id: str, permissions: List[str], title: Optional[str] = None
) -> Role:
    """
    Creates iam role with given parameters.
    Args:
        project_id: GCP project id
        role_id: id of GCP iam role
        permissions: list of iam permissions to assign to role. f.e ["iam.roles.get", "iam.roles.list"]
        title: title for iam role. role_id will be used in case of None

    Returns: google.cloud.iam_admin_v1.Role object
    """
    client = IAMClient()

    parent = f"projects/{project_id}"

    request = CreateRoleRequest(
        parent=parent,
        role_id=role_id,
        role=Role(title=title, included_permissions=permissions),
    )
    try:
        role = client.create_role(request)
        print(f"Created iam role: {role_id}: {role}")
        return role
    except AlreadyExists:
        print(f"Role with id [{role_id}] already exists, take some actions")
    except FailedPrecondition:
        print(
            f"Role with id [{role_id}] already exists and in deleted state, take some actions"
        )

What's next

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