Create and manage custom roles Stay organized with collections Save and categorize content based on your preferences.
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 Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission.Learn how to grant roles.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.
At the bottom of the Google Cloud console, aCloud 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.
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.
If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
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.
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.
If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
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.
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.
If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
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.
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.
If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
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.
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.
If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
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, seeAuthenticate for using REST in the Google Cloud authentication documentation.
Understand the Google Cloudresource hierarchy.
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, seeManage access to projects, folders, and organizations.
You might also be able to get the required permissions throughcustom roles or otherpredefined roles.
View available permissions for projects, folders, and organizations
You can create custom roles for an entire organization, or for a specificproject in that organization. The permissions that are available for customroles depend on where you create the role. For example, if a permission can onlybe used at the organization level, then you can't include that permission in aproject-level custom role.
To check which permissions are available for organization-level andproject-level custom roles, you can use the gcloud CLI or theIdentity and Access Management API to list the permissions that are available in a specificorganization or project. For example, you can get all permissions that areavailable 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 supportedin custom roles. For example, a permission might not be available for use in custom roles if youhave notenabled the API for the service.
To learn more about the permissions that you can add to custom roles, seeSupported permissions.
gcloud
In the Google Cloud console, activate Cloud Shell.
At the bottom of the Google Cloud console, aCloud 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.
Use the
gcloud iam list-testable-permissionscommand 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-permissionsFULL_RESOURCE_NAME \ --filter="customRolesSupportLevel!=NOT_SUPPORTED"
Replace
FULL_RESOURCE_NAMEwith 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
customRolesSupportLevelfield are fully supported.The
list-testable-permissionscommand might return hundreds of results. This partial example shows the format of each result:---name: appengine.applications.createstage: GA---customRolesSupportLevel: TESTINGname: appengine.applications.disablestage: GA---name: appengine.applications.getstage: GA---name: appengine.applications.updatestage: GA---name: appengine.instances.deletestage: GA---name: appengine.instances.getstage: GA---
C++
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMC++ API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
namespaceiam=::google::cloud::iam_admin_v1;[](std::stringconst&resource){iam::IAMClientclient(iam::MakeIAMConnection());google::iam::admin::v1::QueryTestablePermissionsRequestrequest;request.set_full_resource_name(resource);intcount=0;for(auto&permission:client.QueryTestablePermissions(request)){if(!permission)throwstd::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, seeIAM client libraries. For more information, see theIAMC# API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
usingSystem;usingSystem.Collections.Generic;usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Iam.v1;usingGoogle.Apis.Iam.v1.Data;publicpartialclassCustomRoles{publicstaticIList<Permission>QueryTestablePermissions(stringfullResourceName){varcredential=GoogleCredential.GetApplicationDefault().CreateScoped(IamService.Scope.CloudPlatform);varservice=newIamService(newIamService.Initializer{HttpClientInitializer=credential});varrequest=newQueryTestablePermissionsRequest{FullResourceName=fullResourceName};varresponse=service.Permissions.QueryTestablePermissions(request).Execute();foreach(varpinresponse.Permissions){Console.WriteLine(p.Name);}returnresponse.Permissions;}}Go
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMGo API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
import("context""fmt""io"iam"google.golang.org/api/iam/v1")// queryTestablePermissions lists testable permissions on a resource.funcqueryTestablePermissions(wio.Writer,fullResourceNamestring)([]*iam.Permission,error){ctx:=context.Background()service,err:=iam.NewService(ctx)iferr!=nil{returnnil,fmt.Errorf("iam.NewService: %w",err)}request:=&iam.QueryTestablePermissionsRequest{FullResourceName:fullResourceName,}response,err:=service.Permissions.QueryTestablePermissions(request).Do()iferr!=nil{returnnil,fmt.Errorf("Permissions.QueryTestablePermissions: %w",err)}for_,p:=rangeresponse.Permissions{fmt.Fprintf(w,"Found permissions: %v",p.Name)}returnresponse.Permissions,nil}Java
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMJava API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
importcom.google.cloud.iam.admin.v1.IAMClient;importcom.google.cloud.iam.admin.v1.IAMClient.QueryTestablePermissionsPagedResponse;importcom.google.iam.admin.v1.QueryTestablePermissionsRequest;importjava.io.IOException;/** View available permissions in a project. */publicclassQueryTestablePermissions{publicstaticvoidmain(String[]args)throwsIOException{// 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_IDStringfullResourceName="your-full-resource-name";queryTestablePermissions(fullResourceName);}publicstaticvoidqueryTestablePermissions(StringfullResourceName)throwsIOException{QueryTestablePermissionsRequestqueryTestablePermissionsRequest=QueryTestablePermissionsRequest.newBuilder().setFullResourceName(fullResourceName).build();try(IAMClientiamClient=IAMClient.create()){QueryTestablePermissionsPagedResponsequeryTestablePermissionsPagedResponse=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, seeIAM client libraries. For more information, see theIAMPython API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
importosfromtypingimportListfromgoogle.cloudimportresourcemanager_v3fromgoogle.iam.v1importiam_policy_pb2,policy_pb2defquery_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)returnpermissions_reponse.permissionsREST
Thepermissions.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 ofthe service name and the path to the resource. For examples, seeFull 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:
curl (Linux, macOS, or Cloud Shell)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://iam.googleapis.com/v1/permissions:queryTestablePermissions"
PowerShell (Windows)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://iam.googleapis.com/v1/permissions:queryTestablePermissions" | Select-Object -Expand Content
APIs Explorer (browser)
Copy the request body and open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Paste the request body in this tool, complete any other required fields, and clickExecute.
The response contains the list of permissions.
Note: Permissions that do not have acustomRolesSupportLevel field are fully supported in custom roles.{ "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 bothpredefined and custom roles. Role metadata includes the role ID and permissionscontained in the role. You can view the metadata using theGoogle Cloud console or the IAM API.
To view the role metadata, use one of the methods below:
Console
In the Google Cloud console, go to theRoles page.
Select your organization or project from the drop-down list at the top ofthe page.
Select the checkbox for one or more roles to view the role permissions.The right side panel displays the permissions contained in the role(s),if any.
The icons in theType column indicate if it's a custom role or a predefined role
![]()
![]()
If you want to find all the roles that include a specific permission, typethe permission name in theFilter box at the top of the Roles list.
gcloud
In the Google Cloud console, activate Cloud Shell.
At the bottom of the Google Cloud console, aCloud 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.
Use the
gcloud iam roles describecommand to view metadata for predefined roles and custom roles.To view the metadata for a predefined role, execute the following command:
gcloud iam roles describeROLE_ID
ROLE_IDis the ID of the role. Predefined roles include theroleprefix in their IDs, for example,roles/iam.roleViewer.The following example demonstrates the output of the
describecommand when executed on the predefined roleroles/iam.roleViewer:gcloud iam roles describe roles/iam.roleViewerdescription:Read access to all custom roles in the project.etag:AA==includedPermissions:-iam.roles.get-iam.roles.list-resourcemanager.projects.get-resourcemanager.projects.getIamPolicyname:roles/iam.roleViewerstage:GAtitle: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_IDROLE_ID
To view the metadata for a custom role created at the project level, execute the following command:
gcloud iam roles describe --project=PROJECT_IDROLE_ID
Each placeholder value is described below:
ORGANIZATION_IDis the numeric ID of the organization, such as123456789012.PROJECT_IDis the name of the project, such asmy-project.ROLE_IDis the ID of the role, excluding any prefixes likeprojects/,organizations/, orroles/. 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, seeIAM client libraries. For more information, see theIAMC++ API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
namespaceiam=::google::cloud::iam_admin_v1;[](std::stringconst&name){iam::IAMClientclient(iam::MakeIAMConnection());google::iam::admin::v1::GetRoleRequestrequest;request.set_name(name);autoresponse=client.GetRole(request);if(!response)throwstd::move(response).status();std::cout <<"Role successfully retrieved: " <<response->DebugString() <<"\n";}C#
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMC# API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
usingSystem;usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Iam.v1;usingGoogle.Apis.Iam.v1.Data;publicpartialclassCustomRoles{publicstaticRoleGetRole(stringname){varcredential=GoogleCredential.GetApplicationDefault().CreateScoped(IamService.Scope.CloudPlatform);varservice=newIamService(newIamService.Initializer{HttpClientInitializer=credential});varrole=service.Roles.Get(name).Execute();Console.WriteLine(role.Name);Console.WriteLine(String.Join(", ",role.IncludedPermissions));returnrole;}}Go
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMGo API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
import("context""fmt""io"iam"google.golang.org/api/iam/v1")// getRole gets role metadata.funcgetRole(wio.Writer,namestring)(*iam.Role,error){ctx:=context.Background()service,err:=iam.NewService(ctx)iferr!=nil{returnnil,fmt.Errorf("iam.NewService: %w",err)}role,err:=service.Roles.Get(name).Do()iferr!=nil{returnnil,fmt.Errorf("Roles.Get: %w",err)}fmt.Fprintf(w,"Got role: %v\n",role.Name)for_,permission:=rangerole.IncludedPermissions{fmt.Fprintf(w,"Got permission: %v\n",permission)}returnrole,nil}Java
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMJava API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
importcom.google.cloud.iam.admin.v1.IAMClient;importcom.google.iam.admin.v1.GetRoleRequest;importcom.google.iam.admin.v1.Role;importjava.io.IOException;/** Get role metadata. Specifically, printing out role permissions. */publicclassGetRole{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace the variable before running the sample.StringroleId="a unique identifier (e.g. testViewer)";getRole(roleId);}publicstaticvoidgetRole(StringroleId)throwsIOException{GetRoleRequestgetRoleRequest=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(IAMClientiamClient=IAMClient.create()){Rolerole=iamClient.getRole(getRoleRequest);role.getIncludedPermissionsList().forEach(permission->System.out.println(permission));}}}Python
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMPython API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
fromgoogle.api_core.exceptionsimportNotFoundfromgoogle.cloud.iam_admin_v1importGetRoleRequest,IAMClient,Roledefget_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}")returnroleexceptNotFoundasexc:raiseNotFound(f"Role with id [{role_id}] not found, take some actions")fromexcREST
Theroles.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 anyorganizations/,projects/, orroles/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:
curl (Linux, macOS, or Cloud Shell)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.Execute the following command:
curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://iam.googleapis.com/v1/ROLE_NAME"
PowerShell (Windows)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.Execute the following command:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://iam.googleapis.com/v1/ROLE_NAME" | Select-Object -Expand Content
APIs Explorer (browser)
Open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Complete any required fields and clickExecute.
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 IAMpermissions that are supported in customroles. A project-level custom role cancontain any supported permissionexcept for permissions that can only be usedat the organization or folder level, such asresourcemanager.organizations.get. If you try to add these permissions to aproject-level custom role, you see an error message:
Console
The following warning message is displayed:"Not applicable for project-level custom roles". Thepermission will be automatically unselected from the list of includedpermissions, and you can proceed with creating the role.
gcloud
The following error messageis returned:INVALID_ARGUMENT: PermissionPERMISSION is notvalid. The custom role will not be created until you first remove thepermission from the role definition and trythe operation again.
REST API
The following error message is returned:PermissionPERMISSION is not valid, along with anHTTP 400 error code and a status ofINVALID_ARGUMENT. The custom role willnot be created until you first remove the permission from the roledefinition and try the operation again.
Each custom role can contain up to 3,000permissions. Also, the maximum total size of the title, description, andpermission names for a custom role is 64 KB. If youneed to create a larger custom role, you can split the permissions acrossmultiple custom roles. Choose role titles that show the relationship between thecustom roles, such asCustom Admin (1 of 2) andCustom 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, theDISABLED launch stage lets youdisable a customrole. For more information about launch stages, seeTesting and deploying.
Console
Some predefined roles contain deprecated permissions or permissions that areotherwise not permitted in custom roles. If you try to create a custom rolebased on one of these predefined roles, the custom role will omit the deprecatedand restricted permissions.
To create a new custom role from scratch:
In the Google Cloud console, go to theRoles page.
Using the drop-down list at the top of the page, select the organization orproject in which you want to create a role.
ClickCreate Role.
Enter aTitle,Description,ID, andRole launch stagefor the role. The role ID cannot be changed after the role is created.
ClickAdd Permissions.
Select the permissions you want to include in the role and clickAddPermissions. Use theAll Services andAll Types drop-down lists tofilter and select permissions by services and types.
Creating a custom role based on an existing predefined role:
- In the Google Cloud console, go to theRoles page.
- Select the organization or project in which you want to create a role.
- Select the roles on which you want to base the new custom role.
- ClickCreate Role from Selection.
- Enter aTitle,Description,ID, andRole launch stagefor the role. The role ID cannot be changed after the role is created.
- Uncheck the permissions you want to exclude from the role.
- ClickAdd Permissions to include any permissions.
- ClickCreate.
gcloud
In the Google Cloud console, activate Cloud Shell.
At the bottom of the Google Cloud console, aCloud 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.
Use the
gcloud iam roles createcommand 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_IDor--project=PROJECT_IDflags. Each example below creates a custom role at the project level.A custom role can contain onlypermissions 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_TITLEdescription:ROLE_DESCRIPTIONstage:LAUNCH_STAGEincludedPermissions:-PERMISSION_1-PERMISSION_2
Each placeholder value is described below:
ROLE_TITLEis a friendly title for the role, such as"My Company Admin".ROLE_DESCRIPTIONis a short description of the role, such as"My custom role description".LAUNCH_STAGEindicates the stage of a role in the launch lifecycle, such asALPHA,BETA, orGA.PERMISSION_1andPERMISSION_2are permissions to include in the custom role, such asiam.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 createROLE_ID--organization=ORGANIZATION_ID \ --file=YAML_FILE_PATH
To create a custom role at the project level, execute the following command:
gcloud iam roles createROLE_ID --project=PROJECT_ID \ --file=YAML_FILE_PATH
Each placeholder value is described below:
ROLE_IDis the name of the role, such asmyCompanyAdmin.ORGANIZATION_IDis the numeric ID of the organization, such as123456789012.PROJECT_IDis the name of the project, such asmy-project.YAML_FILE_PATHis 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:"MyCompanyAdmin"description:"Mycustomroledescription."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.listname:organizations/123456789012/roles/myCompanyAdminstage:ALPHAtitle: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.listname:projects/my-project/roles/myCompanyAdminstage:ALPHAtitle: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 createROLE_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 createROLE_ID --project=PROJECT_ID \ --title=ROLE_TITLE --description=ROLE_DESCRIPTION \ --permissions="PERMISSIONS_LIST" --stage=LAUNCH_STAGE
Each placeholder value is described below:
ROLE_IDis the name of the role, such asmyCompanyAdmin.ORGANIZATION_IDis the numeric ID of the organization, such as123456789012.PROJECT_IDis the name of the project, such asmy-project.ROLE_TITLEis a friendly title for the role, such as"My Company Admin".ROLE_DESCRIPTIONis a short description of the role, such as"My custom role description.".PERMISSIONS_LISTcontains 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_STAGEindicates the stage of a role in the launch lifecycle, such asALPHA,BETA, orGA.
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.listname:organizations/123456789012/roles/myCompanyAdminstage:ALPHAtitle: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.listname:projects/my-project/roles/myCompanyAdminstage:ALPHAtitle:My Company Admin
C++
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMC++ API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
namespaceiam=::google::cloud::iam_admin_v1;[](std::stringconst&parent,std::stringconst&role_id,std::vector<std::string>const&included_permissions){iam::IAMClientclient(iam::MakeIAMConnection());google::iam::admin::v1::CreateRoleRequestrequest;request.set_parent("projects/"+parent);request.set_role_id(role_id);google::iam::admin::v1::Rolerole;role.set_stage(google::iam::admin::v1::Role::GA);for(autoconst&permission:included_permissions){*role.add_included_permissions()=permission;}*request.mutable_role()=role;autoresponse=client.CreateRole(request);if(!response)throwstd::move(response).status();std::cout <<"Role successfully created: " <<response->DebugString() <<"\n";}C#
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMC# API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
usingSystem;usingSystem.Collections.Generic;usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Iam.v1;usingGoogle.Apis.Iam.v1.Data;publicpartialclassCustomRoles{publicstaticRoleCreateRole(stringname,stringprojectId,stringtitle,stringdescription,IList<string>permissions,stringstage){varcredential=GoogleCredential.GetApplicationDefault().CreateScoped(IamService.Scope.CloudPlatform);varservice=newIamService(newIamService.Initializer{HttpClientInitializer=credential});varrole=newRole{Title=title,Description=description,IncludedPermissions=permissions,Stage=stage};varrequest=newCreateRoleRequest{Role=role,RoleId=name};role=service.Projects.Roles.Create(request,"projects/"+projectId).Execute();Console.WriteLine("Created role: "+role.Name);returnrole;}}Go
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMGo API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
import("context""fmt""io"iam"google.golang.org/api/iam/v1")// createRole creates a custom role.funccreateRole(wio.Writer,projectID,name,title,description,stagestring,permissions[]string)(*iam.Role,error){ctx:=context.Background()service,err:=iam.NewService(ctx)iferr!=nil{returnnil,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()iferr!=nil{returnnil,fmt.Errorf("Projects.Roles.Create: %w",err)}fmt.Fprintf(w,"Created role: %v",role.Name)returnrole,nil}Java
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMJava API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
importcom.google.cloud.iam.admin.v1.IAMClient;importcom.google.iam.admin.v1.CreateRoleRequest;importcom.google.iam.admin.v1.Role;importcom.google.iam.admin.v1.Role.RoleLaunchStage;importjava.io.IOException;importjava.util.Arrays;/** Create role. */publicclassCreateRole{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace the variables before running the sample.StringprojectId="your-project-id";StringroleId="a unique identifier (e.g. testViewer)";Stringtitle="a title for your role (e.g. IAM Role Viewer)";Stringdescription="a description of the role";Iterable<String>includedPermissions=Arrays.asList("roles/iam.roleViewer","roles/logging.viewer");createRole(projectId,title,description,includedPermissions,roleId);}publicstaticvoidcreateRole(StringprojectId,Stringtitle,Stringdescription,Iterable<String>includedPermissions,StringroleId)throwsIOException{Role.BuilderroleBuilder=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);CreateRoleRequestcreateRoleRequest=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(IAMClientiamClient=IAMClient.create()){Roleresult=iamClient.createRole(createRoleRequest);System.out.println("Created role: "+result.getName());}}}Python
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMPython API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
fromtypingimportList,Optionalfromgoogle.api_core.exceptionsimportAlreadyExists,FailedPreconditionfromgoogle.cloud.iam_admin_v1importCreateRoleRequest,IAMClient,Roledefcreate_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}")returnroleexceptAlreadyExists:print(f"Role with id [{role_id}] already exists, take some actions")exceptFailedPrecondition:print(f"Role with id [{role_id}] already exists and in deleted state, take some actions")REST
Theroles.create method creates a custom role in a project or organization.
Before using any of the request data, make the following replacements:
RESOURCE_TYPE: The resource type whosecustom roles you want to manage. Use the valueprojectsororganizations.RESOURCE_ID: The project ID ororganization ID whose custom roles you want to manage. Project IDs are alphanumeric strings, likemy-project. Organization IDs are numeric, like123456789012.ROLE_ID: The name of the role, such asmyCompanyAdmin.ROLE_TITLE: The human-readable title for therole. For example,My Company Admin.ROLE_DESCRIPTION: A description for therole. For example,"The company admin role allows company admins to access importantresources".PERMISSION_1andPERMISSION_2: The permissions that you want to include in the role. Forexample,storage.objects.update. You can't use wildcard characters (*) inpermission names.A custom role can contain onlypermissions that are supported in custom roles. If the custom role contains other permissions, the request fails.
LAUNCH_STAGE: The current launch stage of therole. This field can contain one of the following values:EAP,ALPHA,BETA,GA,DEPRECATED, orDISABLED.
HTTP method and URL:
POST https://iam.googleapis.com/v1/RESOURCE_TYPE/RESOURCE_ID/roles
Request JSON body:
{ "roleId": "ROLE_ID", "role": { "title": "ROLE_TITLE", "description": "ROLE_DESCRIPTION", "includedPermissions": [ "PERMISSION_1", "PERMISSION_2" ], "stage": "LAUNCH_STAGE" }}To send your request, expand one of these options:
curl (Linux, macOS, or Cloud Shell)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://iam.googleapis.com/v1/RESOURCE_TYPE/RESOURCE_ID/roles"
PowerShell (Windows)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://iam.googleapis.com/v1/RESOURCE_TYPE/RESOURCE_ID/roles" | Select-Object -Expand Content
APIs Explorer (browser)
Copy the request body and open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Paste the request body in this tool, complete any other required fields, and clickExecute.
The response contains the role you created.
{ "name": "projects/myProject/roles/myCompanyAdmin", "title": "My Company Admin", "description": "My custom role description.", "includedPermissions": [ "iam.roles.get", "iam.roles.list" ], "etag": "BwWox/JbaZw="}Edit an existing custom role
A common pattern for updating a resource's metadata, such as a custom role, istheread-modify-write pattern. With this pattern, you read the role's currentstate, update the data locally, and then send the modified data for writing.
The read-modify-write pattern can cause a conflict if two or more independentprocesses attempt the sequence simultaneously. For example, if two owners for aproject try to make conflicting changes to a role at the same time, some changescould fail. IAM solves this problem using anetag property incustom roles. This property is used to verify if the custom role has changedsince the last request. When you make a request to IAM with anetag value, IAM compares the etag value in the request with theexisting etag value associated with the custom role. It writes the change onlyif the etag values match.
When you update a role, first get the role usingroles.get(), update the role,and then write the updated role usingroles.patch(). Use the etag value whensetting the role only if the corresponding role inroles.get() contains anetag value.
resourcemanager.organizations.get,resourcemanager.folders.get,andresourcemanager.projects.get, the change to the custom role can require upto 24 hours to take effect for theorganizations.search andfolders.searchCloud Resource Manager APIs. The APIprojects.list is also subject to thisdelay for API calls that do not provide a filter specifying a parent type andID. This delay occurs because these permissions involve search functionality,and it can take up to 24 hours between rebuilds of the search index.Console
In the Google Cloud console, go to theRoles page.
Using the drop-down list at the top of the page, select the project ororganization that contains the role that you want to edit.
Click a custom role.
ClickEdit Role.
To update the role's metadata, edit the role'sTitle,Description,orRole launch stage.
To update the role's permissions, do the following:
- ClickAdd Permissions to add new permissions to the role.
- Uncheck permissions to remove permissions from the role.
ClickUpdate to save the edited role.
gcloud
In the Google Cloud console, activate Cloud Shell.
At the bottom of the Google Cloud console, aCloud 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.
Use the
gcloud iam roles updatecommand to update custom roles. You can use this command in two ways:By providing a YAML file that contains the updated role definition
By using flags to specify the updated role definition
When updating a custom role, you must specify whether it applies to the organization level or project level by using the
--organization=ORGANIZATION_IDor--project=PROJECT_IDflags. Each example below creates a custom role at the project level.To update a custom role using a YAML file:
Get the current definition for the role by executing one of the following commands:
To get the role definition of an organization-level custom role, execute the following command:
gcloud iam roles describeROLE_ID --organization=ORGANIZATION_ID
To get the role definition of a project-level custom role, execute the following command:
gcloud iam roles describeROLE_ID --project=PROJECT_ID
Each placeholder value is described below:
ROLE_IDis the name of the role to update, such asmyCompanyAdmin.ORGANIZATION_IDis the numeric ID of the organization, such as123456789012.PROJECT_IDis the name of the project, such asmy-project.
The
describecommand returns the role's definition and includes anetagvalue that uniquely identifies the current version of the role. Theetagvalue should be provided in the updated role definition to ensure that any concurrent role changes are not overwritten.The
describecommand returns the following output:description:ROLE_DESCRIPTIONetag:ETAGincludedPermissions:-PERMISSION_1-PERMISSION_2name:ROLE_NAMEstage:LAUNCH_STAGEtitle:ROLE_TITLE
Each placeholder value is described below:
ROLE_DESCRIPTIONis a short description of the role, such as"My custom role description".ETAGis the unique identifier for the current version of the role, such asBwVkBkbfr70=.PERMISSION_1andPERMISSION_2are permissions to include in the custom role, such asiam.roles.get. You can't use wildcard characters (*) in permission names.ROLE_NAMEis the full role name, including anyorganizations/,projects/, orroles/prefixes. For example,organizations/123456789012/roles/myCompanyAdmin.LAUNCH_STAGEindicates the stage of a role in the launch lifecycle, such asALPHA,BETA, orGA.ROLE_TITLEis a friendly title for the role, such as"My Company Admin".
To update the role, either include the outputted role definition to a YAML file or update the original YAML file with the outputted
etagvalue.Consider the following example YAML file, which contains the output from the
describecommand for a project-level role and adds two Cloud Storage permissions:description:My custom role description.etag:BwVkBkbfr70=includedPermissions:-iam.roles.get-iam.roles.list-storage.buckets.get-storage.buckets.listname:projects/my-project/roles/myCompanyAdminstage:ALPHAtitle:My Company Admin
Save the YAML file, and then execute one of the following commands:
To update an organization-level role, execute the following command:
gcloud iam roles updateROLE_ID--organization=ORGANIZATION_ID \ --file=YAML_FILE_PATH
To update a project-level role, execute the following command:
gcloud iam roles updateROLE_ID --project=PROJECT_ID \ --file=YAML_FILE_PATH
Each placeholder value is described below:
ROLE_IDis the name of the role to update, such asmyCompanyAdmin.ORGANIZATION_IDis the numeric ID of the organization, such as123456789012.PROJECT_IDis the name of the project, such asmy-project-id.YAML_FILE_PATHis the path to the location of your YAML file that contains the updated custom role definition.
Examples
The following example demonstrates how to update an organization-level role using a YAML file:
gcloud iam roles updateROLE_ID --organization=ORGANIZATION_ID \ --file=YAML_FILE_PATH
To update a project-level role, execute the following command:
gcloud iam roles updateROLE_ID --project=PROJECT_ID \ --file=YAML_FILE_PATH
Each placeholder value is described below:
ROLE_IDis the name of the role to update, such asmyCompanyAdmin.ORGANIZATION_IDis the numeric ID of the organization, such as123456789012.PROJECT_IDis the name of the project, such asmy-project.YAML_FILE_PATHis the path to the location of your YAML file that contains the updated custom role definition.
Examples
The following example demonstrates how to update an organization-level role using a YAML file:
gcloud iam roles update myCompanyAdmin --organization=123456789012 \ --file=my-role-definition.yaml
If the role was updated successfully, the command's output is similar to the following:
description:My custom role description.etag:BwVkBwDN0lg=includedPermissions:-iam.roles.get-iam.roles.list-storage.buckets.get-storage.buckets.listname:organizations/123456789012/roles/myCompanyAdminstage:ALPHAtitle:My Company Admin
The following example demonstrates how to update a project-level role using a YAML file:
gcloud iam roles update myCompanyAdmin --project=my-project \ --file=my-role-definition.yaml
If the role was updated successfully, the command's output is similar to the following:
description:My custom role description.etag:BwVkBwDN0lg=includedPermissions:-iam.roles.get-iam.roles.list-storage.buckets.get-storage.buckets.listname:projects/my-project/roles/myCompanyAdminstage:ALPHAtitle:My Company Admin
To update a custom role using flags:
Each part of a role definition can be updated using a corresponding flag. See the
gcloud iam roles updatetopic for a list of all possible flags.You can use the following flags to add or remove permissions:
--add-permissions=PERMISSIONS: Adds one or more comma-separated permissions to the role. You can't use wildcard characters (*) in permission names.--remove-permissions=PERMISSIONS: Removes one or more comma-separated permissions from the role. You can't use wildcard characters (*) in permission names.
Alternatively, you can simply specify the new permissions using the
--permissions=PERMISSIONSflag and providing a comma-separated list of permissions to replace the existing permissions list.To update other parts of the role definition, execute one of the following commands:
To update an organization-level role, execute the following command:
gcloud iam roles updateROLE_ID--organization=ORGANIZATION_ID \ --title=ROLE_TITLE --description=ROLE_DESCRIPTION \ --stage=LAUNCH_STAGE
To update a project-level role, execute the following command:
gcloud iam roles updateROLE_ID --project=PROJECT_ID \ --title=ROLE_TITLE --description=ROLE_DESCRIPTION \ --stage=LAUNCH_STAGE
Each placeholder value is described below:
ROLE_IDis the name of the role, such asmyCompanyAdmin.ORGANIZATION_IDis the numeric ID of the organization, such as123456789012.PROJECT_IDis the name of the project, such asmy-project.ROLE_TITLEis a friendly title for the role, such as"My Company Admin".ROLE_DESCRIPTIONis a short description of the role, such as"My custom role description.".LAUNCH_STAGEindicates the stage of a role in the launch lifecycle, such asALPHA,BETA, orGA.
Examples
The following example demonstrates how to add permissions to an organization-level role using flags:
gcloud iam roles update myCompanyAdmin --organization=123456789012 \ --add-permissions="storage.buckets.get,storage.buckets.list"
If the role was updated successfully, the command's output is similar to the following:
description:My custom role description.etag:BwVkBwDN0lg=includedPermissions:-iam.roles.get-iam.roles.list-storage.buckets.get-storage.buckets.listname:organizations/123456789012/roles/myCompanyAdminstage:ALPHAtitle:My Company Admin
The following example demonstrates how to add permissions to a project-level role using flags:
gcloud iam roles update myCompanyAdmin --project=my-project \ --add-permissions="storage.buckets.get,storage.buckets.list"
If the role was updated successfully, the command's output is similar to the following:
description:My custom role description.etag:BwVkBwDN0lg=includedPermissions:-iam.roles.get-iam.roles.list-storage.buckets.get-storage.buckets.listname:projects/my-project/roles/myCompanyAdminstage:ALPHAtitle:My Company Admin
C++
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMC++ API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
namespaceiam=::google::cloud::iam_admin_v1;[](std::stringconst&name,std::stringconst&title){iam::IAMClientclient(iam::MakeIAMConnection());google::iam::admin::v1::UpdateRoleRequestrequest;request.set_name(name);google::iam::admin::v1::Rolerole;role.set_title(title);google::protobuf::FieldMaskupdate_mask;*update_mask.add_paths()="title";*request.mutable_role()=role;*request.mutable_update_mask()=update_mask;autoresponse=client.UpdateRole(request);if(!response)throwstd::move(response).status();std::cout <<"Role successfully updated: " <<response->DebugString() <<"\n";}C#
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMC# API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
usingSystem;usingSystem.Collections.Generic;usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Iam.v1;usingGoogle.Apis.Iam.v1.Data;publicpartialclassCustomRoles{publicstaticRoleEditRole(stringname,stringprojectId,stringnewTitle,stringnewDescription,IList<string>newPermissions,stringnewStage){varcredential=GoogleCredential.GetApplicationDefault().CreateScoped(IamService.Scope.CloudPlatform);varservice=newIamService(newIamService.Initializer{HttpClientInitializer=credential});// First, get a Role using List() or Get().stringresource=$"projects/{projectId}/roles/{name}";varrole=service.Projects.Roles.Get(resource).Execute();// Then you can update its fields.role.Title=newTitle;role.Description=newDescription;role.IncludedPermissions=newPermissions;role.Stage=newStage;role=service.Projects.Roles.Patch(role,resource).Execute();Console.WriteLine("Updated role: "+role.Name);returnrole;}}Go
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMGo API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
import("context""fmt""io"iam"google.golang.org/api/iam/v1")// editRole modifies a custom role.funceditRole(wio.Writer,projectID,name,newTitle,newDescription,newStagestring,newPermissions[]string)(*iam.Role,error){ctx:=context.Background()service,err:=iam.NewService(ctx)iferr!=nil{returnnil,fmt.Errorf("iam.NewService: %w",err)}resource:="projects/"+projectID+"/roles/"+namerole,err:=service.Projects.Roles.Get(resource).Do()iferr!=nil{returnnil,fmt.Errorf("Projects.Roles.Get: %w",err)}role.Title=newTitlerole.Description=newDescriptionrole.IncludedPermissions=newPermissionsrole.Stage=newStagerole,err=service.Projects.Roles.Patch(resource,role).Do()iferr!=nil{returnnil,fmt.Errorf("Projects.Roles.Patch: %w",err)}fmt.Fprintf(w,"Updated role: %v",role.Name)returnrole,nil}Java
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMJava API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
importcom.google.cloud.iam.admin.v1.IAMClient;importcom.google.iam.admin.v1.Role;importcom.google.iam.admin.v1.Role.RoleLaunchStage;importcom.google.iam.admin.v1.UpdateRoleRequest;importcom.google.protobuf.FieldMask;importjava.io.IOException;/** Edit role metadata. Specifically, update description and launch stage. */publicclassEditRole{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace the variables before running the sample.// Role ID must point to an existing role.StringprojectId="your-project-id";StringroleId="a unique identifier (e.g. testViewer)";Stringdescription="a new description of the role";editRole(projectId,roleId,description);}publicstaticvoideditRole(StringprojectId,StringroleId,Stringdescription)throwsIOException{StringroleName="projects/"+projectId+"/roles/"+roleId;Role.BuilderroleBuilder=Role.newBuilder().setName(roleName).setDescription(description)// See launch stage enums at// https://cloud.google.com/iam/docs/reference/rpc/google.iam.admin.v1#rolelaunchstage.setStage(RoleLaunchStage.GA);FieldMaskfieldMask=FieldMask.newBuilder().addPaths("description").addPaths("stage").build();UpdateRoleRequestupdateRoleRequest=UpdateRoleRequest.newBuilder().setName(roleName).setRole(roleBuilder).setUpdateMask(fieldMask).build();// Initialize client for sending requests. This client only needs to be created// once, and can be reused for multiple requests.try(IAMClientiamClient=IAMClient.create()){Roleresult=iamClient.updateRole(updateRoleRequest);System.out.println("Edited role:\n"+result);}}}Python
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMPython API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
fromgoogle.api_core.exceptionsimportNotFoundfromgoogle.cloud.iam_admin_v1importIAMClient,Role,UpdateRoleRequestfromsnippets.get_roleimportget_roledefedit_role(role:Role)->Role:"""Edits an existing IAM role in a GCP project. Args: role: google.cloud.iam_admin_v1.Role object to be updated Returns: Updated google.cloud.iam_admin_v1.Role object """client=IAMClient()request=UpdateRoleRequest(name=role.name,role=role)try:role=client.update_role(request)print(f"Edited role:{role.name}:{role}")returnroleexceptNotFound:print(f"Role [{role.name}] not found, take some actions")REST
Theroles.patch method updates a custom role in a project or organization.
Before using any of the request data, make the following replacements:
Required:
RESOURCE_TYPE: The resource type whosecustom roles you want to manage. Use the valueprojectsororganizations.RESOURCE_ID: The project ID ororganization ID whose custom roles you want to manage. Project IDs are alphanumeric strings, likemy-project. Organization IDs are numeric, like123456789012.ROLE_NAME: The full role name, including anyorganizations/,projects/, orroles/prefixes. For example,organizations/123456789012/roles/myCompanyAdmin.
Recommended:
ETAG: An identifier for a version of the role.Include this field to prevent overwriting other role changes.
Optional (define one or more of the following values):
ROLE_TITLE: The human-readable title for therole. For example,My Company Admin.ROLE_DESCRIPTION: A description for therole. For example,"The company admin role allows company admins to access importantresources".PERMISSION_1andPERMISSION_2: The permissions that you want to include in the role. Forexample,storage.objects.update. You can't use wildcard characters (*) inpermission names.LAUNCH_STAGE: The current launch stage of therole. This field can contain one of the following values:EAP,ALPHA,BETA,GA,DEPRECATED, orDISABLED.
HTTP method and URL:
PATCH https://iam.googleapis.com/v1/RESOURCE_TYPE/RESOURCE_ID/roles
Request JSON body:
{ "roleId": "ROLE_NAME", "title": "ROLE_TITLE", "description": "ROLE_DESCRIPTION", "includedPermissions": [ "PERMISSION_1", "PERMISSION_2" ], "stage": "LAUNCH-STAGE", "etag": "ETAG"}To send your request, expand one of these options:
curl (Linux, macOS, or Cloud Shell)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
curl -X PATCH \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://iam.googleapis.com/v1/RESOURCE_TYPE/RESOURCE_ID/roles"
PowerShell (Windows)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method PATCH `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://iam.googleapis.com/v1/RESOURCE_TYPE/RESOURCE_ID/roles" | Select-Object -Expand Content
APIs Explorer (browser)
Copy the request body and open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Paste the request body in this tool, complete any other required fields, and clickExecute.
The response contains an abbreviated role definition that includes the role name, the fields that you updated, and an etag that identifies the current version of the role.
{ "name": "projects/test-project-1000092/roles/myCompanyAdmin", "title": "My Updated Company Admin", "includedPermissions": [ "storage.buckets.get", "storage.buckets.list" ], "stage": "BETA", "etag": "BwWoyDpAxBc="}Disable a custom role
You can disable a custom role by changing its launch stage toDISABLED. When arole is disabled, any role bindings related to the role are inactivated,meaning that granting the role to a user has no effect.
Console
In the Google Cloud console, go to theRoles page.
Click "Select a project" drop-down list at the top of the page.
Select your organization or project.
Select a custom role and clickDisable.
gcloud
In the Google Cloud console, activate Cloud Shell.
At the bottom of the Google Cloud console, aCloud 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.
Use the
gcloud iam roles updatecommand to disable a custom role by setting its launch stage toDISABLED.As described in thegcloud tab of theEditing an existing custom role section, you can update an existing custom role in the following two ways:
By providing a YAML file that contains the updated role definition
By using flags to specify the updated role definition
The easiest way to disable an existing custom role is to use the
--stageflag and set it toDISABLED. Execute one of the following commands:To disable an organization-level role, execute the following command:
gcloud iam roles updateROLE_ID--organization=ORGANIZATION_ID \ --stage=DISABLED
To disable a project-level role, execute the following command:
gcloud iam roles updateROLE_ID --project=PROJECT_ID \ --stage=DISABLED
Each placeholder value is described below:
ROLE_IDis the name of the role, such asmyCompanyAdmin.ORGANIZATION_IDis the numeric ID of the organization, such as123456789012.PROJECT_IDis the name of the project, such asmy-project.
Examples
The following example demonstrates how to disable an organization-level role:
gcloud iam roles update myCompanyAdmin --organization=123456789012 \ --stage=DISABLED
If the role was updated successfully, the command's output is similar to the following:
description:My custom role description.etag:BwVkB5NLIQw=includedPermissions:-iam.roles.get-iam.roles.listname:organizations/123456789012/roles/myCompanyAdminstage:DISABLEDtitle:My Company Admin
The following example demonstrates how to disable a project-level role:
gcloud iam roles update myCompanyAdmin --project=my-project \ --stage=DISABLED
If the role was updated successfully, the command's output is similar to the following:
description:My custom role description.etag:BwVkB5NLIQw=includedPermissions:-iam.roles.get-iam.roles.listname:projects/my-project/roles/myCompanyAdminstage:DISABLEDtitle:My Company Admin
C++
Updatethestage field of the role toDISABLED.
C#
Updatethestage field of the role toDISABLED.
Go
Updatethestage field of the role toDISABLED.
Java
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMJava API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
importcom.google.cloud.iam.admin.v1.IAMClient;importcom.google.iam.admin.v1.Role;importcom.google.iam.admin.v1.UpdateRoleRequest;importcom.google.protobuf.FieldMask;importjava.io.IOException;publicclassDisableRole{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace the variables before running the sample.// Role ID must point to an existing role.StringprojectId="your-project-id";StringroleId="testRole";Rolerole=disableRole(projectId,roleId);System.out.println("Role name: "+role.getName());System.out.println("Role stage: "+role.getStage());}publicstaticRoledisableRole(StringprojectId,StringroleId)throwsIOException{StringroleName="projects/"+projectId+"/roles/"+roleId;Rolerole=Role.newBuilder().setName(roleName).setStage(Role.RoleLaunchStage.DISABLED).build();FieldMaskfieldMask=FieldMask.newBuilder().addPaths("stage").build();UpdateRoleRequestupdateRoleRequest=UpdateRoleRequest.newBuilder().setName(roleName).setRole(role).setUpdateMask(fieldMask).build();// Initialize client for sending requests. This client only needs to be created// once, and can be reused for multiple requests.try(IAMClientiamClient=IAMClient.create()){returniamClient.updateRole(updateRoleRequest);}}}Python
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMPython API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
fromgoogle.api_core.exceptionsimportNotFoundfromgoogle.cloud.iam_admin_v1importGetRoleRequest,IAMClient,Role,UpdateRoleRequestdefdisable_role(project_id:str,role_id:str)->Role:"""Disables an IAM role in a GCP project. Args: project_id: GCP project ID role_id: ID of GCP IAM role Returns: Updated google.cloud.iam_admin_v1.Role object with disabled stage """client=IAMClient()name=f"projects/{project_id}/roles/{role_id}"get_request=GetRoleRequest(name=name)try:role=client.get_role(get_request)role.stage=Role.RoleLaunchStage.DISABLEDupdate_request=UpdateRoleRequest(name=role.name,role=role)client.update_role(update_request)print(f"Disabled role:{role_id}:{role}")returnroleexceptNotFoundasexc:raiseNotFound(f'Role with id [{role_id}] not found, take some actions')fromexcREST
Theroles.patch method lets you change a custom role's launch stage toDISABLED,which disables the role.
Before using any of the request data, make the following replacements:
RESOURCE_TYPE: The resource type whosecustom roles you want to manage. Use the valueprojectsororganizations.RESOURCE_ID: The project ID ororganization ID whose custom roles you want to manage. Project IDs are alphanumeric strings, likemy-project. Organization IDs are numeric, like123456789012.ROLE_NAME: The full role name, including anyorganizations/,projects/, orroles/prefixes. For example,organizations/123456789012/roles/myCompanyAdmin.ETAG: An identifier for a version of the role.Include this field to prevent overwriting other role changes.
HTTP method and URL:
PATCH https://iam.googleapis.com/v1/RESOURCE_TYPE/RESOURCE_ID/roles
Request JSON body:
{ "roleId": "ROLE_NAME", "stage": DISABLED, "etag": "ETAG"}To send your request, expand one of these options:
curl (Linux, macOS, or Cloud Shell)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
curl -X PATCH \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://iam.googleapis.com/v1/RESOURCE_TYPE/RESOURCE_ID/roles"
PowerShell (Windows)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method PATCH `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://iam.googleapis.com/v1/RESOURCE_TYPE/RESOURCE_ID/roles" | Select-Object -Expand Content
APIs Explorer (browser)
Copy the request body and open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Paste the request body in this tool, complete any other required fields, and clickExecute.
You should receive a JSON response similar to the following:
{ "name": "projects/test-project-1000092/roles/myCompanyAdmin","stage": "DISABLED", "etag": "BwWoyDpAxBc="}List roles
You can list all custom roles created in your project or organization.
Console
In the Google Cloud console, go to theRoles page.
All the custom roles for the organization or project that you have selected arelisted on the page.
gcloud
In the Google Cloud console, activate Cloud Shell.
At the bottom of the Google Cloud console, aCloud 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.
Use the
gcloud iam roles listcommand to list custom roles and predefined roles for a project or organization:To list organization-level custom roles, execute the following command:
gcloud iam roles list --organization=ORGANIZATION_ID
To list project-level custom roles, execute the following command:
gcloud iam roles list --project=PROJECT_ID
Each placeholder value is described below:
ORGANIZATION_IDis the numeric ID of the organization, such as123456789012.PROJECT_IDis the name of the project, such asmy-project.
To list deleted roles, you can also specify the
--show-deletedflag.Execute the following command to list predefined roles:
gcloud iam roles list
C++
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMC++ API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
namespaceiam=::google::cloud::iam_admin_v1;[](std::stringconst&project){iam::IAMClientclient(iam::MakeIAMConnection());intcount=0;google::iam::admin::v1::ListRolesRequestrequest;request.set_parent(project);for(auto&role:client.ListRoles(request)){if(!role)throwstd::move(role).status();std::cout <<"Roles successfully retrieved: " <<role->name() <<"\n";++count;}if(count==0){std::cout <<"No roles found in project: " <<project <<"\n";}}C#
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMC# API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
usingSystem;usingSystem.Collections.Generic;usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Iam.v1;usingGoogle.Apis.Iam.v1.Data;publicpartialclassCustomRoles{publicstaticIList<Role>ListRoles(stringprojectId){varcredential=GoogleCredential.GetApplicationDefault().CreateScoped(IamService.Scope.CloudPlatform);varservice=newIamService(newIamService.Initializer{HttpClientInitializer=credential});varresponse=service.Projects.Roles.List("projects/"+projectId).Execute();foreach(varroleinresponse.Roles){Console.WriteLine(role.Name);}returnresponse.Roles;}}Go
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMGo API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
import("context""fmt""io"iam"google.golang.org/api/iam/v1")// listRoles lists a project's roles.funclistRoles(wio.Writer,projectIDstring)([]*iam.Role,error){ctx:=context.Background()service,err:=iam.NewService(ctx)iferr!=nil{returnnil,fmt.Errorf("iam.NewService: %w",err)}response,err:=service.Projects.Roles.List("projects/"+projectID).Do()iferr!=nil{returnnil,fmt.Errorf("Projects.Roles.List: %w",err)}for_,role:=rangeresponse.Roles{fmt.Fprintf(w,"Listing role: %v\n",role.Name)}returnresponse.Roles,nil}Java
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMJava API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
importcom.google.cloud.iam.admin.v1.IAMClient;importcom.google.cloud.iam.admin.v1.IAMClient.ListRolesPagedResponse;importcom.google.iam.admin.v1.ListRolesRequest;importjava.io.IOException;/** List roles in a project. */publicclassListRoles{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace the variable before running the sample.StringprojectId="your-project-id";listRoles(projectId);}publicstaticvoidlistRoles(StringprojectId)throwsIOException{ListRolesRequestlistRolesRequest=ListRolesRequest.newBuilder().setParent("projects/"+projectId).build();// Initialize client for sending requests. This client only needs to be created// once, and can be reused for multiple requests.try(IAMClientiamClient=IAMClient.create()){ListRolesPagedResponselistRolesResponse=iamClient.listRoles(listRolesRequest);listRolesResponse.iterateAll().forEach(role->System.out.println(role));}}}Python
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMPython API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
fromgoogle.cloud.iam_admin_v1importIAMClient,ListRolesRequest,RoleViewfromgoogle.cloud.iam_admin_v1.services.iam.pagersimportListRolesPagerdeflist_roles(project_id:str,show_deleted:bool=True,role_view:RoleView=RoleView.BASIC)->ListRolesPager:"""Lists IAM roles in a GCP project. Args: project_id: GCP project ID show_deleted: Whether to include deleted roles in the results role_view: Level of detail for the returned roles (e.g., BASIC or FULL) Returns: A pager for traversing through the roles """client=IAMClient()parent=f"projects/{project_id}"request=ListRolesRequest(parent=parent,show_deleted=show_deleted,view=role_view)roles=client.list_roles(request)forpageinroles.pages:forroleinpage.roles:print(role)print("Listed all iam roles")returnrolesREST
Theroles.list method lists all of the custom roles in a project or organization.
Before using any of the request data, make the following replacements:
RESOURCE_TYPE: The resource type whosecustom roles you want to manage. Use the valueprojectsororganizations.RESOURCE_ID: The project ID ororganization ID whose custom roles you want to manage. Project IDs are alphanumeric strings, likemy-project. Organization IDs are numeric, like123456789012.ROLE_VIEW: Optional. The information to include for the returned roles. To include the roles' permissions, set this field toFULL. To exclude the roles' permissions, set this field toBASIC. The default value isBASIC.PAGE_SIZE: Optional. The number of roles to include in the response. The default value is 300, and the maximum value is 1,000. If the number of roles 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 roles will start where the previous request ended.
RESOURCE_TYPE andRESOURCE_ID fields. For example:GET https://iam.googleapis.com/v1/roles.HTTP method and URL:
GET https://iam.googleapis.com/v1/RESOURCE_TYPE/RESOURCE_ID/roles?view=ROLE_VIEW&pageSize=PAGE_SIZE&pageToken=NEXT_PAGE_TOKEN
To send your request, expand one of these options:
curl (Linux, macOS, or Cloud Shell)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.Execute the following command:
curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://iam.googleapis.com/v1/RESOURCE_TYPE/RESOURCE_ID/roles?view=ROLE_VIEW&pageSize=PAGE_SIZE&pageToken=NEXT_PAGE_TOKEN"
PowerShell (Windows)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.Execute the following command:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://iam.googleapis.com/v1/RESOURCE_TYPE/RESOURCE_ID/roles?view=ROLE_VIEW&pageSize=PAGE_SIZE&pageToken=NEXT_PAGE_TOKEN" | Select-Object -Expand Content
APIs Explorer (browser)
Open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Complete any required fields and clickExecute.
You should receive a JSON response similar to the following:
{ "roles": [ { "name": "projects/my-project/roles/customRole1", "title": "First Custom Role", "description": "Created on: 2020-06-01", "etag": "BwWiPg2fmDE=" }, { "name": "projects/my-project/roles/customRole2", "title": "Second Custom Role", "description": "Created on: 2020-06-07", "etag": "BwWiuX53Wi0=" } ]}Delete a custom role
You can delete any custom role in your project or organization.
Important: Deleted roles are suspended and cannot be used to create new rolebindings in allow policies. Existing role bindings that include the deleted rolehave no effect.Console
In the Google Cloud console, go to theRoles page.
Select the role you wish to delete and clickdeleteDelete on thetop of the page.
gcloud
In the Google Cloud console, activate Cloud Shell.
At the bottom of the Google Cloud console, aCloud 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.
Use the
gcloud iam roles deletecommand to delete a custom role:To delete an organization-level custom role, execute the following command:
gcloud iam roles deleteROLE_ID --organization=ORGANIZATION_ID
To delete a project-level custom role, execute the following command:
gcloud iam roles deleteROLE_ID --project=PROJECT_ID
Each placeholder value is described below:
ROLE_IDis the name of the role, such asmyCompanyAdmin.ORGANIZATION_IDis the numeric ID of the organization, such as123456789012.PROJECT_IDis the name of the project, such asmy-project.
The role will not be included in
gcloud iam roles list, unless the--show-deletedflag is included. Deleted roles are indicated by thedeleted: trueblock in alistresponse, such as:---deleted: truedescription: My custom role description.etag: BwVkB5NLIQw=name: projects/my-project/roles/myCompanyAdmintitle: My Company Admin---
C++
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMC++ API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
namespaceiam=::google::cloud::iam_admin_v1;[](std::stringconst&name){iam::IAMClientclient(iam::MakeIAMConnection());google::iam::admin::v1::DeleteRoleRequestrequest;request.set_name(name);autoresponse=client.DeleteRole(request);if(!response)throwstd::move(response).status();std::cout <<"Role successfully deleted: " <<response->DebugString() <<"\n";}C#
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMC# API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
usingSystem;usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Iam.v1;usingGoogle.Apis.Iam.v1.Data;publicpartialclassCustomRoles{publicstaticvoidDeleteRole(stringname,stringprojectId){varcredential=GoogleCredential.GetApplicationDefault().CreateScoped(IamService.Scope.CloudPlatform);varservice=newIamService(newIamService.Initializer{HttpClientInitializer=credential});service.Projects.Roles.Delete($"projects/{projectId}/roles/{name}").Execute();Console.WriteLine("Deleted role: "+name);}}Go
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMGo API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
import("context""fmt""io"iam"google.golang.org/api/iam/v1")// deleteRole deletes a custom role.funcdeleteRole(wio.Writer,projectID,namestring)error{ctx:=context.Background()service,err:=iam.NewService(ctx)iferr!=nil{returnfmt.Errorf("iam.NewService: %w",err)}_,err=service.Projects.Roles.Delete("projects/"+projectID+"/roles/"+name).Do()iferr!=nil{returnfmt.Errorf("Projects.Roles.Delete: %w",err)}fmt.Fprintf(w,"Deleted role: %v",name)returnnil}Java
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMJava API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
importcom.google.cloud.iam.admin.v1.IAMClient;importcom.google.iam.admin.v1.DeleteRoleRequest;importjava.io.IOException;/** Delete role. */publicclassDeleteRole{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace the variables before running the sample.// Role ID must point to an existing role.StringprojectId="your-project-id";StringroleId="a unique identifier (e.g. testViewer)";deleteRole(projectId,roleId);}publicstaticvoiddeleteRole(StringprojectId,StringroleId)throwsIOException{StringroleName="projects/"+projectId+"/roles/"+roleId;DeleteRoleRequestdeleteRoleRequest=DeleteRoleRequest.newBuilder().setName(roleName).build();// Initialize client for sending requests. This client only needs to be created// once, and can be reused for multiple requests.try(IAMClientiamClient=IAMClient.create()){iamClient.deleteRole(deleteRoleRequest);System.out.println("Role deleted.");}}}Python
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMPython API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
fromgoogle.api_core.exceptionsimportFailedPrecondition,NotFoundfromgoogle.cloud.iam_admin_v1import(DeleteRoleRequest,IAMClient,Role,UndeleteRoleRequest,)defdelete_role(project_id:str,role_id:str)->Role:"""Deletes iam role in GCP project. Can be undeleted later. Args: project_id: GCP project id role_id: id of GCP iam role Returns: google.cloud.iam_admin_v1.Role object """client=IAMClient()name=f"projects/{project_id}/roles/{role_id}"request=DeleteRoleRequest(name=name)try:role=client.delete_role(request)print(f"Deleted role:{role_id}:{role}")returnroleexceptNotFound:print(f"Role with id [{role_id}] not found, take some actions")exceptFailedPreconditionaserr:print(f"Role with id [{role_id}] already deleted, take some actions)",err)REST
Theroles.delete method deletes a custom role in a project or organization.
Before using any of the request data, make the following replacements:
ROLE_NAME: The full role name, including anyorganizations/,projects/, orroles/prefixes. For example,organizations/123456789012/roles/myCompanyAdmin.
HTTP method and URL:
DELETE https://iam.googleapis.com/v1/ROLE_NAME
To send your request, expand one of these options:
curl (Linux, macOS, or Cloud Shell)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.Execute the following command:
curl -X DELETE \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://iam.googleapis.com/v1/ROLE_NAME"
PowerShell (Windows)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.Execute the following command:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method DELETE `
-Headers $headers `
-Uri "https://iam.googleapis.com/v1/ROLE_NAME" | Select-Object -Expand Content
APIs Explorer (browser)
Open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Complete any required fields and clickExecute.
The response contains the definition of the role that was deleted.
{ "name": "projects/my-project/roles/myCompanyAdmin", "title": "My Company Admin", "description": "My custom role description.", "includedPermissions": [ "iam.roles.get", "iam.roles.list" ], "etag": "BwWiPg2fmDE=","deleted": true}When a role is deleted, any role bindings that refer to the role remain in yourallow policies, but they have no effect. You can undelete a role within7 days. During this 7-dayperiod, the Google Cloud console shows that the role was deleted. You can alsolist deleted roles programmatically, but they are omitted by default.
The role is scheduled for permanent deletion 7 to14 days after the initial request to delete the role.At this point, the role no longer counts towards the limit of300 custom roles per organization or300 custom roles per project.
Note: Custom roles created in a project don't count towards your organization'scustom role limit.After the role is scheduled for permanent deletion, Google Cloud initiatesthe process to permanently delete the role. This process takes30 days. During this 30-daywindow, the role and all associated bindings are permanently removed, and youcannot create a new role with the same role ID.
After the role has been permanently deleted, up to 44days after the initial deletion request, you can create a new role using thesame role ID.
Undelete a custom role
Undeleting a role returns it to its previous state.
Roles can only be undeleted within 7 days. After7 days, Google Cloud initiates the process topermanently delete the role. This permanent deletion process can take up to30 days. After a role is permanently deleted, all rolebindings that refer to the role are removed, and you can create a new role usingthe same role ID.
Console
In the Google Cloud console, go to theRoles page.
Locate the role you wish to undelete, click the more iconat the end of the row, and clickUndelete.
gcloud
In the Google Cloud console, activate Cloud Shell.
At the bottom of the Google Cloud console, aCloud 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.
Use the
gcloud iam roles undeletecommand to undelete a custom role:To undelete an organization-level custom role, execute the following command:
gcloud iam roles undeleteROLE_ID --organization=ORGANIZATION_ID
To undelete a project-level custom role, execute the following command:
gcloud iam roles undeleteROLE_ID --project=PROJECT_ID
Each placeholder value is described below:
ROLE_IDis the name of the role, such asmyCompanyAdmin.ORGANIZATION_IDis the numeric ID of the organization, such as123456789012.PROJECT_IDis the name of the project, such asmy-project.
Examples
The following example demonstrates how to undelete an organization-level custom role:
gcloud iam roles undelete myCompanyAdmin --organization=123456789012
If the role was undeleted successfully, the command's output is similar to the following:
description:My custom role description.etag:BwVkCAx9W6w=includedPermissions:-iam.roles.get-iam.roles.listname:organizations/123456789012/roles/myCompanyAdminstage:ALPHAtitle:My Company Admin
The following example demonstrates how to undelete a project-level custom role:
gcloud iam roles undelete myCompanyAdmin --project=my-project
If the role was undeleted successfully, the command's output is similar to the following:
description:My custom role description.etag:BwVkCAx9W6w=includedPermissions:-iam.roles.get-iam.roles.listname:projects/my-project/roles/myCompanyAdminstage:ALPHAtitle:My Company Admin
C++
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMC++ API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
namespaceiam=::google::cloud::iam_admin_v1;[](std::stringconst&name){iam::IAMClientclient(iam::MakeIAMConnection());google::iam::admin::v1::UndeleteRoleRequestrequest;request.set_name(name);autoresponse=client.UndeleteRole(request);if(!response)throwstd::move(response).status();std::cout <<"Role successfully undeleted: " <<response->DebugString() <<"\n";}C#
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMC# API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
usingSystem;usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Iam.v1;usingGoogle.Apis.Iam.v1.Data;publicpartialclassCustomRoles{publicstaticRoleUndeleteRole(stringname,stringprojectId){varcredential=GoogleCredential.GetApplicationDefault().CreateScoped(IamService.Scope.CloudPlatform);varservice=newIamService(newIamService.Initializer{HttpClientInitializer=credential});stringresource=$"projects/{projectId}/roles/{name}";varrole=service.Projects.Roles.Undelete(newUndeleteRoleRequest(),resource).Execute();Console.WriteLine("Undeleted role: "+role.Name);returnrole;}}Go
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMGo API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
import("context""fmt""io"iam"google.golang.org/api/iam/v1")// undeleteRole restores a deleted custom role.funcundeleteRole(wio.Writer,projectID,namestring)(*iam.Role,error){ctx:=context.Background()service,err:=iam.NewService(ctx)iferr!=nil{returnnil,fmt.Errorf("iam.NewService: %w",err)}resource:="projects/"+projectID+"/roles/"+namerequest:=&iam.UndeleteRoleRequest{}role,err:=service.Projects.Roles.Undelete(resource,request).Do()iferr!=nil{returnnil,fmt.Errorf("Projects.Roles.Undelete: %w",err)}fmt.Fprintf(w,"Undeleted role: %v",role.Name)returnrole,nil}Java
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMJava API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
importcom.google.cloud.iam.admin.v1.IAMClient;importcom.google.iam.admin.v1.Role;importcom.google.iam.admin.v1.UndeleteRoleRequest;importjava.io.IOException;/** * Undelete a role to return it to its previous state. Undeleting only works on roles that were * deleted in the past 7 days. */publicclassUndeleteRole{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace the variables before running the sample.// Role ID must point to a role that was deleted in the past 7 days.StringprojectId="your-project-id";StringroleId="a unique identifier (e.g. testViewer)";undeleteRole(projectId,roleId);}publicstaticvoidundeleteRole(StringprojectId,StringroleId)throwsIOException{StringroleName="projects/"+projectId+"/roles/"+roleId;UndeleteRoleRequestundeleteRoleRequest=UndeleteRoleRequest.newBuilder().setName(roleName).build();// Initialize client for sending requests. This client only needs to be created// once, and can be reused for multiple requests.try(IAMClientiamClient=IAMClient.create()){Roleresult=iamClient.undeleteRole(undeleteRoleRequest);System.out.println("Undeleted role:\n"+result);}}}Python
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMPython API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
fromgoogle.api_core.exceptionsimportFailedPrecondition,NotFoundfromgoogle.cloud.iam_admin_v1import(DeleteRoleRequest,IAMClient,Role,UndeleteRoleRequest,)defundelete_role(project_id:str,role_id:str)->Role:"""Undeleted deleted iam role in GCP project. Args: project_id: GCP project id role_id: id of GCP iam role """client=IAMClient()name=f"projects/{project_id}/roles/{role_id}"request=UndeleteRoleRequest(name=name)try:role=client.undelete_role(request)print(f"Undeleted role:{role_id}:{role}")returnroleexceptNotFound:print(f"Role with id [{role_id}] not found, take some actions")exceptFailedPreconditionaserr:print(f"Role with id [{role_id}] is not deleted, take some actions)",err)REST
Theroles.undelete method undeletes a custom role in a project or organization.
Before using any of the request data, make the following replacements:
ROLE_NAME: The full role name, including anyorganizations/,projects/, orroles/prefixes. For example,organizations/123456789012/roles/myCompanyAdmin.ETAG: An identifier for a version of the role.Include this field to prevent overwriting other role changes.
HTTP method and URL:
POST https://iam.googleapis.com/v1/ROLE_NAME:undelete
Request JSON body:
{ "etag": "ETAG"}To send your request, expand one of these options:
curl (Linux, macOS, or Cloud Shell)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://iam.googleapis.com/v1/ROLE_NAME:undelete"
PowerShell (Windows)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://iam.googleapis.com/v1/ROLE_NAME:undelete" | Select-Object -Expand Content
APIs Explorer (browser)
Copy the request body and open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Paste the request body in this tool, complete any other required fields, and clickExecute.
The response contains the definition of the role that was undeleted.
{ "name": "projects/my-project/roles/myCompanyAdmin", "title": "My Company Admin", "description": "My custom role description.", "includedPermissions": [ "iam.roles.get", "iam.roles.list" ], "etag": "BwWiPg2fmDE="}What's next
- Find out how togrant roles to principals.
- Explore how you can userole recommendations todownscope permissions for principals.
- Learn aboutconditional role bindings, which grant a role only ifspecific conditions are met.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.