Skip to content

Commit ba096de

Browse files
melaniedejonglesv
andauthored
[IAM] Remove old quickstart, add dependencies (GoogleCloudPlatform#3752)
* Remove old quickstart, add dependencies * Update QuickstartTests file name * Update README and enable mvn:exec for quickstart * Rename application * Update error reporting Co-authored-by: Les Vogel <lesv@users.noreply.github.com>
1 parent b8b440d commit ba096de

File tree

6 files changed

+179
-255
lines changed

6 files changed

+179
-255
lines changed

iam/api-client/README.md

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,36 @@ the Google API Client Library for Java.
1010

1111
## Quickstart
1212

13-
Install [Maven](http://maven.apache.org/).
13+
The Quickstart does the following:
1414

15-
Build the project with:
15+
* Initializes the Resource Manager service, which manages GCP projects.
16+
* Reads the [IAM policy](https://cloud.google.com/iam/docs/overview#cloud-iam-policy)
17+
for your project.
18+
* Modifies the IAM policy by granting the Log Writer role
19+
(`roles/logging.logWriter`) to your Google Account.
20+
* Writes the updated IAM policy.
21+
* Prints all the members in your project that have the Log Writer role
22+
(`roles/logging.logWriter`).
23+
* Revokes the Log Writer role.
24+
25+
To build and run the Quickstart, install [Maven](http://maven.apache.org/).
26+
27+
To build the project, run the following command:
1628

1729
```xml
1830
mvn clean package
1931
```
2032

21-
Run the Quickstart, which lists roles in a project:
33+
To run the Quickstart, ensure that the Resource Manager API is enabled
34+
for your project and that you have set up authentication. For details, see the
35+
[Before you begin](https://cloud.google.com/iam/docs/quickstart-client-libraries#before-you-begin)
36+
section of the IAM client library Quickstart documentation.
37+
38+
Then, replace the `projectId` and `member` fields with your
39+
project ID and member ID, and run the following command:
2240

2341
```xml
2442
mvn exec:java
25-
```
43+
```
44+
45+
For more information, see the [IAM client library Quickstart documentation](https://cloud.google.com/iam/docs/quickstart-client-libraries).

iam/api-client/pom.xml

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,20 @@
5555
<version>v1-rev20200907-1.30.10</version><!-- v1 required here, v2 is different - DO NOT UPDATE to v2 -->
5656
</dependency>
5757
<!-- [END iam_java_quickstart_dependency] -->
58+
<!-- [START iamcredentials_java_dependency]-->
59+
<dependency>
60+
<groupId>com.google.apis</groupId>
61+
<artifactId>google-api-services-iamcredentials</artifactId>
62+
<version>v1-rev20200821-1.30.10</version>
63+
</dependency>
64+
<!-- [END iamcredentials_java_dependency]-->
65+
<!-- [START troubleshooter_java_dependency]-->
66+
<dependency>
67+
<groupId>com.google.apis</groupId>
68+
<artifactId>google-api-services-policytroubleshooter</artifactId>
69+
<version>v1-rev20200801-1.30.10</version>
70+
</dependency>
71+
<!-- [END troubleshooter_java_dependency]-->
5872
<dependency>
5973
<groupId>commons-cli</groupId>
6074
<artifactId>commons-cli</artifactId>
@@ -89,7 +103,7 @@
89103
<artifactId>exec-maven-plugin</artifactId>
90104
<version>3.0.0</version>
91105
<configuration>
92-
<mainClass>com.google.iam.snippets.GrantableRoles</mainClass>
106+
<mainClass>iam.snippets.Quickstart</mainClass>
93107
</configuration>
94108
</plugin>
95109
</plugins>

iam/api-client/src/main/java/iam/snippets/Quickstart.java

Lines changed: 134 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/* Copyright 2018 Google LLC
1+
/* Copyright 2020 Google LLC
22
*
33
* Licensed under the Apache License, Version 2.0 (the "License");
44
* you may not use this file except in compliance with the License.
@@ -13,48 +13,161 @@
1313
* limitations under the License.
1414
*/
1515

16-
// [START iam_quickstart]
17-
1816
package iam.snippets;
1917

18+
// [START iam_quickstart]
2019
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
2120
import com.google.api.client.json.jackson2.JacksonFactory;
22-
import com.google.api.services.iam.v1.Iam;
21+
import com.google.api.services.cloudresourcemanager.CloudResourceManager;
22+
import com.google.api.services.cloudresourcemanager.model.Binding;
23+
import com.google.api.services.cloudresourcemanager.model.GetIamPolicyRequest;
24+
import com.google.api.services.cloudresourcemanager.model.Policy;
25+
import com.google.api.services.cloudresourcemanager.model.SetIamPolicyRequest;
2326
import com.google.api.services.iam.v1.IamScopes;
24-
import com.google.api.services.iam.v1.model.ListRolesResponse;
25-
import com.google.api.services.iam.v1.model.Role;
2627
import com.google.auth.http.HttpCredentialsAdapter;
2728
import com.google.auth.oauth2.GoogleCredentials;
29+
import java.io.IOException;
30+
import java.security.GeneralSecurityException;
2831
import java.util.Collections;
2932
import java.util.List;
3033

3134
public class Quickstart {
3235

33-
public static void main(String[] args) throws Exception {
34-
// Get credentials
36+
public static void main(String[] args) {
37+
// TODO: Replace with your project ID.
38+
String projectId = "your-project";
39+
// TODO: Replace with the ID of your member in the form "user:member@example.com"
40+
String member = "your-member";
41+
// The role to be granted.
42+
String role = "roles/logging.logWriter";
43+
44+
// Initializes the Cloud Resource Manager service.
45+
CloudResourceManager crmService = null;
46+
try {
47+
crmService = initializeService();
48+
} catch (IOException | GeneralSecurityException e) {
49+
System.out.println("Unable to initialize service: \n" + e.getMessage() + e.getStackTrace());
50+
}
51+
52+
// Grants your member the "Log writer" role for your project.
53+
addBinding(crmService, projectId, member, role);
54+
55+
// Get the project's policy and print all members with the "Log Writer" role
56+
Policy policy = getPolicy(crmService, projectId);
57+
Binding binding = null;
58+
List<Binding> bindings = policy.getBindings();
59+
for (Binding b : bindings) {
60+
if (b.getRole().equals(role)) {
61+
binding = b;
62+
break;
63+
}
64+
}
65+
System.out.println("Role: " + binding.getRole());
66+
System.out.print("Members: ");
67+
for (String m : binding.getMembers()) {
68+
System.out.print("[" + m + "] ");
69+
}
70+
System.out.println();
71+
72+
// Removes member from the "Log writer" role.
73+
removeMember(crmService, projectId, member, role);
74+
}
75+
76+
public static CloudResourceManager initializeService()
77+
throws IOException, GeneralSecurityException {
78+
// Use the Application Default Credentials strategy for authentication. For more info, see:
79+
// https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
3580
GoogleCredentials credential =
3681
GoogleCredentials.getApplicationDefault()
3782
.createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
3883

39-
// Create the Cloud IAM service object
40-
Iam service =
41-
new Iam.Builder(
84+
// Creates the Cloud Resource Manager service object.
85+
CloudResourceManager service =
86+
new CloudResourceManager.Builder(
4287
GoogleNetHttpTransport.newTrustedTransport(),
4388
JacksonFactory.getDefaultInstance(),
4489
new HttpCredentialsAdapter(credential))
45-
.setApplicationName("quickstart")
90+
.setApplicationName("iam-quickstart")
4691
.build();
92+
return service;
93+
}
94+
95+
public static void addBinding(
96+
CloudResourceManager crmService, String projectId, String member, String role) {
97+
98+
// Gets the project's policy.
99+
Policy policy = getPolicy(crmService, projectId);
47100

48-
// Call the Cloud IAM Roles API
49-
ListRolesResponse response = service.roles().list().execute();
50-
List<Role> roles = response.getRoles();
101+
// Finds binding in policy, if it exists
102+
Binding binding = null;
103+
for (Binding b : policy.getBindings()) {
104+
if (b.getRole().equals(role)) {
105+
binding = b;
106+
break;
107+
}
108+
}
109+
110+
if (binding != null) {
111+
// If binding already exists, adds member to binding.
112+
binding.getMembers().add(member);
113+
} else {
114+
// If binding does not exist, adds binding to policy.
115+
binding = new Binding();
116+
binding.setRole(role);
117+
binding.setMembers(Collections.singletonList(member));
118+
policy.getBindings().add(binding);
119+
}
120+
121+
// Sets the updated policy
122+
setPolicy(crmService, projectId, policy);
123+
}
124+
125+
public static void removeMember(
126+
CloudResourceManager crmService, String projectId, String member, String role) {
127+
// Gets the project's policy.
128+
Policy policy = getPolicy(crmService, projectId);
129+
130+
// Removes the member from the role.
131+
Binding binding = null;
132+
for (Binding b : policy.getBindings()) {
133+
if (b.getRole().equals(role)) {
134+
binding = b;
135+
break;
136+
}
137+
}
138+
if (binding.getMembers().contains(member)) {
139+
binding.getMembers().remove(member);
140+
if (binding.getMembers().isEmpty()) {
141+
policy.getBindings().remove(binding);
142+
}
143+
}
144+
145+
// Sets the updated policy.
146+
setPolicy(crmService, projectId, policy);
147+
}
148+
149+
public static Policy getPolicy(CloudResourceManager crmService, String projectId) {
150+
// Gets the project's policy by calling the
151+
// Cloud Resource Manager Projects API.
152+
Policy policy = null;
153+
try {
154+
GetIamPolicyRequest request = new GetIamPolicyRequest();
155+
policy = crmService.projects().getIamPolicy(projectId, request).execute();
156+
} catch (IOException e) {
157+
System.out.println("Unable to get policy: \n" + e.getMessage() + e.getStackTrace());
158+
}
159+
return policy;
160+
}
51161

52-
// Process the response
53-
for (Role role : roles) {
54-
System.out.println("Title: " + role.getTitle());
55-
System.out.println("Name: " + role.getName());
56-
System.out.println("Description: " + role.getDescription());
57-
System.out.println();
162+
private static void setPolicy(CloudResourceManager crmService, String projectId, Policy policy) {
163+
// Sets the project's policy by calling the
164+
// Cloud Resource Manager Projects API.
165+
try {
166+
SetIamPolicyRequest request = new SetIamPolicyRequest();
167+
request.setPolicy(policy);
168+
crmService.projects().setIamPolicy(projectId, request).execute();
169+
} catch (IOException e) {
170+
System.out.println("Unable to set policy: \n" + e.getMessage() + e.getStackTrace());
58171
}
59172
}
60173
}

0 commit comments

Comments
 (0)