use of com.google.api.services.cloudresourcemanager.model.GetIamPolicyRequest in project google-cloud-intellij by GoogleCloudPlatform.
the class CloudApiManager method addRolesToServiceAccount.
/**
* Adds a set of {@link Role roles} to a {@link ServiceAccount}.
*
* <p>This is done by fetching the cloud project's existing IAM Policy, adding the new roles to
* the given service account, and then writing the updated policy back to the cloud project.
*
* @param user the current {@link CredentialedUser}
* @param serviceAccount the {@link ServiceAccount} to which to add roles
* @param roles the set of {@link Role} to be added to the service account
* @param cloudProject the current {@link CloudProject}
* @throws IOException if the API call fails to update the IAM policy
*/
private static void addRolesToServiceAccount(CredentialedUser user, ServiceAccount serviceAccount, Set<Role> roles, CloudProject cloudProject) throws IOException {
CloudResourceManager resourceManager = GoogleApiClientFactory.getInstance().getCloudResourceManagerClient(user.getCredential());
Policy existingPolicy = resourceManager.projects().getIamPolicy(cloudProject.projectId(), new GetIamPolicyRequest()).execute();
List<Binding> bindings = Lists.newArrayList(existingPolicy.getBindings());
List<Binding> additionalBindings = roles.stream().map(role -> {
Binding binding = new Binding();
binding.setRole(role.getName());
binding.setMembers(createServiceAccountMemberBindings(serviceAccount));
return binding;
}).collect(Collectors.toList());
bindings.addAll(additionalBindings);
SetIamPolicyRequest policyRequest = new SetIamPolicyRequest();
Policy newPolicy = new Policy();
newPolicy.setBindings(bindings);
policyRequest.setPolicy(newPolicy);
resourceManager.projects().setIamPolicy(cloudProject.projectId(), policyRequest).execute();
}
Aggregations