Create and manage custom roles

This page describes how to create and manage Identity and Access Management (IAM) custom roles. Managing roles includes modifying, disabling, listing, deleting, and undeleting roles.

Before you begin

  • Enable the IAM API.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  • Set up authentication.

    Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    gcloud

    In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

    C#

    To use the .NET samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    For more information, see Set up ADC for a local development environment in the Google Cloud authentication documentation.

    C++

    To use the C++ samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    For more information, see Set up ADC for a local development environment in the Google Cloud authentication documentation.

    Go

    To use the Go samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    For more information, see Set up ADC for a local development environment in the Google Cloud authentication documentation.

    Java

    To use the Java samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    For more information, see Set up ADC for a local development environment in the Google Cloud authentication documentation.

    Python

    To use the Python samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    For more information, see Set up ADC for a local development environment in the Google Cloud authentication documentation.

    REST

    To use the REST API samples on this page in a local development environment, you use the credentials you provide to the gcloud CLI.

      Install the Google Cloud CLI.

      If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    For more information, see Authenticate for using REST in the Google Cloud authentication documentation.

  • Understand the Google Cloud resource hierarchy.

  • Read Understanding IAM custom roles.

Required roles

To get the permissions that you need to create and manage custom roles, ask your administrator to grant you the following IAM roles:

  • To manage roles for a project: Role Administrator (roles/iam.roleAdmin) on the project that you want to manage roles for
  • To manage roles for an organization: Organization Role Administrator (roles/iam.organizationRoleAdmin) on the organization that you want to manage roles for

For more information about granting roles, see Manage access to projects, folders, and organizations.

You might also be able to get the required permissions through custom roles or other predefined roles.

View available permissions for projects, folders, and organizations

You can create custom roles for an entire organization, or for a specific project in that organization. The permissions that are available for custom roles depend on where you create the role. For example, if a permission can only be used at the organization level, then you can't include that permission in a project-level custom role.

To check which permissions are available for organization-level and project-level custom roles, you can use the gcloud CLI or the Identity and Access Management API to list the permissions that are available in a specific organization or project. For example, you can get all permissions that are available for custom roles that are created in your project.

Some permissions might not be visible to you or usable in a custom role, even if they are supported in custom roles. For example, a permission might not be available for use in custom roles if you have not enabled the API for the service.

To learn more about the permissions that you can add to custom roles, see Supported permissions.

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. Use the gcloud iam list-testable-permissions command to get a list of permissions that are available for custom roles in a specific project or organization. The response lists the permissions that you can use in custom roles for that project or organization.

    To list permissions that are available in custom roles for a project or organization, run this command:

    gcloud iam list-testable-permissions FULL_RESOURCE_NAME \
        --filter="customRolesSupportLevel!=NOT_SUPPORTED"

    Replace FULL_RESOURCE_NAME with one of the following values:

    • Project: //cloudresourcemanager.googleapis.com/projects/PROJECT_ID (for example, //cloudresourcemanager.googleapis.com/projects/my-project)

    • Organization: //cloudresourcemanager.googleapis.com/organizations/NUMERIC_ID (for example, //cloudresourcemanager.googleapis.com/organizations/123456789012)

    The results indicate whether each permission is supported in custom roles. Permissions that do not have a customRolesSupportLevel field are fully supported.

    The list-testable-permissions command might return hundreds of results. This partial example shows the format of each result:

    ---
    name: appengine.applications.create
    stage: GA
    ---
    customRolesSupportLevel: TESTING
    name: appengine.applications.disable
    stage: GA
    ---
    name: appengine.applications.get
    stage: GA
    ---
    name: appengine.applications.update
    stage: GA
    ---
    name: appengine.instances.delete
    stage: GA
    ---
    name: appengine.instances.get
    stage: GA
    ---
    

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 Before you begin.

namespace iam = ::google::cloud::iam_admin_v1;
[](std::string const& resource) {
  iam::IAMClient client(iam::MakeIAMConnection());
  google::iam::admin::v1::QueryTestablePermissionsRequest request;
  request.set_full_resource_name(resource);
  int count = 0;
  for (auto& permission : client.QueryTestablePermissions(request)) {
    if (!permission) throw std::move(permission).status();
    std::cout << "Permission successfully retrieved: " << permission->name()
              << "\n";
    ++count;
  }
  if (count == 0) {
    std::cout << "No testable permissions 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 Before you begin.


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<Permission> QueryTestablePermissions(
        string fullResourceName)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var request = new QueryTestablePermissionsRequest
        {
            FullResourceName = fullResourceName
        };
        var response = service.Permissions.QueryTestablePermissions(request)
            .Execute();
        foreach (var p in response.Permissions)
        {
            Console.WriteLine(p.Name);
        }
        return response.Permissions;
    }
}

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 Before you begin.

import (
	"context"
	"fmt"
	"io"

	iam "google.golang.org/api/iam/v1"
)

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

	request := &iam.QueryTestablePermissionsRequest{
		FullResourceName: fullResourceName,
	}
	response, err := service.Permissions.QueryTestablePermissions(request).Do()
	if err != nil {
		return nil, fmt.Errorf("Permissions.QueryTestablePermissions: %w", err)
	}
	for _, p := range response.Permissions {
		fmt.Fprintf(w, "Found permissions: %v", p.Name)
	}
	return response.Permissions, 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 Before you begin.


import com.google.cloud.iam.admin.v1.IAMClient;
import com.google.cloud.iam.admin.v1.IAMClient.QueryTestablePermissionsPagedResponse;
import com.google.iam.admin.v1.QueryTestablePermissionsRequest;
import java.io.IOException;

/** View available permissions in a project. */
public class QueryTestablePermissions {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace the variable before running the sample.
    // Full resource names can take one of the following forms:
    // cloudresourcemanager.googleapis.com/projects/PROJECT_ID
    // cloudresourcemanager.googleapis.com/organizations/NUMERIC_ID
    String fullResourceName = "your-full-resource-name";

    queryTestablePermissions(fullResourceName);
  }

  public static void queryTestablePermissions(String fullResourceName) throws IOException {
    QueryTestablePermissionsRequest queryTestablePermissionsRequest =
        QueryTestablePermissionsRequest.newBuilder().setFullResourceName(fullResourceName).build();

    try (IAMClient iamClient = IAMClient.create()) {
      QueryTestablePermissionsPagedResponse queryTestablePermissionsPagedResponse =
          iamClient.queryTestablePermissions(queryTestablePermissionsRequest);
      queryTestablePermissionsPagedResponse
          .iterateAll()
          .forEach(permission -> System.out.println(permission.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 Before you begin.

import os
from typing import List

from google.cloud import resourcemanager_v3
from google.iam.v1 import iam_policy_pb2, policy_pb2


def query_testable_permissions(
    project_id: str, permissions: List[str]
) -> policy_pb2.Policy:
    """Tests IAM permissions of the caller.

    project_id: ID or number of the Google Cloud project you want to use.
    permissions: List of permissions to get.
    """

    client = resourcemanager_v3.ProjectsClient()
    request = iam_policy_pb2.TestIamPermissionsRequest()
    request.resource = f"projects/{project_id}"
    request.permissions.extend(permissions)

    permissions_reponse = client.test_iam_permissions(request)
    print(permissions_reponse)
    return permissions_reponse.permissions

REST

The permissions.queryTestablePermissions method lists permissions available in an organization or project.

Before using any of the request data, make the following replacements:

  • FULL_RESOURCE_NAME: A URI consisting of the service name and the path to the resource. For examples, see Full resource names.
  • PAGE_SIZE: Optional. The number of permissions to include in the response. The default value is 100, and the maximum value is 1,000. If the number of permissions is greater than the page size, the response contains a pagination token that you can use to retrieve the next page of results.
  • NEXT_PAGE_TOKEN: Optional. The pagination token returned in an earlier response from this method. If specified, the list of testable permissions will start where the previous response ended.

HTTP method and URL:

POST https://iam.googleapis.com/v1/permissions:queryTestablePermissions

Request JSON body:

{
  "fullResourceName": "FULL_RESOURCE_NAME"
  "pageSize": PAGE_SIZE,
  "pageToken": "NEXT_PAGE_TOKEN"
}

To send your request, expand one of these options:

The response contains the list of permissions.

{
  "permissions": [
    {
      "name": "iam.serviceAccountKeys.create",
      "stage": "GA"
    },
    {
      "name": "iam.serviceAccountKeys.delete",
      "stage": "GA"
    },
    {
      "name": "iam.serviceAccountKeys.get",
      "stage": "GA"
    }
  ],
  "nextPageToken": "CgoHBajEfjUDQyABEPaIv5vIiMDTVhgDIhtpYW0uc2VydmljZUFjY291bnRLZXlzLmxpc3Q"
}

Get the role metadata

Before you create a custom role, you might want to get the metadata for both predefined and custom roles. Role metadata includes the role ID and permissions contained in the role. You can view the metadata using the Google Cloud console or the IAM API.

To view the role metadata, use one of the methods below:

Console

  1. In the Google Cloud console go to the Roles page.

    Go to the Roles page

  2. Select your organization or project from the drop-down list at the top of the page.

  3. Click the tab for the type of role that you want to view metadata for:

    • To view metadata for predefined roles, stay on the Predefined tab.
    • To view metadata for custom roles, click the Custom tab.
  4. To view the role permissions, select the checkbox for the roles whose permissions you want to view, then click Details. The panel displays the permissions contained in the roles.

If you want to find all the roles that include a specific permission, type the permission name in the Filter box at the top of the list of roles.

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. Use the gcloud iam roles describe command to view metadata for predefined roles and custom roles.

    To view the metadata for a predefined role, execute the following command:

    gcloud iam roles describe ROLE_ID

    ROLE_ID is the ID of the role. Predefined roles include the role prefix in their IDs, for example, roles/iam.roleViewer.

    The following example demonstrates the output of the describe command when executed on the predefined role roles/iam.roleViewer:

    gcloud iam roles describe roles/iam.roleViewer

    description: Read access to all custom roles in the project.
    etag: AA==
    includedPermissions:
    - iam.roles.get
    - iam.roles.list
    - resourcemanager.projects.get
    - resourcemanager.projects.getIamPolicy
    name: roles/iam.roleViewer
    stage: GA
    title: Role Viewer

    To view the metadata for a custom role, execute one of the following commands:

    • To view the metadata for a custom role created at the organization level, execute the following command:

      gcloud iam roles describe --organization=ORGANIZATION_ID ROLE_ID
    • To view the metadata for a custom role created at the project level, execute the following command:

      gcloud iam roles describe --project=PROJECT_ID ROLE_ID

    Each placeholder value is described below:

    • ORGANIZATION_ID is the numeric ID of the organization, such as 123456789012.

    • PROJECT_ID is the name of the project, such as my-project.

    • ROLE_ID is the ID of the role, excluding any prefixes like projects/, organizations/, or roles/. For example, myCompanyAdmin.

    For more information, see the reference documentation for gcloud iam roles describe.

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 Before you begin.

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 Before you begin.


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 Before you begin.

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 Before you begin.


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 Before you begin.

from google.api_core.exceptions import NotFound
from google.cloud.iam_admin_v1 import GetRoleRequest, IAMClient, Role


def get_role(project_id: str, role_id: str) -> Role:
    client = IAMClient()
    name = f"projects/{project_id}/roles/{role_id}"
    request = GetRoleRequest(name=name)
    try:
        role = client.get_role(request)
        print(f"Retrieved role: {role_id}: {role}")
        return role
    except NotFound as exc:
        raise NotFound(f"Role with id [{role_id}] not found, take some actions") from exc

REST

The roles.get method gets the definition of a role.

Before using any of the request data, make the following replacements:

  • ROLE_NAME: The full role name, including any organizations/, projects/, or roles/ prefixes. For example, organizations/123456789012/roles/myCompanyAdmin.

HTTP method and URL:

GET https://iam.googleapis.com/v1/ROLE_NAME

To send your request, expand one of these options:

The response contains the role definition.

{
  "name": "projects/my-project/roles/customRole",
  "title": "My Custom Role",
  "description": "My custom role description.",
  "includedPermissions": [
    "storage.buckets.get",
    "storage.buckets.list"
  ],
  "etag": "BwWiPg2fmDE="
}

Create a custom role

You can create a custom role at the project or organization level.

An organization-level custom role can include any of the IAM permissions that are supported in custom roles. A project-level custom role can contain any supported permission except for permissions that can only be used at the organization or folder level, such as resourcemanager.organizations.get. If you try to add these permissions to a project-level custom role, you see an error message:

Console

The following warning message is displayed: "Not applicable for project-level custom roles". The permission will be automatically unselected from the list of included permissions, and you can proceed with creating the role.

gcloud

The following error message is returned: INVALID_ARGUMENT: Permission PERMISSION is not valid. The custom role will not be created until you first remove the permission from the role definition and try the operation again.

REST API

The following error message is returned: Permission PERMISSION is not valid, along with an HTTP 400 error code and a status of INVALID_ARGUMENT. The custom role will not be created until you first remove the permission from the role definition and try the operation again.

Each custom role can contain up to 3,000 permissions. Also, the maximum total size of the title, description, and permission names for a custom role is 64 KB. If you need to create a larger custom role, you can split the permissions across multiple custom roles. Choose role titles that show the relationship between the custom roles, such as Custom Admin (1 of 2) and Custom Admin (2 of 2).

Each custom role can have a launch stage. Most launch stages are informational, and help you keep track of whether each role is ready for widespread use. Additionally, the DISABLED launch stage lets you disable a custom role. For more information about launch stages, see Testing and deploying.

Console

Some predefined roles contain deprecated permissions or permissions that are otherwise not permitted in custom roles. If you try to create a custom role based on one of these predefined roles, the custom role will omit the deprecated and restricted permissions.

To create a new custom role from scratch, do the following:

  1. In the Google Cloud console, go to the Roles page.

    Go to the Roles page

  2. Using the drop-down list at the top of the page, select the organization or project in which you want to create a role.

  3. Click Create custom role.

  4. Enter a Title, Description, ID, and Role launch stage for the role. The role ID cannot be changed after the role is created.

  5. Click Add Permissions.

  6. Select the permissions you want to include in the role and click Add Permissions. Use the All Services and All Types drop-down lists to filter and select permissions by services and types.

To create a custom role based on an existing predefined role, do the following:

  1. In the Google Cloud console, go to the Roles page.

    Go to the Roles page

  2. Select the organization or project in which you want to create a role.

  3. Select the checkbox for the roles that you want to base the new custom role on.

  4. Click Create custom role from selection.

  5. Enter a Title, Description, ID, and Role launch stage for the role. The role ID cannot be changed after the role is created.

  6. Uncheck the permissions you want to exclude from the role.

  7. Click Add Permissions to include any permissions.

  8. Click Create.

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. Use the gcloud iam roles create command to create new custom roles. You can use this command in two ways:

    • By providing a YAML file that contains the role definition

    • By using flags to specify the role definition

    When creating a custom role, you must specify whether it applies to the organization level or project level by using the --organization=ORGANIZATION_ID or --project=PROJECT_ID flags. Each example below creates a custom role at the project level.

    A custom role can contain only permissions that are supported in custom roles. If the custom role contains other permissions, the command fails.

    To create a custom role using a YAML file:

    Create a YAML file that contains the definition for your custom role. The file must be structured in the following way:

    title: ROLE_TITLE
    description: ROLE_DESCRIPTION
    stage: LAUNCH_STAGE
    includedPermissions:
    - PERMISSION_1
    - PERMISSION_2

    Each placeholder value is described below:

    • ROLE_TITLE is a friendly title for the role, such as "My Company Admin".

    • ROLE_DESCRIPTION is a short description of the role, such as "My custom role description".

    • LAUNCH_STAGE indicates the stage of a role in the launch lifecycle, such as ALPHA, BETA, or GA.

    • PERMISSION_1 and PERMISSION_2 are permissions to include in the custom role, such as iam.roles.get. You can't use wildcard characters (*) in permission names.

    Save the YAML file, and then execute one of the following commands:

    • To create a custom role at the organization level, execute the following command:

      gcloud iam roles create ROLE_ID--organization=ORGANIZATION_ID \
          --file=YAML_FILE_PATH
    • To create a custom role at the project level, execute the following command:

      gcloud iam roles create ROLE_ID --project=PROJECT_ID \
          --file=YAML_FILE_PATH

    Each placeholder value is described below:

    • ROLE_ID is the name of the role, such as myCompanyAdmin.

    • ORGANIZATION_ID is the numeric ID of the organization, such as 123456789012.

    • PROJECT_ID is the name of the project, such as my-project.

    • YAML_FILE_PATH is the path to the location of your YAML file that contains the custom role definition.

    Examples

    The following example YAML file demonstrates how to create a role definition:

    title: "My Company Admin"
    description: "My custom role description."
    stage: "ALPHA"
    includedPermissions:
    - iam.roles.get
    - iam.roles.list

    The following example demonstrates how to create a role at the organization level using the YAML file:

    gcloud iam roles create myCompanyAdmin --organization=123456789012 \
        --file=my-role-definition.yaml

    If the role was created successfully, the command's output is similar to the following:

    Created role [myCompanyAdmin].
    description: My custom role description.
    etag: BwVkBX0sQD0=
    includedPermissions:
    - iam.roles.get
    - iam.roles.list
    name: organizations/123456789012/roles/myCompanyAdmin
    stage: ALPHA
    title: My Company Admin

    The following example demonstrates how to create a role at the project level using the YAML file:

    gcloud iam roles create myCompanyAdmin --project=my-project \
        --file=my-role-definition.yaml

    If the role was created successfully, the command's output is similar to the following:

    Created role [myCompanyAdmin].
    description: My custom role description.
    etag: BwVkBX0sQD0=
    includedPermissions:
    - iam.roles.get
    - iam.roles.list
    name: projects/my-project/roles/myCompanyAdmin
    stage: ALPHA
    title: My Company Admin

    To create a custom role using flags:

    Execute one of the following commands:

    • To create a custom role at the organization level, execute the following command:

      gcloud iam roles create ROLE_ID--organization=ORGANIZATION_ID \
          --title=ROLE_TITLE --description=ROLE_DESCRIPTION \
          --permissions="PERMISSIONS_LIST" --stage=LAUNCH_STAGE
    • To create a custom role at the project level, execute the following command:

      gcloud iam roles create ROLE_ID --project=PROJECT_ID \
          --title=ROLE_TITLE --description=ROLE_DESCRIPTION \
          --permissions="PERMISSIONS_LIST" --stage=LAUNCH_STAGE

    Each placeholder value is described below:

    • ROLE_ID is the name of the role, such as myCompanyAdmin.

    • ORGANIZATION_ID is the numeric ID of the organization, such as 123456789012.

    • PROJECT_ID is the name of the project, such as my-project.

    • ROLE_TITLE is a friendly title for the role, such as "My Company Admin".

    • ROLE_DESCRIPTION is a short description of the role, such as "My custom role description.".

    • PERMISSIONS_LIST contains a comma-separated list of permissions you want to include in the custom role. For example: iam.roles.get,iam.roles.list. You can't use wildcard characters (*) in permission names.

    • LAUNCH_STAGE indicates the stage of a role in the launch lifecycle, such as ALPHA, BETA, or GA.

    Examples

    The following example demonstrates how to create a role at the organization level using flags:

    gcloud iam roles create myCompanyAdmin --organization=123456789012 \
        --title="My Company Admin" --description="My custom role description." \
        --permissions="iam.roles.get,iam.roles.list" --stage=ALPHA

    If the role was created successfully, the command's output is similar to the following:

    Created role [myCompanyAdmin].
    description: My custom role description.
    etag: BwVkBX0sQD0=
    includedPermissions:
    - iam.roles.get
    - iam.roles.list
    name: organizations/123456789012/roles/myCompanyAdmin
    stage: ALPHA
    title: My Company Admin

    The following example demonstrates how to create a role at the project level using flags:

    gcloud iam roles create myCompanyAdmin --project=my-project \
        --title="My Company Admin" --description="My custom role description." \
        --permissions="iam.roles.get,iam.roles.list" --stage=ALPHA

    If the role was created successfully, the command's output is similar to the following:

    Created role [myCompanyAdmin].
    description: My custom role description.
    etag: BwVkBX0sQD0=
    includedPermissions:
    - iam.roles.get
    - iam.roles.list
    name: projects/my-project/roles/myCompanyAdmin
    stage: ALPHA
    title: My Company Admin

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 Before you begin.

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 Before you begin.


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 Before you begin.

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 Before you begin.


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[]