• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2016 Google LLC
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *       http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 /*
18  * EDITING INSTRUCTIONS
19  * This file is referenced in READMEs and javadoc. Any change to this file should be reflected in
20  * the project's READMEs and package-info.java.
21  */
22 
23 package com.google.cloud.examples.resourcemanager.snippets;
24 
25 import com.google.cloud.Identity;
26 import com.google.cloud.Policy;
27 import com.google.cloud.Role;
28 import com.google.cloud.resourcemanager.Project;
29 import com.google.cloud.resourcemanager.ResourceManager;
30 import com.google.cloud.resourcemanager.ResourceManagerOptions;
31 
32 /** A snippet for Google Cloud Resource Manager showing how to modify a project's IAM policy. */
33 public class ModifyPolicy {
34 
main(String... args)35   public static void main(String... args) {
36     // Create Resource Manager service object
37     // By default, credentials are inferred from the runtime environment.
38     ResourceManager resourceManager = ResourceManagerOptions.getDefaultInstance().getService();
39 
40     // Get a project from the server
41     String projectId = "some-project-id"; // Use an existing project's ID
42     Project project = resourceManager.get(projectId);
43 
44     // Get the project's policy
45     Policy policy = project.getPolicy();
46 
47     // Add a viewer
48     Policy.Builder modifiedPolicy = policy.toBuilder();
49     Identity newViewer = Identity.user("<insert user's email address here>");
50     modifiedPolicy.addIdentity(Role.viewer(), newViewer);
51 
52     // Write policy
53     Policy updatedPolicy = project.replacePolicy(modifiedPolicy.build());
54 
55     // Print policy
56     System.out.printf("Updated policy for %s: %n%s%n", projectId, updatedPolicy);
57   }
58 }
59