Disable and enable service accounts

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

Before you begin

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 to projects, folders, and organizations.

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 Trusted Cloud resources through that service account. If you disable the default Compute Engine service account, 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 Trusted 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 Trusted Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Trusted 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.s3ns-system.iam.gserviceaccount.com

    Output:

    Disabled service account SA_NAME@PROJECT_ID.s3ns-system.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.

Before running code samples, set the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable to s3nsapis.fr.

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.

Before running code samples, set the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable to s3nsapis.fr.


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.

Before running code samples, set the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable to s3nsapis.fr.

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.

Before running code samples, set the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable to s3nsapis.fr.

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

public class DisableServiceAccount {

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

    disableServiceAccount(projectId, serviceAccountName);
  }

  // Disables a service account.
  public static void disableServiceAccount(String projectId, String accountName)
          throws IOException {
    String email = String.format("%s@%s.iam.gserviceaccount.com", accountName, projectId);

    // 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.disableServiceAccount(DisableServiceAccountRequest.newBuilder()
              .setName(String.format("projects/%s/serviceAccounts/%s", projectId, email))
              .build());

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

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.

Before running code samples, set the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable to s3nsapis.fr.

import time

from google.cloud import iam_admin_v1
from google.cloud.iam_admin_v1 import types


def disable_service_account(project_id: str, account: str) -> types.ServiceAccount:
    """Disables a service account.

    project_id: ID or number of the Google Cloud project you want to use.
    account: ID or email which is unique identifier of the service account.
    """

    iam_admin_client = iam_admin_v1.IAMClient()
    request = types.DisableServiceAccountRequest()
    name = f"projects/{project_id}/serviceAccounts/{account}"
    request.name = name

    iam_admin_client.disable_service_account(request=request)
    time.sleep(5)  # waiting to make sure changes applied

    get_request = types.GetServiceAccountRequest()
    get_request.name = name

    service_account = iam_admin_client.get_service_account(request=get_request)
    if service_account.disabled:
        print(f"Disabled service account: {account}")
    return service_account

REST

The serviceAccounts.disable method immediately disables a service account.

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

  • PROJECT_ID: Your Trusted 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.s3ns-system.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 Trusted 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 Trusted 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 Trusted Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Trusted 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.s3ns-system.iam.gserviceaccount.com

    Output:

    Enabled service account SA_NAME@PROJECT_ID.s3ns-system.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.

Before running code samples, set the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable to s3nsapis.fr.

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.

Before running code samples, set the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable to s3nsapis.fr.


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.

Before running code samples, set the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable to s3nsapis.fr.

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.

Before running code samples, set the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable to s3nsapis.fr.

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


public class EnableServiceAccount {

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

    enableServiceAccount(projectId, serviceAccountName);
  }

  // Enables a service account.
  public static void enableServiceAccount(String projectId, String accountName)
          throws IOException {
    String email = String.format("%s@%s.iam.gserviceaccount.com", accountName, projectId);

    // 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.enableServiceAccount(EnableServiceAccountRequest.newBuilder()
              .setName(String.format("projects/%s/serviceAccounts/%s", projectId, email))
              .build());

      System.out.println("Enabled service account: " + email);
    }
  }
}

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.

Before running code samples, set the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable to s3nsapis.fr.

import time

from google.cloud import iam_admin_v1
from google.cloud.iam_admin_v1 import types


def enable_service_account(project_id: str, account: str) -> types.ServiceAccount:
    """Enables a service account.

    project_id: ID or number of the Google Cloud project you want to use.
    account: ID or email which is unique identifier of the service account.
    """

    iam_admin_client = iam_admin_v1.IAMClient()
    request = types.EnableServiceAccountRequest()
    name = f"projects/{project_id}/serviceAccounts/{account}"
    request.name = name

    iam_admin_client.enable_service_account(request=request)
    time.sleep(5)  # waiting to make sure changes applied

    get_request = types.GetServiceAccountRequest()
    get_request.name = name

    service_account = iam_admin_client.get_service_account(request=get_request)
    if not service_account.disabled:
        print(f"Enabled service account: {account}")
    return service_account

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 Trusted 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.s3ns-system.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