Disable and enable service accounts

This page explains how to disable and enable service accounts using the Identity and Access Management (IAM) API, the Google Cloud console, and the gcloud CLI.

Before you begin

  • Enable the IAM API.

    Enable the API

  • Set up authentication.

    Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    gcloud

    You can use the gcloud CLI samples on this page from either of the following development environments:

    • Cloud Shell: To use an online terminal with the gcloud CLI already set up, activate Cloud Shell.

      At the bottom of this page, a Cloud Shell session starts and displays a command-line prompt. It can take a few seconds for the session to initialize.

    • Local shell: To use the gcloud CLI in a local development environment, install and initialize the gcloud CLI.

    C++

    To use the C++ samples on this page from a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    1. Install the Google Cloud CLI.
    2. To initialize the gcloud CLI, run the following command:

      gcloud init
    3. Create local authentication credentials for your Google Account:

      gcloud auth application-default login

    For more information, see Set up authentication for a local development environment in the Google Cloud authentication documentation.

    C#

    To use the .NET samples on this page from a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    1. Install the Google Cloud CLI.
    2. To initialize the gcloud CLI, run the following command:

      gcloud init
    3. Create local authentication credentials for your Google Account:

      gcloud auth application-default login

    For more information, see Set up authentication for a local development environment in the Google Cloud authentication documentation.

    Go

    To use the Go samples on this page from a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    1. Install the Google Cloud CLI.
    2. To initialize the gcloud CLI, run the following command:

      gcloud init
    3. Create local authentication credentials for your Google Account:

      gcloud auth application-default login

    For more information, see Set up authentication for a local development environment in the Google Cloud authentication documentation.

    Java

    To use the Java samples on this page from a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    1. Install the Google Cloud CLI.
    2. To initialize the gcloud CLI, run the following command:

      gcloud init
    3. Create local authentication credentials for your Google Account:

      gcloud auth application-default login

    For more information, see Set up authentication for a local development environment in the Google Cloud authentication documentation.

    Python

    To use the Python samples on this page from a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    1. Install the Google Cloud CLI.
    2. To initialize the gcloud CLI, run the following command:

      gcloud init
    3. Create local authentication credentials for your Google Account:

      gcloud auth application-default login

    For more information, see Set up authentication for a local development environment in the Google Cloud authentication documentation.

    REST

    To use the REST API samples on this page in a local development environment, you use the credentials you provide to the gcloud CLI.

      Install the Google Cloud CLI, then initialize it by running the following command:

      gcloud init

  • Understand IAM service accounts

Required roles

To get the permissions that you need to manage service accounts, ask your administrator to grant you the Service Account Admin (roles/iam.serviceAccountAdmin) IAM role on the project. For more information about granting roles, see Manage access.

You might also be able to get the required permissions through custom roles or other predefined roles.

To learn more about this role, see Service Accounts roles.

IAM basic roles also contain permissions to manage service accounts. You should not grant basic roles in a production environment, but you can grant them in a development or test environment.

Disable a service account

Similar to deleting a service account, when you disable a service account, applications will no longer have access to Google Cloud resources through that service account. If you disable the default App Engine and Compute Engine service accounts, the instances will no longer have access to resources in the project. If you attempt to disable an already disabled service account, it will have no effect.

Unlike deleting a service account, disabled service accounts can easily be re-enabled as necessary. We recommend disabling a service account before deleting it to make sure no critical applications are using the service account.

Console

  1. In the Google Cloud console, go to the Service accounts page.

    Go to Service accounts

  2. Select a project.

  3. Click the name of the service account that you want to disable.

  4. Under Service account status, click Disable service account, then click Disable to confirm the change.

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. Execute the gcloud iam service-accounts disable command to disable a service account.

    Command:

    gcloud iam service-accounts disable SA_NAME@PROJECT_ID.iam.gserviceaccount.com

    Output:

    Disabled service account SA_NAME@PROJECT_ID.iam.gserviceaccount.com

C++

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

To authenticate to IAM, set up Application Default Credentials. For more information, see Before you begin.

namespace iam = ::google::cloud::iam_admin_v1;
[](std::string const& name) {
  iam::IAMClient client(iam::MakeIAMConnection());
  google::iam::admin::v1::DisableServiceAccountRequest request;
  request.set_name(name);
  auto response = client.DisableServiceAccount(request);
  if (!response.ok()) throw std::runtime_error(response.message());
  std::cout << "ServiceAccount successfully disabled.\n";
}

C#

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

To authenticate to IAM, set up Application Default Credentials. For more information, see Before you begin.


using System;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Iam.v1;
using Google.Apis.Iam.v1.Data;

public partial class ServiceAccounts
{
    public static void DisableServiceAccount(string email)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var request = new DisableServiceAccountRequest();

        string resource = "projects/-/serviceAccounts/" + email;
        service.Projects.ServiceAccounts.Disable(request, resource).Execute();
        Console.WriteLine("Disabled service account: " + email);
    }
}

Go

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

To authenticate to IAM, set up Application Default Credentials. For more information, see Before you begin.

import (
	"context"
	"fmt"
	"io"

	iam "google.golang.org/api/iam/v1"
)

// disableServiceAccount disables a service account.
func disableServiceAccount(w io.Writer, email string) error {
	// email:= service-account@your-project.iam.gserviceaccount.com
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return fmt.Errorf("iam.NewService: %w", err)
	}

	request := &iam.DisableServiceAccountRequest{}
	_, err = service.Projects.ServiceAccounts.Disable("projects/-/serviceAccounts/"+email, request).Do()
	if err != nil {
		return fmt.Errorf("Projects.ServiceAccounts.Disable: %w", err)
	}
	fmt.Fprintf(w, "Disabled service account: %v", email)
	return nil
}

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 Before you begin.

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.DisableServiceAccountRequest;
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 DisableServiceAccount {

  // Disables a service account.
  public static void disableServiceAccount(String projectId, String serviceAccountName) {
    // String projectId = "my-project-id";
    // String serviceAccountName = "my-service-account-name";

    Iam service = null;
    try {
      service = initService();
    } catch (IOException | GeneralSecurityException e) {
      System.out.println("Unable to initialize service: \n" + e.toString());
      return;
    }

    String serviceAccountEmail = serviceAccountName + "@" + projectId + ".iam.gserviceaccount.com";
    try {
      DisableServiceAccountRequest request = new DisableServiceAccountRequest();
      service
          .projects()
          .serviceAccounts()
          .disable("projects/-/serviceAccounts/" + serviceAccountEmail, request)
          .execute();

      System.out.println("Disabled service account: " + serviceAccountEmail);
    } catch (IOException e) {
      System.out.println("Unable to disable service account: \n" + e.toString());
    }
  }

  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 =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
    // Initialize the IAM service, which can be used to send requests to the IAM API.
    Iam service =
        new Iam.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                GsonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

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

To authenticate to IAM, set up Application Default Credentials. For more information, see Before you begin.

import os

from google.oauth2 import service_account  # type: ignore
import googleapiclient.discovery  # type: ignore

def disable_service_account(email: str) -> None:
    """Disables a service account."""

    credentials = service_account.Credentials.from_service_account_file(
        filename=os.environ["GOOGLE_APPLICATION_CREDENTIALS"],
        scopes=["https://www.googleapis.com/auth/cloud-platform"],
    )

    service = googleapiclient.discovery.build("iam", "v1", credentials=credentials)

    service.projects().serviceAccounts().disable(
        name="projects/-/serviceAccounts/" + email
    ).execute()

    print("Disabled service account :" + email)

REST

The serviceAccounts.disable method immediately disables a service account.

Before using any of the request data, make the following replacements:

  • PROJECT_ID: Your Google Cloud project ID. Project IDs are alphanumeric strings, like my-project.
  • SA_ID: The ID of your service account. This can either be the service account's email address in the form SA_NAME@PROJECT_ID.iam.gserviceaccount.com, or the service account's unique numeric ID.

HTTP method and URL:

POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_ID:disable

To send your request, expand one of these options:

If successful, the response body will be empty.

Enable a service account

After enabling a disabled service account, applications will regain access to Google Cloud resources through that service account.

You can enable a disabled service account whenever you need to. If you attempt to enable an already enabled service account, it will have no effect.

Console

  1. In the Google Cloud console, go to the Service accounts page.

    Go to Service accounts

  2. Select a project.

  3. Click the name of the service account that you want to enable.

  4. Under Service account status, click Enable service account, then click Enable to confirm the change.

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. Execute the gcloud iam service-accounts enable command to enable a service account.

    Command:

    gcloud iam service-accounts enable SA_NAME@PROJECT_ID.iam.gserviceaccount.com

    Output:

    Enabled service account SA_NAME@PROJECT_ID.iam.gserviceaccount.com

C++

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

To authenticate to IAM, set up Application Default Credentials. For more information, see Before you begin.

namespace iam = ::google::cloud::iam_admin_v1;
[](std::string const& name) {
  iam::IAMClient client(iam::MakeIAMConnection());
  google::iam::admin::v1::EnableServiceAccountRequest request;
  request.set_name(name);
  auto response = client.EnableServiceAccount(request);
  if (!response.ok()) throw std::runtime_error(response.message());
  std::cout << "ServiceAccount successfully enabled.\n";
}

C#

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

To authenticate to IAM, set up Application Default Credentials. For more information, see Before you begin.


using System;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Iam.v1;
using Google.Apis.Iam.v1.Data;

public partial class ServiceAccounts
{
    public static void EnableServiceAccount(string email)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var request = new EnableServiceAccountRequest();

        string resource = "projects/-/serviceAccounts/" + email;
        service.Projects.ServiceAccounts.Enable(request, resource).Execute();
        Console.WriteLine("Enabled service account: " + email);
    }
}

Go

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

To authenticate to IAM, set up Application Default Credentials. For more information, see Before you begin.

import (
	"context"
	"fmt"
	"io"

	iam "google.golang.org/api/iam/v1"
)

// enableServiceAccount enables a service account.
func enableServiceAccount(w io.Writer, email string) error {
	// email:= service-account@your-project.iam.gserviceaccount.com
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return fmt.Errorf("iam.NewService: %w", err)
	}

	request := &iam.EnableServiceAccountRequest{}
	_, err = service.Projects.ServiceAccounts.Enable("projects/-/serviceAccounts/"+email, request).Do()
	if err != nil {
		return fmt.Errorf("Projects.ServiceAccounts.Enable: %w", err)
	}
	fmt.Fprintf(w, "Enabled service account: %v", email)
	return nil
}

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 Before you begin.

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.EnableServiceAccountRequest;
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 EnableServiceAccount {

  // Enables a service account.
  public static void enableServiceAccount(String projectId, String serviceAccountName) {
    // String projectId = "my-project-id";
    // String serviceAccountName = "my-service-account-name";

    Iam service = null;
    try {
      service = initService();
    } catch (IOException | GeneralSecurityException e) {
      System.out.println("Unable to initialize service: \n" + e.toString());
      return;
    }

    String serviceAccountEmail = serviceAccountName + "@" + projectId + ".iam.gserviceaccount.com";
    try {
      EnableServiceAccountRequest request = new EnableServiceAccountRequest();
      service
          .projects()
          .serviceAccounts()
          .enable("projects/-/serviceAccounts/" + serviceAccountEmail, request)
          .execute();

      System.out.println("Enabled service account: " + serviceAccountEmail);
    } catch (IOException e) {
      System.out.println("Unable to enable service account: \n" + e.toString());
    }
  }

  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 =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
    // Initialize the IAM service, which can be used to send requests to the IAM API.
    Iam service =
        new Iam.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                GsonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

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

To authenticate to IAM, set up Application Default Credentials. For more information, see Before you begin.

import os

from google.oauth2 import service_account  # type: ignore
import googleapiclient.discovery  # type: ignore

def enable_service_account(email: str) -> None:
    """Enables a service account."""

    credentials = service_account.Credentials.from_service_account_file(
        filename=os.environ["GOOGLE_APPLICATION_CREDENTIALS"],
        scopes=["https://www.googleapis.com/auth/cloud-platform"],
    )

    service = googleapiclient.discovery.build("iam", "v1", credentials=credentials)

    service.projects().serviceAccounts().enable(
        name="projects/-/serviceAccounts/" + email
    ).execute()

    print("Enabled service account :" + email)

REST

The serviceAccounts.enable method enables a previously disabled service account.

Before using any of the request data, make the following replacements:

  • PROJECT_ID: Your Google Cloud project ID. Project IDs are alphanumeric strings, like my-project.
  • SA_ID: The ID of your service account. This can either be the service account's email address in the form SA_NAME@PROJECT_ID.iam.gserviceaccount.com, or the service account's unique numeric ID.

HTTP method and URL:

POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_ID:enable

To send your request, expand one of these options:

If successful, the response body will be empty.

What's next

Try it for yourself

If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.

Get started for free