Disable a service account key

Demonstrates disabling an IAM service account key.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

Java

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.

To authenticate to IAM, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import com.google.cloud.iam.admin.v1.IAMClient;
import java.io.IOException;


public class DisableServiceAccountKey {

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

    disableServiceAccountKey(projectId, serviceAccountName, serviceAccountKeyName);
  }

  // Disables a service account key.
  public static void disableServiceAccountKey(String projectId,
                                              String accountName,
                                              String key) throws IOException {
    // Construct the service account email.
    // You can modify the ".iam.gserviceaccount.com" to match the service account name in which
    // you want to disable the key.
    // See, https://cloud.google.com/iam/docs/creating-managing-service-account-keys?hl=en#disabling
    String email = String.format("%s@%s.iam.gserviceaccount.com", accountName, projectId);
    String name = String.format("projects/%s/serviceAccounts/%s/keys/%s", projectId, email, key);

    // Initialize client that will be used to send requests.
    // This client only needs to be created once, and can be reused for multiple requests.
    try (IAMClient iamClient = IAMClient.create()) {
      iamClient.disableServiceAccountKey(name);

      System.out.println("Disabled service account key: " + name);
    }
  }
}

What's next

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