Grant roles using client libraries

Learn how to get started with the IAM methods fromthe Resource Manager API in your favorite programming language.


To follow step-by-step guidance for this task directly in the Google Cloud console, clickGuide me:

Guide me


Before you begin

Create a Google Cloud project

For this quickstart, you need a new Google Cloud project.

Warning: If you use an existing project, then completing this quickstart willenable some users to temporarily access resources in that project.
  1. 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.
  2. Install the Google Cloud CLI.

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

  4. Toinitialize the gcloud CLI, run the following command:

    gcloudinit
  5. 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 role (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.create permission.Learn how to grant roles.
    Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.
    • Create a Google Cloud project:

      gcloud projects createPROJECT_ID

      ReplacePROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set projectPROJECT_ID

      ReplacePROJECT_ID with your Google Cloud project name.

  6. 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.enable permission.Learn how to grant roles.

    gcloudservicesenablecloudresourcemanager.googleapis.com
  7. 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.

  8. Grant roles to your user account. Run the following command once for each of the following IAM roles:roles/resourcemanager.projectIamAdmin

    gcloudprojectsadd-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.
  9. Install the Google Cloud CLI.

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

  11. Toinitialize the gcloud CLI, run the following command:

    gcloudinit
  12. 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 role (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.create permission.Learn how to grant roles.
    Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.
    • Create a Google Cloud project:

      gcloud projects createPROJECT_ID

      ReplacePROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set projectPROJECT_ID

      ReplacePROJECT_ID with your Google Cloud project name.

  13. 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.enable permission.Learn how to grant roles.

    gcloudservicesenablecloudresourcemanager.googleapis.com
  14. 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.

  15. Grant roles to your user account. Run the following command once for each of the following IAM roles:roles/resourcemanager.projectIamAdmin

    gcloudprojectsadd-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 theC# Development Environment Setup Guide.

install-package Google.Apis.Iam.v1install-package Google.Apis.CloudResourceManager.v1

Go

go get golang.org/x/oauth2/googlego get google.golang.org/api/cloudresourcemanager/v1

Java

For more on setting up your Java development environment, refer to theJava Development Environment Setup Guide.

If you are usingMaven, add this to yourpom.xmlfile.
<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 thePython 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 Cloudprojects.
  • Reads theallow policy for yourproject.
  • 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 youruser account. For example,user:my-user@example.com.
Note: The following snippet modifies access by getting, modifying, and settingtheallow policy for the project. For more information on allow policies,see theIAM overview.

C#

To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries. For more information, see theResource ManagerC# API reference documentation.

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeSet 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 IDvarprojectId="your-project";// TODO: Replace with the ID of your principal.// For examples, see https://cloud.google.com/iam/docs/principal-identifiersvarmember="your-principal";// Role to be grantedvarrole="roles/logging.logWriter";// Initialize serviceCloudResourceManagerServicecrmService=InitializeService();// Grant your principal the "Log Writer" role for your projectAddBinding(crmService,projectId,member,role);// Get the project's policy and print all principals with the the "Log Writer" rolevarpolicy=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" roleRemoveMember(crmService,projectId,member,role);}publicstaticCloudResourceManagerServiceInitializeService(){// Get credentialsvarcredential=GoogleCredential.GetApplicationDefault().CreateScoped(IamService.Scope.CloudPlatform);// Create the Cloud Resource Manager service objectCloudResourceManagerServicecrmService=newCloudResourceManagerService(newCloudResourceManagerService.Initializer{HttpClientInitializer=credential});returncrmService;}publicstaticPolicyGetPolicy(CloudResourceManagerServicecrmService,StringprojectId){// Get the project's policy by calling the// Cloud Resource Manager Projects APIvarpolicy=crmService.Projects.GetIamPolicy(newGetIamPolicyRequest(),projectId).Execute();returnpolicy;}publicstaticvoidSetPolicy(CloudResourceManagerServicecrmService,StringprojectId,Policypolicy){// Set the project's policy by calling the// Cloud Resource Manager Projects APIcrmService.Projects.SetIamPolicy(newSetIamPolicyRequest{Policy=policy},projectId).Execute();}publicstaticvoidAddBinding(CloudResourceManagerServicecrmService,stringprojectId,stringmember,stringrole){// Get the project's policyvarpolicy=GetPolicy(crmService,projectId);// Find binding in policyvarbinding=policy.Bindings.FirstOrDefault(x=>x.Role==role);// If binding already exists, add principal to bindingif(binding!=null){binding.Members.Add(member);}// If binding does not exist, add binding to policyelse{binding=newBinding{Role=role,Members=newList<string>{member}};policy.Bindings.Add(binding);}// Set the updated policySetPolicy(crmService,projectId,policy);}publicstaticvoidRemoveMember(CloudResourceManagerServicecrmService,stringprojectId,stringmember,stringrole){// Get the project's policyvarpolicy=GetPolicy(crmService,projectId);// Remove the principal from the rolevarbinding=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 policySetPolicy(crmService,projectId,policy);}}

Go

To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries. For more information, see theResource ManagerGo API reference documentation.

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

packagemainimport("context""flag""fmt""log""strings""time""google.golang.org/api/cloudresourcemanager/v1")funcmain(){// TODO: Add your project IDprojectID:=flag.String("project_id","","Cloud Project ID")// TODO: Add the ID of your principal.// For examples, see https://cloud.google.com/iam/docs/principal-identifiersmember:=flag.String("member_id","","Your principal ID")flag.Parse()// The role to be grantedvarrolestring="roles/logging.logWriter"// Initializes the Cloud Resource Manager servicectx:=context.Background()crmService,err:=cloudresourcemanager.NewService(ctx)iferr!=nil{log.Fatalf("cloudresourcemanager.NewService: %v",err)}// Grants your principal the "Log writer" role for your projectaddBinding(crmService,*projectID,*member,role)// Gets the project's policy and prints all principals with the "Log Writer" rolepolicy:=getPolicy(crmService,*projectID)// Find the policy binding for role. Only one binding can have the role.varbinding*cloudresourcemanager.Bindingfor_,b:=rangepolicy.Bindings{ifb.Role==role{binding=bbreak}}fmt.Println("Role: ",binding.Role)fmt.Print("Members: ",strings.Join(binding.Members,", "))// Removes member from the "Log writer" roleremoveMember(crmService,*projectID,*member,role)}// addBinding adds the principal to the project's IAM policyfuncaddBinding(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.Bindingfor_,b:=rangepolicy.Bindings{ifb.Role==role{binding=bbreak}}ifbinding!=nil{// If the binding exists, adds the principal to the bindingbinding.Members=append(binding.Members,member)}else{// If the binding does not exist, adds a new binding to the policybinding=&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 policyfuncremoveMember(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.BindingvarbindingIndexintfori,b:=rangepolicy.Bindings{ifb.Role==role{binding=bbindingIndex=ibreak}}// 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 bindinglast:=len(policy.Bindings)-1policy.Bindings[bindingIndex]=policy.Bindings[last]policy.Bindings=policy.Bindings[:last]}else{// If there is more than one member in the binding, removes the principalvarmemberIndexintfori,mm:=rangebinding.Members{ifmm==member{memberIndex=i}}last:=len(policy.Bindings[bindingIndex].Members)-1binding.Members[memberIndex]=binding.Members[last]binding.Members=binding.Members[:last]}setPolicy(crmService,projectID,policy)}// getPolicy gets the project's IAM policyfuncgetPolicy(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 policyfuncsetPolicy(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=policypolicy,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, seeResource Manager client libraries. For more information, see theResource ManagerJava API reference documentation.

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeSet 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;publicclassQuickstart{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-identifiersStringmember="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(IAMClientiamClient=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" rolePolicypolicy=getPolicy(iamClient,projectId,serviceAccount);Bindingbinding=null;List<Binding>bindings=policy.getBindingsList();for(Bindingb: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(IAMClientiamClient,StringprojectId,StringserviceAccount,Stringmember,Stringrole){// Gets the project's policy.Policypolicy=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.Bindingbinding=null;for(Bindingb: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(IAMClientiamClient,StringprojectId,StringserviceAccount,Stringmember,Stringrole){// Gets the project's policy.Policy.Builderpolicy=getPolicy(iamClient,projectId,serviceAccount).toBuilder();// Removes the principal from the role.Bindingbinding=null;for(Bindingb: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);BindingnewBinding=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());}publicstaticPolicygetPolicy(IAMClientiamClient,StringprojectId,StringserviceAccount){// Gets the project's policy by calling the// IAMClient API.GetIamPolicyRequestrequest=GetIamPolicyRequest.newBuilder().setResource(ServiceAccountName.of(projectId,serviceAccount).toString()).build();returniamClient.getIamPolicy(request);}privatestaticvoidsetPolicy(IAMClientiamClient,StringprojectId,StringserviceAccount,Policypolicy){List<String>paths=Arrays.asList("bindings","etag");// Sets a project's policy.SetIamPolicyRequestrequest=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, seeResource Manager client libraries. For more information, see theResource ManagerPython API reference documentation.

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

fromgoogle.cloudimportresourcemanager_v3fromgoogle.iam.v1importiam_policy_pb2,policy_pb2defquickstart(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(bforbinpolicy.bindingsifb.role==role)print(f"Role:{(binding.role)}")print("Members: ")forminbinding.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)returnpolicydefset_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)forbindinpolicy.bindings:ifbind.role==role:bind.members.append(principal)breakelse:binding=policy_pb2.Binding()binding.role=rolebinding.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)forbindinpolicy.bindings:ifbind.role==role:ifprincipalinbind.members:bind.members.remove(principal)breakset_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-identifiersprincipal="your-principal"quickstart(project_id,principal)

Congratulations! You used the IAM methods in the Resource Manager APIto modify access for a project.

How did it go?

Clean up

  1. Optional: Revoke the authentication credentials that you created, and delete the local credential file.

    gcloudauthapplication-defaultrevoke
  2. Optional: Revoke credentials from the gcloud CLI.

    gcloudauthrevoke

What's next

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.