Enable a service account key

Stay organized with collections Save and categorize content based on your preferences.

Demonstrates enabling a disabled IAM service account key.

Code sample


To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM Java API reference documentation.

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.IamScopes;
import com.google.api.services.iam.v1.model.EnableServiceAccountKeyRequest;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;

public class EnableServiceAccountKey {

  public static void main(String[] args) {
    // TODO(Developer): Replace the below variables before running.
    String projectId = "gcloud-project-id";
    String serviceAccountName = "service-account-name";
    String serviceAccountKeyName = "service-account-key-name";

    enableServiceAccountKey(projectId, serviceAccountName, serviceAccountKeyName);

  // Enables a service account key.
  public static void enableServiceAccountKey(String projectId, String serviceAccountName,
      String serviceAccountKeyName) {
    // Initialize the IAM service.
    Iam service = null;
    try {
      service = initService();
    } catch (IOException | GeneralSecurityException e) {
      System.out.println("Unable to initialize service: \n" + e);

    String serviceAccountEmail = serviceAccountName + "@" + projectId + ".iam.gserviceaccount.com";

    try {
          enableServiceAccountKeyRequest = new EnableServiceAccountKeyRequest();
      // Use the IAM service to enable the service account key.
              .format("projects/%s/serviceAccounts/%s/keys/%s", projectId, serviceAccountEmail,
                  serviceAccountKeyName), enableServiceAccountKeyRequest)

      System.out.println("Enabled service account key: " + serviceAccountKeyName);
    } catch (IOException e) {
      System.out.println("Failed to enable service account key: \n" + e);

  private static Iam initService() throws GeneralSecurityException, IOException {
    /* Use the Application Default Credentials strategy for authentication. For more info, see:
     https://cloud.google.com/docs/authentication/production#finding_credentials_automatically */
    GoogleCredentials credential =

    // Initialize the IAM service, which can be used to send requests to the IAM API.
    return new Iam.Builder(
        new HttpCredentialsAdapter(credential))

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.