Skip to content

Commit 1f30a72

Browse files
authored
docs(iam-samples): added samples and tests for enabling and disabling… (GoogleCloudPlatform#6064)
* docs(iam-samples): added samples and tests for enabling and disabling service account keys. * docs(iam-samples): lint fix
1 parent eb49a93 commit 1f30a72

File tree

3 files changed

+207
-1
lines changed

3 files changed

+207
-1
lines changed
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
/* Copyright 2021 Google LLC
2+
*
3+
* Licensed under the Apache License, Version 2.0 (the "License");
4+
* you may not use this file except in compliance with the License.
5+
* You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software
10+
* distributed under the License is distributed on an "AS IS" BASIS,
11+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
* See the License for the specific language governing permissions and
13+
* limitations under the License.
14+
*/
15+
16+
package iam.snippets;
17+
18+
// [START iam_disable_service_account_key]
19+
20+
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
21+
import com.google.api.client.json.gson.GsonFactory;
22+
import com.google.api.services.iam.v1.Iam;
23+
import com.google.api.services.iam.v1.IamScopes;
24+
import com.google.api.services.iam.v1.model.DisableServiceAccountKeyRequest;
25+
import com.google.auth.http.HttpCredentialsAdapter;
26+
import com.google.auth.oauth2.GoogleCredentials;
27+
import java.io.IOException;
28+
import java.security.GeneralSecurityException;
29+
import java.util.Collections;
30+
31+
32+
public class DisableServiceAccountKey {
33+
34+
public static void main(String[] args) throws IOException {
35+
// TODO(Developer): Replace the below variables before running.
36+
String projectId = "gcloud-project-id";
37+
String serviceAccountName = "service-account-name";
38+
String serviceAccountKeyName = "service-account-key-name";
39+
40+
disableServiceAccountKey(projectId, serviceAccountName, serviceAccountKeyName);
41+
}
42+
43+
// Disables a service account key.
44+
public static void disableServiceAccountKey(String projectId, String serviceAccountName,
45+
String serviceAccountKeyName) {
46+
// Initialize the IAM service.
47+
Iam service = null;
48+
try {
49+
service = initService();
50+
} catch (IOException | GeneralSecurityException e) {
51+
System.out.println("Unable to initialize service: \n" + e);
52+
return;
53+
}
54+
55+
String serviceAccountEmail = serviceAccountName + "@" + projectId + ".iam.gserviceaccount.com";
56+
57+
try {
58+
DisableServiceAccountKeyRequest
59+
disableServiceAccountKeyRequest = new DisableServiceAccountKeyRequest();
60+
// Use the IAM service to disable the service account key.
61+
service
62+
.projects()
63+
.serviceAccounts()
64+
.keys()
65+
.disable(String
66+
.format("projects/%s/serviceAccounts/%s/keys/%s", projectId, serviceAccountEmail,
67+
serviceAccountKeyName), disableServiceAccountKeyRequest)
68+
.execute();
69+
70+
System.out.println("Disabled service account key: " + serviceAccountKeyName);
71+
} catch (IOException e) {
72+
System.out.println("Failed to disable service account key: \n" + e);
73+
}
74+
}
75+
76+
private static Iam initService() throws GeneralSecurityException, IOException {
77+
/* Use the Application Default Credentials strategy for authentication. For more info, see:
78+
https://cloud.google.com/docs/authentication/production#finding_credentials_automatically */
79+
GoogleCredentials credential =
80+
GoogleCredentials.getApplicationDefault()
81+
.createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
82+
83+
// Initialize the IAM service, which can be used to send requests to the IAM API.
84+
return new Iam.Builder(
85+
GoogleNetHttpTransport.newTrustedTransport(),
86+
GsonFactory.getDefaultInstance(),
87+
new HttpCredentialsAdapter(credential))
88+
.setApplicationName("service-accounts")
89+
.build();
90+
}
91+
}
92+
// [END iam_disable_service_account_key]
93+
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
/* Copyright 2021 Google LLC
2+
*
3+
* Licensed under the Apache License, Version 2.0 (the "License");
4+
* you may not use this file except in compliance with the License.
5+
* You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software
10+
* distributed under the License is distributed on an "AS IS" BASIS,
11+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
* See the License for the specific language governing permissions and
13+
* limitations under the License.
14+
*/
15+
16+
package iam.snippets;
17+
18+
// [START iam_enable_service_account_key]
19+
20+
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
21+
import com.google.api.client.json.gson.GsonFactory;
22+
import com.google.api.services.iam.v1.Iam;
23+
import com.google.api.services.iam.v1.IamScopes;
24+
import com.google.api.services.iam.v1.model.EnableServiceAccountKeyRequest;
25+
import com.google.auth.http.HttpCredentialsAdapter;
26+
import com.google.auth.oauth2.GoogleCredentials;
27+
import java.io.IOException;
28+
import java.security.GeneralSecurityException;
29+
import java.util.Collections;
30+
31+
32+
public class EnableServiceAccountKey {
33+
34+
public static void main(String[] args) {
35+
// TODO(Developer): Replace the below variables before running.
36+
String projectId = "gcloud-project-id";
37+
String serviceAccountName = "service-account-name";
38+
String serviceAccountKeyName = "service-account-key-name";
39+
40+
enableServiceAccountKey(projectId, serviceAccountName, serviceAccountKeyName);
41+
}
42+
43+
// Enables a service account key.
44+
public static void enableServiceAccountKey(String projectId, String serviceAccountName,
45+
String serviceAccountKeyName) {
46+
// Initialize the IAM service.
47+
Iam service = null;
48+
try {
49+
service = initService();
50+
} catch (IOException | GeneralSecurityException e) {
51+
System.out.println("Unable to initialize service: \n" + e);
52+
return;
53+
}
54+
55+
String serviceAccountEmail = serviceAccountName + "@" + projectId + ".iam.gserviceaccount.com";
56+
57+
try {
58+
EnableServiceAccountKeyRequest
59+
enableServiceAccountKeyRequest = new EnableServiceAccountKeyRequest();
60+
// Use the IAM service to enable the service account key.
61+
service
62+
.projects()
63+
.serviceAccounts()
64+
.keys()
65+
.enable(String
66+
.format("projects/%s/serviceAccounts/%s/keys/%s", projectId, serviceAccountEmail,
67+
serviceAccountKeyName), enableServiceAccountKeyRequest)
68+
.execute();
69+
70+
System.out.println("Enabled service account key: " + serviceAccountKeyName);
71+
} catch (IOException e) {
72+
System.out.println("Failed to enable service account key: \n" + e);
73+
}
74+
}
75+
76+
private static Iam initService() throws GeneralSecurityException, IOException {
77+
/* Use the Application Default Credentials strategy for authentication. For more info, see:
78+
https://cloud.google.com/docs/authentication/production#finding_credentials_automatically */
79+
GoogleCredentials credential =
80+
GoogleCredentials.getApplicationDefault()
81+
.createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
82+
83+
// Initialize the IAM service, which can be used to send requests to the IAM API.
84+
return new Iam.Builder(
85+
GoogleNetHttpTransport.newTrustedTransport(),
86+
GsonFactory.getDefaultInstance(),
87+
new HttpCredentialsAdapter(credential))
88+
.setApplicationName("service-accounts")
89+
.build();
90+
}
91+
}
92+
// [END iam_enable_service_account_key]
93+

iam/api-client/src/test/java/iam/snippets/ServiceAccountTests.java

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,11 @@
3535
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
3636
public class ServiceAccountTests {
3737

38-
private ByteArrayOutputStream bout;
3938
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
4039
private static final String SERVICE_ACCOUNT =
4140
"service-account-" + UUID.randomUUID().toString().substring(0, 8);
41+
private static String SERVICE_ACCOUNT_KEY;
42+
private ByteArrayOutputStream bout;
4243

4344
private static void requireEnvVar(String varName) {
4445
assertNotNull(
@@ -90,6 +91,9 @@ public void stage2_testServiceAccountKeyCreate() {
9091
CreateServiceAccountKey.createKey(PROJECT_ID, SERVICE_ACCOUNT);
9192
String got = bout.toString();
9293
assertThat(got, containsString("Created key:"));
94+
String serviceAccountKeyPath = got.substring(got.lastIndexOf(":") + 1);
95+
SERVICE_ACCOUNT_KEY = serviceAccountKeyPath
96+
.substring(serviceAccountKeyPath.lastIndexOf("/") + 1).trim();
9397
}
9498

9599
@Test
@@ -99,6 +103,22 @@ public void stage2_testServiceAccountKeysList() {
99103
assertThat(got, containsString("Key:"));
100104
}
101105

106+
@Test
107+
public void stage2_testServiceAccountKeyDisable() {
108+
DisableServiceAccountKey
109+
.disableServiceAccountKey(PROJECT_ID, SERVICE_ACCOUNT, SERVICE_ACCOUNT_KEY);
110+
String got = bout.toString();
111+
assertThat(got, containsString("Disabled service account key"));
112+
}
113+
114+
@Test
115+
public void stage2_testServiceAccountKeyEnable() {
116+
EnableServiceAccountKey
117+
.enableServiceAccountKey(PROJECT_ID, SERVICE_ACCOUNT, SERVICE_ACCOUNT_KEY);
118+
String got = bout.toString();
119+
assertThat(got, containsString("Enabled service account key"));
120+
}
121+
102122
@Test
103123
public void stage3_testServiceAccountKeyDelete() {
104124
DeleteServiceAccountKey.deleteKey(PROJECT_ID, SERVICE_ACCOUNT);

0 commit comments

Comments
 (0)