Grant roles using client libraries
Learn how to get started with the IAM methods from the Resource Manager API in your favorite programming language.
To follow step-by-step guidance for this task directly in the Google Cloud console, click Guide me:
Before you begin
Create a Google Cloud project
For this quickstart, you need a new Google Cloud project.
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get 300ドル in free credits to run, test, and deploy workloads.
-
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.
-
To initialize the gcloud CLI, run the following command:
gcloudinit
-
Create or select a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_IDwith a name for the Google Cloud project you are creating. -
Select the Google Cloud project that you created:
gcloud config set project PROJECT_ID
Replace
PROJECT_IDwith your Google Cloud project name.
-
Enable the Resource Manager 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.gcloudservicesenablecloudresourcemanager.googleapis.com -
Create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
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.
-
Grant roles to your user account. Run the following command once for each of the following IAM roles:
roles/resourcemanager.projectIamAdmingcloudprojectsadd-iam-policy-bindingPROJECT_ID--member="user:USER_IDENTIFIER"--role=ROLE
Replace the following:
PROJECT_ID: Your project ID.USER_IDENTIFIER: The identifier for your user account. For example,myemail@example.com.ROLE: The IAM role that you grant to your user account.
-
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.
-
To initialize the gcloud CLI, run the following command:
gcloudinit
-
Create or select a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_IDwith a name for the Google Cloud project you are creating. -
Select the Google Cloud project that you created:
gcloud config set project PROJECT_ID
Replace
PROJECT_IDwith your Google Cloud project name.
-
Enable the Resource Manager 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.gcloudservicesenablecloudresourcemanager.googleapis.com -
Create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
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.
-
Grant roles to your user account. Run the following command once for each of the following IAM roles:
roles/resourcemanager.projectIamAdmingcloudprojectsadd-iam-policy-bindingPROJECT_ID--member="user:USER_IDENTIFIER"--role=ROLE
Replace the following:
PROJECT_ID: Your project ID.USER_IDENTIFIER: The identifier for your user account. For example,myemail@example.com.ROLE: The IAM role that you grant to your user account.
Install the client library
C#
For more on setting up your C# development environment, refer to the C# Development Environment Setup Guide.
install-package Google.Apis.Iam.v1 install-package Google.Apis.CloudResourceManager.v1
Go
go get golang.org/x/oauth2/google go get google.golang.org/api/cloudresourcemanager/v1
Java
For more on setting up your Java development environment, refer to the Java Development Environment Setup Guide.
If you are using Maven, add this to yourpom.xml
file.
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-cloudresourcemanager</artifactId>
<version>v3-rev20240128-2.0.0</version>
</dependency>
<dependency>
<groupId>com.google.auth</groupId>
<artifactId>google-auth-library-oauth2-http</artifactId>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson2</artifactId>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-iam</artifactId>
<version>v1-rev20240118-2.0.0</version>
</dependency>Python
For more on setting up your Python development environment, refer to the Python Development Environment Setup Guide.
pip install --upgrade google-api-python-client google-auth google-auth-httplib2
Read, modify, and write an allow policy
The code snippet in this quickstart does the following:
- Initializes the Resource Manager service, which manages Google Cloud projects.
- Reads the allow policy for your project.
- Modifies the allow policy by granting the Log Writer role
(
roles/logging.logWriter) to your Google Account. - Writes the updated allow policy.
- Prints all the principals that have the Log Writer role
(
roles/logging.logWriter) at the project level. - Revokes the Log Writer role.
Replace the following values before running the code snippet:
your-project: The ID of your project.your-member: The email address for your user account. For example,user:my-user@example.com.
C#
To learn how to install and use the client library for Resource Manager, see Resource Manager client libraries. For more information, see the Resource Manager C# API reference documentation.
To authenticate to Resource Manager, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.
usingGoogle.Apis.Auth.OAuth2 ;
usingGoogle.Apis.CloudResourceManager.v1;
usingGoogle.Apis.CloudResourceManager.v1.Data;
usingGoogle.Apis.Iam.v1;
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
publicclassQuickStart
{
publicstaticvoidMain(string[]args)
{
// TODO: Replace with your project ID
varprojectId="your-project";
// TODO: Replace with the ID of your principal.
// For examples, see https://cloud.google.com/iam/docs/principal-identifiers
varmember="your-principal";
// Role to be granted
varrole="roles/logging.logWriter";
// Initialize service
CloudResourceManagerServicecrmService=InitializeService();
// Grant your principal the "Log Writer" role for your project
AddBinding(crmService,projectId,member,role);
// Get the project's policy and print all principals with the the "Log Writer" role
varpolicy=GetPolicy(crmService,projectId);
varbinding=policy.Bindings.FirstOrDefault(x=>x.Role==role);
Console.WriteLine("Role: "+binding.Role);
Console.Write("Members: ");
foreach(varminbinding.Members)
{
Console.Write("["+m+"] ");
}
Console.WriteLine();
// Remove principal from the "Log Writer" role
RemoveMember(crmService,projectId,member,role);
}
publicstaticCloudResourceManagerServiceInitializeService()
{
// Get credentials
varcredential=GoogleCredential .GetApplicationDefault ()
.CreateScoped (IamService.Scope.CloudPlatform);
// Create the Cloud Resource Manager service object
CloudResourceManagerServicecrmService=newCloudResourceManagerService(
newCloudResourceManagerService.Initializer
{
HttpClientInitializer=credential
});
returncrmService;
}
publicstaticPolicyGetPolicy(CloudResourceManagerServicecrmService,StringprojectId)
{
// Get the project's policy by calling the
// Cloud Resource Manager Projects API
varpolicy=crmService.Projects.GetIamPolicy(
newGetIamPolicyRequest(),
projectId).Execute();
returnpolicy;
}
publicstaticvoidSetPolicy(CloudResourceManagerServicecrmService,StringprojectId,Policypolicy)
{
// Set the project's policy by calling the
// Cloud Resource Manager Projects API
crmService.Projects.SetIamPolicy(
newSetIamPolicyRequest
{
Policy=policy
},projectId).Execute();
}
publicstaticvoidAddBinding(
CloudResourceManagerServicecrmService,
stringprojectId,
stringmember,
stringrole)
{
// Get the project's policy
varpolicy=GetPolicy(crmService,projectId);
// Find binding in policy
varbinding=policy.Bindings.FirstOrDefault(x=>x.Role==role);
// If binding already exists, add principal to binding
if(binding!=null)
{
binding.Members.Add(member);
}
// If binding does not exist, add binding to policy
else
{
binding=newBinding
{
Role=role,
Members=newList<string>{member}
};
policy.Bindings.Add(binding);
}
// Set the updated policy
SetPolicy(crmService,projectId,policy);
}
publicstaticvoidRemoveMember(
CloudResourceManagerServicecrmService,
stringprojectId,
stringmember,
stringrole)
{
// Get the project's policy
varpolicy=GetPolicy(crmService,projectId);
// Remove the principal from the role
varbinding=policy.Bindings.FirstOrDefault(x=>x.Role==role);
if(binding==null)
{
Console.WriteLine("Role does not exist in policy.");
}
else
{
if(binding.Members.Contains(member))
{
binding.Members.Remove(member);
}
else
{
Console.WriteLine("The member has not been granted this role.");
}
if(binding.Members.Count==0)
{
policy.Bindings.Remove(binding);
}
}
// Set the updated policy
SetPolicy(crmService,projectId,policy);
}
}Go
To learn how to install and use the client library for Resource Manager, see Resource Manager client libraries. For more information, see the Resource Manager Go API reference documentation.
To authenticate to Resource Manager, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.
packagemain
import(
"context"
"flag"
"fmt"
"log"
"strings"
"time"
"google.golang.org/api/cloudresourcemanager/v1"
)
funcmain(){
// TODO: Add your project ID
projectID:=flag.String("project_id","","Cloud Project ID")
// TODO: Add the ID of your principal.
// For examples, see https://cloud.google.com/iam/docs/principal-identifiers
member:=flag.String("member_id","","Your principal ID")
flag.Parse()
// The role to be granted
varrolestring="roles/logging.logWriter"
// Initializes the Cloud Resource Manager service
ctx:=context.Background()
crmService,err:=cloudresourcemanager.NewService(ctx)
iferr!=nil{
log.Fatalf("cloudresourcemanager.NewService: %v",err)
}
// Grants your principal the "Log writer" role for your project
addBinding(crmService,*projectID,*member,role)
// Gets the project's policy and prints all principals with the "Log Writer" role
policy:=getPolicy(crmService,*projectID)
// Find the policy binding for role. Only one binding can have the role.
varbinding*cloudresourcemanager.Binding
for_,b:=rangepolicy.Bindings{
ifb.Role==role{
binding=b
break
}
}
fmt.Println("Role: ",binding.Role)
fmt.Print("Members: ",strings.Join(binding.Members,", "))
// Removes member from the "Log writer" role
removeMember(crmService,*projectID,*member,role)
}
// addBinding adds the principal to the project's IAM policy
funcaddBinding(crmService*cloudresourcemanager.Service,projectID,member,rolestring){
policy:=getPolicy(crmService,projectID)
// Find the policy binding for role. Only one binding can have the role.
varbinding*cloudresourcemanager.Binding
for_,b:=rangepolicy.Bindings{
ifb.Role==role{
binding=b
break
}
}
ifbinding!=nil{
// If the binding exists, adds the principal to the binding
binding.Members=append(binding.Members,member)
}else{
// If the binding does not exist, adds a new binding to the policy
binding=&cloudresourcemanager.Binding{
Role:role,
Members:[]string{member},
}
policy.Bindings=append(policy.Bindings,binding)
}
setPolicy(crmService,projectID,policy)
}
// removeMember removes the principal from the project's IAM policy
funcremoveMember(crmService*cloudresourcemanager.Service,projectID,member,rolestring){
policy:=getPolicy(crmService,projectID)
// Find the policy binding for role. Only one binding can have the role.
varbinding*cloudresourcemanager.Binding
varbindingIndexint
fori,b:=rangepolicy.Bindings{
ifb.Role==role{
binding=b
bindingIndex=i
break
}
}
// Order doesn't matter for bindings or members, so to remove, move the last item
// into the removed spot and shrink the slice.
iflen(binding.Members)==1{
// If the principal is the only member in the binding, removes the binding
last:=len(policy.Bindings)-1
policy.Bindings[bindingIndex]=policy.Bindings[last]
policy.Bindings=policy.Bindings[:last]
}else{
// If there is more than one member in the binding, removes the principal
varmemberIndexint
fori,mm:=rangebinding.Members{
ifmm==member{
memberIndex=i
}
}
last:=len(policy.Bindings[bindingIndex].Members)-1
binding.Members[memberIndex]=binding.Members[last]
binding.Members=binding.Members[:last]
}
setPolicy(crmService,projectID,policy)
}
// getPolicy gets the project's IAM policy
funcgetPolicy(crmService*cloudresourcemanager.Service,projectIDstring)*cloudresourcemanager.Policy{
ctx:=context.Background()
ctx,cancel:=context.WithTimeout(ctx,time.Second*10)
defercancel()
request:=new(cloudresourcemanager.GetIamPolicyRequest)
policy,err:=crmService.Projects.GetIamPolicy(projectID,request).Do()
iferr!=nil{
log.Fatalf("Projects.GetIamPolicy: %v",err)
}
returnpolicy
}
// setPolicy sets the project's IAM policy
funcsetPolicy(crmService*cloudresourcemanager.Service,projectIDstring,policy*cloudresourcemanager.Policy){
ctx:=context.Background()
ctx,cancel:=context.WithTimeout(ctx,time.Second*10)
defercancel()
request:=new(cloudresourcemanager.SetIamPolicyRequest)
request.Policy=policy
policy,err:=crmService.Projects.SetIamPolicy(projectID,request).Do()
iferr!=nil{
log.Fatalf("Projects.SetIamPolicy: %v",err)
}
}
Java
To learn how to install and use the client library for Resource Manager, see Resource Manager client libraries. For more information, see the Resource Manager Java API reference documentation.
To authenticate to Resource Manager, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.
importcom.google.cloud.iam.admin.v1.IAMClient ;
importcom.google.iam.admin.v1.ServiceAccountName ;
importcom.google.iam.v1.Binding ;
importcom.google.iam.v1.GetIamPolicyRequest ;
importcom.google.iam.v1.Policy ;
importcom.google.iam.v1.SetIamPolicyRequest ;
importcom.google.protobuf.FieldMask ;
importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.Arrays;
importjava.util.List;
publicclass Quickstart{
publicstaticvoidmain(String[]args)throwsIOException{
// TODO: Replace with your project ID.
StringprojectId="your-project";
// TODO: Replace with your service account name.
StringserviceAccount="your-service-account";
// TODO: Replace with the ID of your principal.
// For examples, see https://cloud.google.com/iam/docs/principal-identifiers
Stringmember="your-principal";
// The role to be granted.
Stringrole="roles/logging.logWriter";
quickstart(projectId,serviceAccount,member,role);
}
// Creates new policy and adds binding.
// Checks if changes are present and removes policy.
publicstaticvoidquickstart(StringprojectId,StringserviceAccount,
Stringmember,Stringrole)throwsIOException{
// Construct the service account email.
// You can modify the ".iam.gserviceaccount.com" to match the name of the service account
// to use for authentication.
serviceAccount=serviceAccount+"@"+projectId+".iam.gserviceaccount.com";
// Initialize client that will be used to send requests.
// This client only needs to be created once, and can be reused for multiple requests.
try(IAMClient iamClient=IAMClient .create()){
// Grants your principal the "Log writer" role for your project.
addBinding(iamClient,projectId,serviceAccount,member,role);
// Get the project's policy and print all principals with the "Log Writer" role
Policy policy=getPolicy(iamClient,projectId,serviceAccount);
Binding binding=null;
List<Binding>bindings=policy.getBindingsList ();
for(Binding b:bindings){
if(b.getRole().equals(role)){
binding=b;
break;
}
}
System.out.println("Role: "+binding.getRole ());
System.out.print("Principals: ");
for(Stringm:binding.getMembersList ()){
System.out.print("["+m+"] ");
}
System.out.println();
// Removes principal from the "Log writer" role.
removeMember(iamClient,projectId,serviceAccount,member,role);
}
}
publicstaticvoidaddBinding(IAMClient iamClient,StringprojectId,StringserviceAccount,
Stringmember,Stringrole){
// Gets the project's policy.
Policy policy=getPolicy(iamClient,projectId,serviceAccount);
// If policy is not retrieved, return early.
if(policy==null){
return;
}
Policy .BuilderupdatedPolicy=policy.toBuilder ();
// Get the binding if present in the policy.
Binding binding=null;
for(Binding b:updatedPolicy.getBindingsList()){
if(b.getRole().equals(role)){
binding=b;
break;
}
}
if(binding!=null){
// If binding already exists, adds principal to binding.
binding.getMembersList ().add(member);
}else{
// If binding does not exist, adds binding to policy.
binding=Binding .newBuilder()
.setRole(role)
.addMembers (member)
.build();
updatedPolicy.addBindings (binding);
}
// Sets the updated policy.
setPolicy(iamClient,projectId,serviceAccount,updatedPolicy.build());
}
publicstaticvoidremoveMember(IAMClient iamClient,StringprojectId,StringserviceAccount,
Stringmember,Stringrole){
// Gets the project's policy.
Policy .Builderpolicy=getPolicy(iamClient,projectId,serviceAccount).toBuilder();
// Removes the principal from the role.
Binding binding=null;
for(Binding b:policy.getBindingsList ()){
if(b.getRole().equals(role)){
binding=b;
break;
}
}
if(binding!=null && binding.getMembersList ().contains(member)){
List<String>newMemberList=newArrayList<>(binding.getMembersList ());
newMemberList.remove(member);
Binding newBinding=binding.toBuilder ().clearMembers ()
.addAllMembers (newMemberList)
.build();
List<Binding>newBindingList=newArrayList<>(policy.getBindingsList ());
newBindingList.remove(binding);
if(!newBinding.getMembersList ().isEmpty()){
newBindingList.add(newBinding);
}
policy.clearBindings ()
.addAllBindings (newBindingList);
}
// Sets the updated policy.
setPolicy(iamClient,projectId,serviceAccount,policy.build());
}
publicstaticPolicy getPolicy(IAMClient iamClient,StringprojectId,StringserviceAccount){
// Gets the project's policy by calling the
// IAMClient API.
GetIamPolicyRequest request=GetIamPolicyRequest .newBuilder()
.setResource(ServiceAccountName .of(projectId,serviceAccount).toString())
.build();
returniamClient.getIamPolicy (request);
}
privatestaticvoidsetPolicy(IAMClient iamClient,StringprojectId,
StringserviceAccount,Policy policy){
List<String>paths=Arrays.asList("bindings","etag");
// Sets a project's policy.
SetIamPolicyRequest request=SetIamPolicyRequest .newBuilder()
.setResource(ServiceAccountName .of(projectId,serviceAccount).toString())
.setPolicy (policy)
// A FieldMask specifying which fields of the policy to modify. Only
// the fields in the mask will be modified. If no mask is provided, the
// following default mask is used:
// `paths: "bindings, etag"`
.setUpdateMask(FieldMask .newBuilder().addAllPaths (paths).build())
.build();
iamClient.setIamPolicy (request);
}
}Python
To learn how to install and use the client library for Resource Manager, see Resource Manager client libraries. For more information, see the Resource Manager Python API reference documentation.
To authenticate to Resource Manager, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.
fromgoogle.cloudimport resourcemanager_v3
fromgoogle.iam.v1import iam_policy_pb2, policy_pb2
defquickstart(project_id: str, principal: str) -> None:
"""Demonstrates basic IAM operations.
This quickstart shows how to get a project's IAM policy,
add a principal to a role, list members of a role,
and remove a principal from a role.
Args:
project_id: ID or number of the Google Cloud project you want to use.
principal: The principal ID requesting the access.
"""
# Role to be granted.
role = "roles/logging.logWriter"
crm_service = resourcemanager_v3 .ProjectsClient ()
# Grants your principal the 'Log Writer' role for the project.
modify_policy_add_role(crm_service, project_id, role, principal)
# Gets the project's policy and prints all principals with the 'Log Writer' role.
policy = get_policy(crm_service, project_id)
binding = next(b for b in policy.bindings if b.role == role)
print(f"Role: {(binding.role)}")
print("Members: ")
for m in binding.members:
print(f"[{m}]")
# Removes the principal from the 'Log Writer' role.
modify_policy_remove_principal(crm_service, project_id, role, principal)
defget_policy(
crm_service: resourcemanager_v3 .ProjectsClient , project_id: str
) -> policy_pb2.Policy:
"""Gets IAM policy for a project."""
request = iam_policy_pb2.GetIamPolicyRequest()
request.resource = f"projects/{project_id}"
policy = crm_service.get_iam_policy (request)
return policy
defset_policy(
crm_service: resourcemanager_v3 .ProjectsClient ,
project_id: str,
policy: policy_pb2.Policy,
) -> None:
"""Adds a new role binding to a policy."""
request = iam_policy_pb2.SetIamPolicyRequest()
request.resource = f"projects/{project_id}"
request.policy.CopyFrom(policy)
crm_service.set_iam_policy (request)
defmodify_policy_add_role(
crm_service: resourcemanager_v3 .ProjectsClient ,
project_id: str,
role: str,
principal: str,
) -> None:
"""Adds a new role binding to a policy."""
policy = get_policy(crm_service, project_id)
for bind in policy.bindings:
if bind.role == role:
bind.members.append(principal)
break
else:
binding = policy_pb2.Binding()
binding.role = role
binding.members.append(principal)
policy.bindings.append(binding)
set_policy(crm_service, project_id, policy)
defmodify_policy_remove_principal(
crm_service: resourcemanager_v3 .ProjectsClient ,
project_id: str,
role: str,
principal: str,
) -> None:
"""Removes a principal from a role binding."""
policy = get_policy(crm_service, project_id)
for bind in policy.bindings:
if bind.role == role:
if principal in bind.members:
bind.members.remove(principal)
break
set_policy(crm_service, project_id, policy)
if __name__ == "__main__":
# TODO: Replace with your project ID.
project_id = "your-project-id"
# TODO: Replace with the ID of your principal.
# For examples, see https://cloud.google.com/iam/docs/principal-identifiers
principal = "your-principal"
quickstart(project_id, principal)Congratulations! You used the IAM methods in the Resource Manager API to modify access for a project.
How did it go?
Clean up
-
Optional: Revoke the authentication credentials that you created, and delete the local credential file.
gcloudauthapplication-defaultrevoke
-
Optional: Revoke credentials from the gcloud CLI.
gcloudauthrevoke
What's next
- Read about how IAM works.
- Learn more about granting, changing, and revoking access.
- Troubleshoot access issues with the Policy Troubleshooter.