Search in sources :

Example 31 with Project

use of com.google.api.services.cloudresourcemanager.v3.model.Project in project java-docs-samples by GoogleCloudPlatform.

the class GetPolicy method getPolicy.

// Gets a project's policy.
public static Policy getPolicy(String projectId) {
    // projectId = "my-project-id"
    Policy policy = null;
    CloudResourceManager service = null;
    try {
        service = createCloudResourceManagerService();
    } catch (IOException | GeneralSecurityException e) {
        System.out.println("Unable to initialize service: \n" + e.toString());
        return policy;
    }
    try {
        GetIamPolicyRequest request = new GetIamPolicyRequest();
        policy = service.projects().getIamPolicy(projectId, request).execute();
        System.out.println("Policy retrieved: " + policy.toString());
        return policy;
    } catch (IOException e) {
        System.out.println("Unable to get policy: \n" + e.toString());
        return policy;
    }
}
Also used : Policy(com.google.api.services.cloudresourcemanager.v3.model.Policy) CloudResourceManager(com.google.api.services.cloudresourcemanager.v3.CloudResourceManager) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) GetIamPolicyRequest(com.google.api.services.cloudresourcemanager.v3.model.GetIamPolicyRequest)

Example 32 with Project

use of com.google.api.services.cloudresourcemanager.v3.model.Project in project java-docs-samples by GoogleCloudPlatform.

the class Quickstart method main.

public static void main(String[] args) {
    // TODO: Replace with your project ID in the form "projects/your-project-id".
    String projectId = "your-project";
    // TODO: Replace with the ID of your member in the form "user:member@example.com"
    String member = "your-member";
    // The role to be granted.
    String role = "roles/logging.logWriter";
    // Initializes the Cloud Resource Manager service.
    CloudResourceManager crmService = null;
    try {
        crmService = initializeService();
    } catch (IOException | GeneralSecurityException e) {
        System.out.println("Unable to initialize service: \n" + e.getMessage() + e.getStackTrace());
    }
    // Grants your member the "Log writer" role for your project.
    addBinding(crmService, projectId, member, role);
    // Get the project's policy and print all members with the "Log Writer" role
    Policy policy = getPolicy(crmService, projectId);
    Binding binding = null;
    List<Binding> bindings = policy.getBindings();
    for (Binding b : bindings) {
        if (b.getRole().equals(role)) {
            binding = b;
            break;
        }
    }
    System.out.println("Role: " + binding.getRole());
    System.out.print("Members: ");
    for (String m : binding.getMembers()) {
        System.out.print("[" + m + "] ");
    }
    System.out.println();
    // Removes member from the "Log writer" role.
    removeMember(crmService, projectId, member, role);
}
Also used : Policy(com.google.api.services.cloudresourcemanager.v3.model.Policy) Binding(com.google.api.services.cloudresourcemanager.v3.model.Binding) CloudResourceManager(com.google.api.services.cloudresourcemanager.v3.CloudResourceManager) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException)

Example 33 with Project

use of com.google.api.services.cloudresourcemanager.v3.model.Project in project java-docs-samples by GoogleCloudPlatform.

the class RemoveMember method removeMember.

// Removes member from a role; removes binding if binding contains 0 members.
public static void removeMember(Policy policy) {
    // policy = service.Projects.GetIAmPolicy(new GetIamPolicyRequest(), your-project-id).Execute();
    String role = "roles/existing-role";
    String member = "user:member-to-remove@example.com";
    List<Binding> bindings = policy.getBindings();
    Binding binding = null;
    for (Binding b : bindings) {
        if (b.getRole().equals(role)) {
            binding = b;
        }
    }
    if (binding.getMembers().contains(member)) {
        binding.getMembers().remove(member);
        System.out.println("Member " + member + " removed from " + role);
        if (binding.getMembers().isEmpty()) {
            policy.getBindings().remove(binding);
        }
        return;
    }
    System.out.println("Role not found in policy; member not removed");
    return;
}
Also used : Binding(com.google.api.services.cloudresourcemanager.v3.model.Binding)

Example 34 with Project

use of com.google.api.services.cloudresourcemanager.v3.model.Project in project terra-workspace-manager by DataBiosphere.

the class GcpCloudSyncStep method doStep.

@Override
public StepResult doStep(FlightContext flightContext) throws InterruptedException, RetryException {
    String gcpProjectId = flightContext.getWorkingMap().get(GCP_PROJECT_ID, String.class);
    FlightMap workingMap = flightContext.getWorkingMap();
    // Read Sam groups for each workspace role.
    Map<WsmIamRole, String> workspaceRoleGroupsMap = workingMap.get(WorkspaceFlightMapKeys.IAM_GROUP_EMAIL_MAP, new TypeReference<>() {
    });
    try {
        Policy currentPolicy = resourceManagerCow.projects().getIamPolicy(gcpProjectId, new GetIamPolicyRequest()).execute();
        List<Binding> newBindings = new ArrayList<>();
        // Add all existing bindings to ensure we don't accidentally clobber existing permissions.
        newBindings.addAll(currentPolicy.getBindings());
        // Add appropriate project-level roles for each WSM IAM role.
        workspaceRoleGroupsMap.forEach((role, email) -> newBindings.add(bindingForRole(role, email, gcpProjectId)));
        Policy newPolicy = new Policy().setVersion(currentPolicy.getVersion()).setBindings(newBindings).setEtag(currentPolicy.getEtag());
        SetIamPolicyRequest iamPolicyRequest = new SetIamPolicyRequest().setPolicy(newPolicy);
        logger.info("Setting new Cloud Context IAM policy: " + iamPolicyRequest.toPrettyString());
        resourceManagerCow.projects().setIamPolicy(gcpProjectId, iamPolicyRequest).execute();
    } catch (IOException e) {
        throw new RetryableCrlException("Error setting IAM permissions", e);
    }
    return StepResult.getStepResultSuccess();
}
Also used : Policy(com.google.api.services.cloudresourcemanager.v3.model.Policy) Binding(com.google.api.services.cloudresourcemanager.v3.model.Binding) SetIamPolicyRequest(com.google.api.services.cloudresourcemanager.v3.model.SetIamPolicyRequest) ArrayList(java.util.ArrayList) IOException(java.io.IOException) GetIamPolicyRequest(com.google.api.services.cloudresourcemanager.v3.model.GetIamPolicyRequest) RetryableCrlException(bio.terra.workspace.service.workspace.exceptions.RetryableCrlException) FlightMap(bio.terra.stairway.FlightMap) WsmIamRole(bio.terra.workspace.service.iam.model.WsmIamRole)

Example 35 with Project

use of com.google.api.services.cloudresourcemanager.v3.model.Project in project terra-workspace-manager by DataBiosphere.

the class DeleteGcpContextFlightTest method deleteContextDo.

@Test
@DisabledIfEnvironmentVariable(named = "TEST_ENV", matches = BUFFER_SERVICE_DISABLED_ENVS_REG_EX)
void deleteContextDo() throws Exception {
    FlightMap createParameters = new FlightMap();
    AuthenticatedUserRequest userRequest = userAccessUtils.defaultUserAuthRequest();
    createParameters.put(WorkspaceFlightMapKeys.WORKSPACE_ID, workspaceUuid.toString());
    createParameters.put(JobMapKeys.AUTH_USER_INFO.getKeyName(), userRequest);
    // Create the google context.
    FlightState flightState = StairwayTestUtils.blockUntilFlightCompletes(jobService.getStairway(), CreateGcpContextFlightV2.class, createParameters, CREATION_FLIGHT_TIMEOUT, null);
    assertEquals(FlightStatus.SUCCESS, flightState.getFlightStatus());
    String projectId = workspaceService.getAuthorizedGcpProject(workspaceUuid, userRequest).orElse(null);
    assertNotNull(projectId);
    // validate that required project does not throw and gives the same answer
    String projectId2 = workspaceService.getAuthorizedRequiredGcpProject(workspaceUuid, userRequest);
    assertEquals(projectId, projectId2);
    Project project = crl.getCloudResourceManagerCow().projects().get(projectId).execute();
    assertEquals("ACTIVE", project.getState());
    // Delete the google context.
    FlightMap deleteParameters = new FlightMap();
    deleteParameters.put(WorkspaceFlightMapKeys.WORKSPACE_ID, workspaceUuid.toString());
    // Force each step to be retried once to ensure proper behavior.
    Map<String, StepStatus> doFailures = new HashMap<>();
    doFailures.put(DeleteControlledSamResourcesStep.class.getName(), StepStatus.STEP_RESULT_FAILURE_RETRY);
    doFailures.put(DeleteControlledDbResourcesStep.class.getName(), StepStatus.STEP_RESULT_FAILURE_RETRY);
    doFailures.put(DeleteGcpProjectStep.class.getName(), StepStatus.STEP_RESULT_FAILURE_RETRY);
    doFailures.put(DeleteGcpContextStep.class.getName(), StepStatus.STEP_RESULT_FAILURE_RETRY);
    FlightDebugInfo debugInfo = FlightDebugInfo.newBuilder().doStepFailures(doFailures).build();
    flightState = StairwayTestUtils.blockUntilFlightCompletes(jobService.getStairway(), DeleteGcpContextFlight.class, deleteParameters, DELETION_FLIGHT_TIMEOUT, debugInfo);
    assertEquals(FlightStatus.SUCCESS, flightState.getFlightStatus());
    assertTrue(testUtils.getAuthorizedGcpCloudContext(workspaceUuid, userRequest).isEmpty());
    // make sure required really requires
    assertThrows(CloudContextRequiredException.class, () -> workspaceService.getAuthorizedRequiredGcpProject(workspaceUuid, userRequest));
    project = crl.getCloudResourceManagerCow().projects().get(projectId).execute();
    assertEquals("DELETE_REQUESTED", project.getState());
}
Also used : FlightDebugInfo(bio.terra.stairway.FlightDebugInfo) HashMap(java.util.HashMap) AuthenticatedUserRequest(bio.terra.workspace.service.iam.AuthenticatedUserRequest) StepStatus(bio.terra.stairway.StepStatus) FlightState(bio.terra.stairway.FlightState) Project(com.google.api.services.cloudresourcemanager.v3.model.Project) FlightMap(bio.terra.stairway.FlightMap) BaseConnectedTest(bio.terra.workspace.common.BaseConnectedTest) Test(org.junit.jupiter.api.Test) DisabledIfEnvironmentVariable(org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable)

Aggregations

Project (com.google.api.services.cloudresourcemanager.v3.model.Project)38 Test (org.junit.jupiter.api.Test)30 BaseIntegrationTest (bio.terra.buffer.common.BaseIntegrationTest)15 Pool (bio.terra.buffer.common.Pool)15 ResourceId (bio.terra.buffer.common.ResourceId)15 IntegrationUtils.preparePool (bio.terra.buffer.integration.IntegrationUtils.preparePool)15 FlightManager (bio.terra.buffer.service.resource.FlightManager)15 IOException (java.io.IOException)13 Binding (com.google.api.services.cloudresourcemanager.v3.model.Binding)10 StepStatus (bio.terra.stairway.StepStatus)9 ArrayList (java.util.ArrayList)9 BaseConnectedTest (bio.terra.workspace.common.BaseConnectedTest)8 List (java.util.List)8 DisabledIfEnvironmentVariable (org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable)8 FlightDebugInfo (bio.terra.stairway.FlightDebugInfo)7 FlightState (bio.terra.stairway.FlightState)7 AuthenticatedUserRequest (bio.terra.workspace.service.iam.AuthenticatedUserRequest)7 GetIamPolicyRequest (com.google.api.services.cloudresourcemanager.v3.model.GetIamPolicyRequest)7 FlightMap (bio.terra.stairway.FlightMap)6 Project (com.blackducksoftware.bdio2.model.Project)6