I'm able to create a service account but facing issues while assigning a role to the service account. Here is the approach I'm using
CloudResourceManager cloudResourceManagerService = createCloudResourceManagerService(clientId,
clientSecret);
GetIamPolicy getrequest = cloudResourceManagerService.projects().getIamPolicy(projectId,
new GetIamPolicyRequest());
Policy response = getrequest.execute();
//Modification to policy
List<String> members = response.getBindings().get(0).getMembers();
members.add("serviceAccount:[email protected]");
response.getBindings().get(0).setMembers(members);
// =================Set policy========================
String resource = "projects/" + projectId + "/serviceAccounts/" +
"[email protected]";
SetIamPolicyRequest requestBody = new SetIamPolicyRequest().setPolicy(response);
SetIamPolicy setrequest = cloudResourceManagerService.projects().setIamPolicy(resource, requestBody);
Policy newResponse = setrequest.execute();
This code is not giving any error but also not setting a role for the provided service account.
Because you are calling projects.serviceAccounts.setIamPolicy, and because you specifically are passing the serviceAccount, you are only granting the service account editor role on itself.
If you want the service account to be an editor on the project you must call projects.setIamPolicy and the resource you want to specify should be the project itself.
As John Hanley says, you will also need to do this as a read-modify-write cycle as described here.