创建和管理服务帐号

本页面介绍了如何使用 Identity and Access Management (IAM) API、Google Cloud Console 和 gcloud 命令行工具创建和管理服务帐号。

默认情况下,每个项目最多可以有 100 个控制对资源的访问权限的服务帐号。如有必要,您可以申请增加配额。详细了解配额和限制

准备工作

所需权限

要允许用户管理服务帐号,请授予以下角色之一:

  • Service Account User (roles/iam.serviceAccountUser):包括列出服务帐号、获取服务帐号的详细信息以及模拟服务帐号的权限。
  • Service Account Admin (roles/iam.serviceAccountAdmin):包括列出服务帐号和获取服务帐号的详细信息的权限。此外,还包括创建、更新和删除服务帐号的权限,以及查看或更改服务帐号的 IAM 政策的权限。

如需详细了解这些角色,请参阅服务帐号角色

IAM 基本角色也具有管理服务帐号的权限。您不应在生产环境中授予基本角色,但可以在开发或测试环境中授予这些角色。

创建服务帐号

创建服务帐号时,您必须提供字母数字 ID(在下面的示例中为 SA_NAME),例如 my-service-account。ID 必须介于 6 到 30 个字符之间,且可以包含小写字母数字字符和短划线。在服务帐号创建完毕后,无法再更改其名称。

服务帐号的名称将显示在创建过程中预配的电子邮件地址中,格式为 SA_NAME@PROJECT_ID.iam.gserviceaccount.com

每个服务帐号还有一个自动生成的永久性唯一数字 ID。

您还可以在创建服务帐号时提供如下信息:

  • SA_DESCRIPTION 是可选的服务帐号说明。
  • SA_DISPLAY_NAME 是服务帐号的易记名称。
  • PROJECT_ID 是您的 Google Cloud 项目的 ID。

如需创建服务帐号,用户必须至少被授予 Service Account Admin 角色 (roles/iam.serviceAccountAdmin) 或 Editor 基本角色 (roles/editor)。您不应在生产环境中授予基本角色,但可以在开发或测试环境中授予这些角色。

创建服务帐号后,您可能需要等待 60 秒或更长时间才能使用该服务帐号。如果您在创建服务帐号后立即尝试使用该帐号,但收到错误消息,则可以使用指数退避算法重试请求

控制台

  1. In the Cloud Console, go to the Create service account page.

    Go to Create service account
  2. Select a project.
  3. Enter a service account name to display in the Cloud Console.

    The Cloud Console generates a service account ID based on this name. Edit the ID if necessary. You cannot change the ID later.

  4. Optional: Enter a description of the service account.
  5. If you do not want to set access controls now, click Done to finish creating the service account.

    To set access controls now, click Create and continue and continue to the next step.

  6. Optional: Choose one or more IAM roles to grant to the service account on the project.
  7. When you are done adding roles, click Continue.
  8. Optional: In the Service account users role field, add members that can impersonate the service account.
  9. Optional: In the Service account admins role field, add members that can manage the service account.
  10. Click Done to finish creating the service account.

gcloud

    To create the service account, run the gcloud iam service-accounts create command:

    gcloud iam service-accounts create SERVICE_ACCOUNT_ID \
        --description="DESCRIPTION" \
        --display-name="DISPLAY_NAME"

    Replace the following values:

    • SERVICE_ACCOUNT_ID: The ID for the service account.
    • DESCRIPTION: Optional. A description of the service account.
    • DISPLAY_NAME: A service account name to display in the Cloud Console.

    Optional: To grant your service account an IAM role on your project, run the gcloud projects add-iam-policy-binding command:

    gcloud projects add-iam-policy-binding PROJECT_ID \
        --member="serviceAccount:SERVICE_ACCOUNT_ID@PROJECT_ID.iam.gserviceaccount.com" \
        --role="ROLE_NAME"

    Replace the following values:

    • PROJECT_ID: The project id.
    • SERVICE_ACCOUNT_ID: The service account ID.
    • ROLE_NAME: A role name, such as roles/compute.osLogin.

    Optional: To allow users to impersonate the service account, run the gcloud iam service-accounts add-iam-policy-binding command to grant a user the Service Account User role (roles/iam.serviceAccountUser) on the service account:

    gcloud iam service-accounts add-iam-policy-binding \
        SERVICE_ACCOUNT_ID@PROJECT_ID.iam.gserviceaccount.com \
        --member="user:USER_EMAIL" \
        --role="roles/iam.serviceAccountUser"

    Replace the following values:

    • PROJECT_ID: The project ID.
    • SERVICE_ACCOUNT_ID: The service account ID.
    • USER_EMAIL: The email address for the user.

REST

serviceAccounts.create 方法可创建服务帐号。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目 ID。 项目 ID 是字母数字字符串,例如 my-project
  • SA_NAME:您的服务帐号的字母数字 ID。此名称必须介于 6 到 30 个字符之间,且可以包含小写字母数字字符和短划线。
  • SA_DESCRIPTION:可选。服务帐号说明。
  • SA_DISPLAY_NAME:服务帐号的人类可读名称。

HTTP 方法和网址:

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

请求 JSON 正文:

{
  "accountId": "SA_NAME",
  "serviceAccount": {
    "description": "SA_DESCRIPTION",
    "displayName": "SA_DISPLAY_NAME"
  }
}

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/my-project/serviceAccounts/my-service-account@my-project.iam.gserviceaccount.com",
  "projectId": "my-project",
  "uniqueId": "123456789012345678901",
  "email": "my-service-account@my-project.iam.gserviceaccount.com",
  "displayName": "My service account",
  "etag": "BwUp3rVlzes=",
  "description": "A service account for running jobs in my project",
  "oauth2ClientId": "987654321098765432109"
}

C++

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM C++ API 参考文档

namespace iam = ::google::cloud::iam;
[](std::string const& project_id, std::string const& account_id,
   std::string const& display_name, std::string const& description) {
  iam::IAMClient client(iam::MakeIAMConnection());
  google::iam::admin::v1::ServiceAccount service_account;
  service_account.set_display_name(display_name);
  service_account.set_description(description);
  auto response = client.CreateServiceAccount("projects/" + project_id,
                                              account_id, service_account);
  if (!response) throw std::runtime_error(response.status().message());
  std::cout << "ServiceAccount successfully created: "
            << response->DebugString() << "\n";
}

C#

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM C# API 参考文档


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

public partial class ServiceAccounts
{
    public static ServiceAccount CreateServiceAccount(string projectId,
        string name, string displayName)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var request = new CreateServiceAccountRequest
        {
            AccountId = name,
            ServiceAccount = new ServiceAccount
            {
                DisplayName = displayName
            }
        };
        var serviceAccount = service.Projects.ServiceAccounts.Create(
            request, "projects/" + projectId).Execute();
        Console.WriteLine("Created service account: " + serviceAccount.Email);
        return serviceAccount;
    }
}

Go

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Go API 参考文档

import (
	"context"
	"fmt"
	"io"

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

// createServiceAccount creates a service account.
func createServiceAccount(w io.Writer, projectID, name, displayName string) (*iam.ServiceAccount, error) {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return nil, fmt.Errorf("iam.NewService: %v", err)
	}

	request := &iam.CreateServiceAccountRequest{
		AccountId: name,
		ServiceAccount: &iam.ServiceAccount{
			DisplayName: displayName,
		},
	}
	account, err := service.Projects.ServiceAccounts.Create("projects/"+projectID, request).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.ServiceAccounts.Create: %v", err)
	}
	fmt.Fprintf(w, "Created service account: %v", account)
	return account, nil
}

Java

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Java API 参考文档

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.IamScopes;
import com.google.api.services.iam.v1.model.CreateServiceAccountRequest;
import com.google.api.services.iam.v1.model.ServiceAccount;
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 CreateServiceAccount {

  // Creates a service account.
  public static void createServiceAccount(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;
    }

    try {
      ServiceAccount serviceAccount = new ServiceAccount();
      serviceAccount.setDisplayName("your-display-name");
      CreateServiceAccountRequest request = new CreateServiceAccountRequest();
      request.setAccountId(serviceAccountName);
      request.setServiceAccount(serviceAccount);

      serviceAccount =
          service.projects().serviceAccounts().create("projects/" + projectId, request).execute();

      System.out.println("Created service account: " + serviceAccount.getEmail());
    } catch (IOException e) {
      System.out.println("Unable to create 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(),
                JacksonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Python API 参考文档

import os

from google.oauth2 import service_account
import googleapiclient.discovery

def create_service_account(project_id, name, display_name):
    """Creates 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)

    my_service_account = service.projects().serviceAccounts().create(
        name='projects/' + project_id,
        body={
            'accountId': name,
            'serviceAccount': {
                'displayName': display_name
            }
        }).execute()

    print('Created service account: ' + my_service_account['email'])
    return my_service_account

在创建服务帐号后,为服务帐号授予一个或多个角色,以使其代表您执行操作。

此外,如果服务帐号需要访问其他项目中的资源,则您通常必须在创建服务帐号的项目中为这些资源启用 API

列出服务帐号

列出服务帐号时,您可以指定参数来限制要包含在响应中的服务帐号数量。然后,您可以在后续请求中使用 ListServiceAccountsResponse.next_page_token 来列出其余的服务帐号。

使用此方法可审核服务帐号和密钥,或者构建用于管理服务帐号的自定义工具。

要列出服务帐号,必须至少为用户授予 Service Account User 角色 (roles/iam.serviceAccountUser) 或 Viewer 基本角色 (roles/viewer)。

控制台

  1. 在 Cloud Console 中,转到服务帐号页面。

    转到“服务帐号”

  2. 选择一个项目。

    服务帐号页面列出了您所选项目中所有用户管理的服务帐号。 该页面未列出 Google 管理的服务帐号

gcloud

执行 gcloud iam service-accounts list 命令可列出项目中的所有服务帐号。

命令:

gcloud iam service-accounts list

输出列出了项目中的所有服务帐号:

NAME                    EMAIL
SA_DISPLAY_NAME_1       SA_NAME_1@PROJECT_ID.iam.gserviceaccount.com
SA_DISPLAY_NAME_2       SA_NAME_2@PROJECT_ID.iam.gserviceaccount.com

REST

serviceAccounts.list 方法可列出项目中的每个服务帐号。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目 ID。 项目 ID 是字母数字字符串,例如 my-project

HTTP 方法和网址:

GET https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "accounts": [
    {
      "name": "projects/my-project/serviceAccounts/sa-1@my-project.iam.gserviceaccount.com",
      "projectId": "my-project",
      "uniqueId": "123456789012345678901",
      "email": "sa-1@my-project.iam.gserviceaccount.com",
      "description": "My first service account",
      "displayName": "Service account 1",
      "etag": "BwUpTsLVUkQ=",
      "oauth2ClientId": "987654321098765432109"
    },
    {
      "name": "projects/my-project/serviceAccounts/sa-2@my-project.iam.gserviceaccount.com",
      "projectId": "my-project",
      "uniqueId": "234567890123456789012",
      "email": "sa-2@my-project.iam.gserviceaccount.com",
      "description": "My second service account",
      "displayName": "Service account 2",
      "etag": "UkQpTwBVUsL=",
      "oauth2ClientId": "876543210987654321098"
    }
  ]
}

C++

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM C++ API 参考文档

namespace iam = ::google::cloud::iam;
[](std::string const& project_id) {
  iam::IAMClient client(iam::MakeIAMConnection());
  int count = 0;
  for (auto const& sa :
       client.ListServiceAccounts("projects/" + project_id)) {
    if (!sa) throw std::runtime_error(sa.status().message());
    std::cout << "ServiceAccount successfully retrieved: " << sa->name()
              << "\n";
    ++count;
  }
  if (count == 0) {
    std::cout << "No service accounts found in project: " << project_id
              << "\n";
  }
}

C#

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM C# API 参考文档


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

public partial class ServiceAccounts
{
    public static IList<ServiceAccount> ListServiceAccounts(string projectId)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var response = service.Projects.ServiceAccounts.List(
            "projects/" + projectId).Execute();
        foreach (ServiceAccount account in response.Accounts)
        {
            Console.WriteLine("Name: " + account.Name);
            Console.WriteLine("Display Name: " + account.DisplayName);
            Console.WriteLine("Email: " + account.Email);
            Console.WriteLine();
        }
        return response.Accounts;
    }
}

Go

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Go API 参考文档

import (
	"context"
	"fmt"
	"io"

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

// listServiceAccounts lists a project's service accounts.
func listServiceAccounts(w io.Writer, projectID string) ([]*iam.ServiceAccount, error) {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return nil, fmt.Errorf("iam.NewService: %v", err)
	}

	response, err := service.Projects.ServiceAccounts.List("projects/" + projectID).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.ServiceAccounts.List: %v", err)
	}
	for _, account := range response.Accounts {
		fmt.Fprintf(w, "Listing service account: %v\n", account.Name)
	}
	return response.Accounts, nil
}

Java

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Java API 参考文档

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.IamScopes;
import com.google.api.services.iam.v1.model.ListServiceAccountsResponse;
import com.google.api.services.iam.v1.model.ServiceAccount;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;

public class ListServiceAccounts {

  // Lists all service accounts for the current project.
  public static void listServiceAccounts(String projectId) {
    // String projectId = "my-project-id"

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

    try {
      ListServiceAccountsResponse response =
          service.projects().serviceAccounts().list("projects/" + projectId).execute();
      List<ServiceAccount> serviceAccounts = response.getAccounts();

      for (ServiceAccount account : serviceAccounts) {
        System.out.println("Name: " + account.getName());
        System.out.println("Display Name: " + account.getDisplayName());
        System.out.println("Email: " + account.getEmail());
        System.out.println();
      }
    } catch (IOException e) {
      System.out.println("Unable to list service accounts: \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(),
                JacksonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Python API 参考文档

import os

from google.oauth2 import service_account
import googleapiclient.discovery

def list_service_accounts(project_id):
    """Lists all service accounts for the current project."""

    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_accounts = service.projects().serviceAccounts().list(
        name='projects/' + project_id).execute()

    for account in service_accounts['accounts']:
        print('Name: ' + account['name'])
        print('Email: ' + account['email'])
        print(' ')
    return service_accounts

更新服务帐号

通常可通过服务帐号的显示名(易记名称)和说明获知有关该服务帐号的额外信息,例如服务帐号的用途或该帐号的联系人。

要更新服务帐号的名称或说明,必须至少为用户授予 Service Account Admin 角色 (roles/iam.serviceAccountAdmin) 或 Editor 基本角色 (roles/editor)。

控制台

  1. 在 Cloud Console 中,转到服务帐号页面。

    转到“服务帐号”

  2. 选择一个项目。

  3. 点击要重命名的服务帐号的电子邮件地址。

  4. 名称框中输入新名称,然后点击保存

gcloud

执行 gcloud iam service-accounts update 命令可更新服务帐号。

命令:

gcloud iam service-accounts update \
    SA_NAME@PROJECT_ID.iam.gserviceaccount.com \
    --description="UPDATED_SA_DESCRIPTION" \
    --display-name="UPDATED_DISPLAY_NAME"

输出是重命名后的服务帐号:

description: UPDATED_SA_DESCRIPTION
displayName: UPDATED_DISPLAY_NAME
name: projects/PROJECT_ID/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com

REST

serviceAccounts.patch 方法可更新服务帐号。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目 ID。 项目 ID 是字母数字字符串,例如 my-project
  • SA_ID:您的服务帐号的 ID。此 ID 可以是服务帐号的电子邮件地址(格式为 SA_NAME@PROJECT_ID.iam.gserviceaccount.com)或服务帐号的唯一数字 ID。
  • SA_NAME:您的服务帐号的字母数字 ID。此名称必须介于 6 到 30 个字符之间,且可以包含小写字母数字字符和短划线。
  • 请至少替换以下其中一项:
    • UPDATED_DISPLAY_NAME:您的服务帐号的新显示名。
    • UPDATED_DESCRIPTION:您的服务帐号的新说明。

HTTP 方法和网址:

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

请求 JSON 正文:

{
  "serviceAccount": {
    "email": "SA_NAME@PROJECT_ID.iam.gserviceaccount.com",
    "displayName": "UPDATED_DISPLAY_NAME",
    "description": "UPDATED_DESCRIPTION"
  },
  "updateMask": "displayName,description"
}

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/my-project/serviceAccounts/my-service-account@my-project.iam.gserviceaccount.com",
  "displayName": "My updated service account",
  "description": "An updated description of my service account"
}

C++

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM C++ API 参考文档

namespace iam = ::google::cloud::iam;
[](std::string const& name, std::string const& display_name) {
  iam::IAMClient client(iam::MakeIAMConnection());
  google::iam::admin::v1::PatchServiceAccountRequest request;
  google::iam::admin::v1::ServiceAccount service_account;
  service_account.set_name(name);
  service_account.set_display_name(display_name);
  google::protobuf::FieldMask update_mask;
  *update_mask.add_paths() = "display_name";
  *request.mutable_service_account() = service_account;
  *request.mutable_update_mask() = update_mask;
  auto response = client.PatchServiceAccount(request);
  if (!response) throw std::runtime_error(response.status().message());
  std::cout << "ServiceAccount successfully updated: "
            << response->DebugString() << "\n";
}

C#

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM C# API 参考文档


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

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

        // First, get a ServiceAccount using List() or Get().
        string resource = "projects/-/serviceAccounts/" + email;
        var serviceAccount = service.Projects.ServiceAccounts.Get(resource)
            .Execute();
        // Then you can update the display name.
        serviceAccount.DisplayName = newDisplayName;
        serviceAccount = service.Projects.ServiceAccounts.Update(
            serviceAccount, resource).Execute();
        Console.WriteLine($"Updated display name for {serviceAccount.Email} " +
            "to: " + serviceAccount.DisplayName);
        return serviceAccount;
    }
}

Go

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Go API 参考文档

import (
	"context"
	"fmt"
	"io"

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

// renameServiceAccount renames a service account.
func renameServiceAccount(w io.Writer, email, newDisplayName string) (*iam.ServiceAccount, error) {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return nil, fmt.Errorf("iam.NewService: %v", err)
	}

	// First, get a ServiceAccount using List() or Get().
	resource := "projects/-/serviceAccounts/" + email
	serviceAccount, err := service.Projects.ServiceAccounts.Get(resource).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.ServiceAccounts.Get: %v", err)
	}
	// Then you can update the display name.
	serviceAccount.DisplayName = newDisplayName
	serviceAccount, err = service.Projects.ServiceAccounts.Update(resource, serviceAccount).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.ServiceAccounts.Update: %v", err)
	}

	fmt.Fprintf(w, "Updated service account: %v", serviceAccount.Email)
	return serviceAccount, nil
}

Java

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Java API 参考文档

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.IamScopes;
import com.google.api.services.iam.v1.model.ServiceAccount;
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 RenameServiceAccount {

  // Changes a service account's display name.
  public static void renameServiceAccount(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 {
      // First, get a service account using List() or Get()
      ServiceAccount serviceAccount =
          service
              .projects()
              .serviceAccounts()
              .get("projects/-/serviceAccounts/" + serviceAccountEmail)
              .execute();

      // Then you can update the display name
      serviceAccount.setDisplayName("your-new-display-name");
      serviceAccount =
          service
              .projects()
              .serviceAccounts()
              .update(serviceAccount.getName(), serviceAccount)
              .execute();

      System.out.println(
          "Updated display name for "
              + serviceAccount.getName()
              + " to: "
              + serviceAccount.getDisplayName());
    } catch (IOException e) {
      System.out.println("Unable to rename 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(),
                JacksonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Python API 参考文档

import os

from google.oauth2 import service_account
import googleapiclient.discovery

def rename_service_account(email, new_display_name):
    """Changes a service account's display name."""

    # First, get a service account using List() or Get()
    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)

    resource = 'projects/-/serviceAccounts/' + email

    my_service_account = service.projects().serviceAccounts().get(
        name=resource).execute()

    # Then you can update the display name
    my_service_account['displayName'] = new_display_name
    my_service_account = service.projects().serviceAccounts().update(
        name=resource, body=my_service_account).execute()

    print('Updated display name for {} to: {}'.format(
        my_service_account['email'], my_service_account['displayName']))
    return my_service_account

停用服务帐号

与删除服务帐号类似,当您停用服务帐号后,应用将无法再通过该服务帐号来访问 Google Cloud 资源。如果停用默认 App Engine 和 Compute Engine 服务帐号,实例将无法再访问项目中的资源。如果您尝试停用已停用的服务帐号,则操作无效。

与删除服务帐号不同的是,您可根据需要轻松重新启用已停用的服务帐号。我们建议在删除服务帐号之前,先执行停用,以防有关键应用正在使用该服务帐号。

要停用服务帐号,必须至少为用户授予 Service Account Admin 角色 (roles/iam.serviceAccountAdmin) 或 Editor 基本角色 (roles/editor)。

控制台

  1. 在 Cloud Console 中,转到服务帐号页面。

    转到“服务帐号”

  2. 选择一个项目。

  3. 点击要停用的服务帐号的名称。

  4. 服务帐号状态下,点击停用服务帐号,然后点击停用确认更改。

gcloud

执行 gcloud iam service-accounts disable 命令可停用服务帐号。

命令:

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

输出:

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

REST

serviceAccounts.disable 方法可立即停用服务帐号。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目 ID。 项目 ID 是字母数字字符串,例如 my-project
  • SA_ID:您的服务帐号的 ID。此 ID 可以是服务帐号的电子邮件地址(格式为 SA_NAME@PROJECT_ID.iam.gserviceaccount.com)或服务帐号的唯一数字 ID。

HTTP 方法和网址:

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

如需发送您的请求,请展开以下选项之一:

如果成功,则响应正文将为空。

C++

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM C++ API 参考文档

namespace iam = ::google::cloud::iam;
[](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#

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM C# API 参考文档


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

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Go API 参考文档

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: %v", err)
	}

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

Java

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Java API 参考文档

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
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(),
                JacksonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Python API 参考文档

import os

from google.oauth2 import service_account
import googleapiclient.discovery

def disable_service_account(email):
    """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)

启用服务帐号

启用已停用的服务帐号后,应用便能够重新通过该服务帐号访问 Google Cloud 资源。

您可以根据需要随时启用已停用的服务帐号。如果您尝试启用已启用的服务帐号,则操作无效。

要启用服务帐号,必须至少为用户授予 Service Account Admin 角色 (roles/iam.serviceAccountAdmin) 或 Editor 基本角色 (roles/editor)。

控制台

  1. 在 Cloud Console 中,转到服务帐号页面。

    转到“服务帐号”

  2. 选择一个项目。

  3. 点击要启用的服务帐号的名称。

  4. 服务帐号状态下,点击启用服务帐号,然后点击启用确认更改。

gcloud

执行 gcloud iam service-accounts enable 命令可启用服务帐号。

命令:

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

输出:

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

REST

serviceAccounts.enable 方法可启用先前停用的服务帐号。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目 ID。 项目 ID 是字母数字字符串,例如 my-project
  • SA_ID:您的服务帐号的 ID。此 ID 可以是服务帐号的电子邮件地址(格式为 SA_NAME@PROJECT_ID.iam.gserviceaccount.com)或服务帐号的唯一数字 ID。

HTTP 方法和网址:

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

如需发送您的请求,请展开以下选项之一:

如果成功,则响应正文将为空。

C++

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM C++ API 参考文档

namespace iam = ::google::cloud::iam;
[](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#

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM C# API 参考文档


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

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Go API 参考文档

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: %v", err)
	}

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

Java

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Java API 参考文档

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
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(),
                JacksonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Python API 参考文档

import os

from google.oauth2 import service_account
import googleapiclient.discovery

def enable_service_account(email):
    """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)

删除服务帐号

您删除服务帐号后,应用将无法再通过该服务帐号访问 Google Cloud 资源。如果删除默认的 App Engine 和 Compute Engine 服务帐号,实例将无法再访问项目中的资源。

请谨慎执行删除;在删除之前,请确保您的关键应用不再使用该服务帐号。如果您不确定某个服务帐号是否仍在使用,我们建议先停用该服务帐号,然后再执行删除。如果已停用的服务帐号仍在使用,可以轻松将其重新启用。

如果您删除服务帐号,然后创建一个具有相同名称的新服务帐号,新服务帐号将被视为单独的身份;它不会继承那些授予已删除的服务帐号的角色。相反,如果您删除某个服务帐号,然后取消删除,那么该服务帐号的身份不会更改,并且服务帐号会保留其角色。

删除服务帐号时,其角色绑定不会立即移除;它们将在 60 天内自动从系统中清除。

已删除的服务帐号不计入您的服务帐号配额

要删除服务帐号,必须至少为用户授予 Service Account Admin 角色 (roles/iam.serviceAccountAdmin) 或 Editor 基本角色 (roles/editor)。

控制台

  1. 在 Cloud Console 中,转到服务帐号页面。

    转到“服务帐号”

  2. 选择一个项目。

  3. 选择要删除的服务帐号,然后点击删除

gcloud

执行 gcloud iam service-accounts delete 命令可删除服务帐号。

命令:

gcloud iam service-accounts delete \
    SA_NAME@PROJECT_ID.iam.gserviceaccount.com

输出:

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

REST

serviceAccounts.delete 方法可删除服务帐号。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目 ID。 项目 ID 是字母数字字符串,例如 my-project
  • SA_ID:您的服务帐号的 ID。此 ID 可以是服务帐号的电子邮件地址(格式为 SA_NAME@PROJECT_ID.iam.gserviceaccount.com)或服务帐号的唯一数字 ID。

HTTP 方法和网址:

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

如需发送您的请求,请展开以下选项之一:

如果成功,则响应正文将为空。

C++

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM C++ API 参考文档

namespace iam = ::google::cloud::iam;
[](std::string const& name) {
  iam::IAMClient client(iam::MakeIAMConnection());
  auto response = client.DeleteServiceAccount(name);
  if (!response.ok()) throw std::runtime_error(response.message());
  std::cout << "ServiceAccount successfully deleted.\n";
}

C#

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM C# API 参考文档


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

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

        string resource = "projects/-/serviceAccounts/" + email;
        service.Projects.ServiceAccounts.Delete(resource).Execute();
        Console.WriteLine("Deleted service account: " + email);
    }
}

Go

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Go API 参考文档

import (
	"context"
	"fmt"
	"io"

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

// deleteServiceAccount deletes a service account.
func deleteServiceAccount(w io.Writer, email string) error {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return fmt.Errorf("iam.NewService: %v", err)
	}

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

Java

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Java API 参考文档

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.IamScopes;
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 DeleteServiceAccount {

  // Deletes a service account.
  public static void deleteServiceAccount(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 {
      service
          .projects()
          .serviceAccounts()
          .delete("projects/-/serviceAccounts/" + serviceAccountEmail)
          .execute();

      System.out.println("Deleted service account: " + serviceAccountEmail);
    } catch (IOException e) {
      System.out.println("Unable to delete 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(),
                JacksonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Python API 参考文档

import os

from google.oauth2 import service_account
import googleapiclient.discovery

def delete_service_account(email):
    """Deletes 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().delete(
        name='projects/-/serviceAccounts/' + email).execute()

    print('Deleted service account: ' + email)

恢复删除的服务帐号

在某些情况下,您可以使用 undelete 命令恢复已删除的服务帐号。如果已删除的服务帐号满足以下条件,则通常可以恢复该服务帐号:

  • 服务帐号删除的时间不超过 30 天。

    30 天后,IAM 会永久移除该服务帐号。服务帐号被永久移除后,即使您提交支持请求,Google Cloud 也无法将其恢复。

  • 现有服务帐号与已删除的服务帐号的名称不同。

    例如,假设您意外删除了服务帐号 my-service-account@project-id.iam.gserviceaccount.com。您仍需要具有此名称的服务帐号,因此您创建了一个具有相同名称的新服务帐号 my-service-account@project-id.iam.gserviceaccount.com

    新服务帐号不会继承已删除的服务帐号的权限。实际上,它与已删除的服务帐号完全没有关系。但是,您无法恢复删除的原始服务帐号,因为新服务帐号使用了与它相同的名称。

    要解决此问题,请删除新服务帐号,然后尝试恢复删除的原始服务帐号。

如果您无法恢复已删除的服务帐号,可以创建一个具有相同名称的新服务帐号;撤消已删除的服务帐号中的所有角色;然后向新服务帐号授予相同的角色。如需了解详情,请参阅包含已删除主帐号的政策

查找已删除服务帐号的数字 ID

当您恢复删除的服务帐号时,必须提供其数字 ID。数字 ID 是唯一标识服务帐号的 21 位数字,例如 123456789012345678901。例如,如果您删除某一服务帐号,然后创建一个具有相同名称的新服务帐号,原始服务帐号和新服务帐号将具有不同的数字 ID。

如果您知道某项 IAM 政策中的绑定包含已删除的服务帐号,则可以获取该政策,然后在其中找到相应的数字 ID。数字 ID 附加在已删除的服务帐号的名称的后面。例如,在以下政策中,已删除的服务帐号的数字 ID 为 123456789012345678901

{
  "version": 1,
  "etag": "BwUjMhCsNvY=",
  "bindings": [
    {
      "members": [
        "deleted:serviceAccount:my-service-account@project-id.iam.gserviceaccount.com?uid=123456789012345678901"
      ],
      "role": "roles/iam.serviceAccountUser"
    },
  ]
}

数字 ID 仅附加到已删除主帐号的名称中。

或者,您可以在审核日志中搜索删除了服务帐号的 DeleteServiceAccount 操作:

  1. 在 Cloud Console 中,转到日志浏览器页面。

    转到日志浏览器

  2. 在查询编辑器中输入以下查询,将 SERVICE_ACCOUNT_EMAIL 替换为您的服务帐号的电子邮件地址(例如 my-service-account@project-id.iam.gserviceaccount.com):

    resource.type="service_account"
    resource.labels.email_id="SERVICE_ACCOUNT_EMAIL"
    "DeleteServiceAccount"
    
  3. 如果服务帐号已被删除超过 1 小时,请点击 schedule 过去 1 小时,从下拉列表中选择更长的时间段,然后点击应用

  4. 点击运行查询。日志查看器会显示具有您指定的名称的影响服务帐号的 DeleteServiceAccount 操作。

  5. 执行以下任一操作,找到并记下已删除服务帐号的数字 ID:

    • 如果搜索结果仅包含一项 DeleteServiceAccount 操作,请在日志字段窗格的唯一 ID 字段中查找数字 ID。

    • 如果搜索结果显示多个日志,请执行以下操作:

      1. 找到正确的日志条目。如需查找正确的日志条目,请点击日志条目旁边的 展开箭头。查看日志条目的详细信息,并确定日志条目是否显示您要撤消的操作。重复此过程,直至找到正确的日志条目。

      2. 在正确的日志条目中,找到服务帐号的数字 ID。如需查找数字 ID,请展开日志条目的 protoPayload 字段,然后找到 resourceName 字段。

        数字 ID 是 resourceName 字段中 serviceAccounts 之后的所有内容。

按数字 ID 恢复删除的服务帐号

找到已删除的服务帐号的数字 ID 后,您可以尝试恢复删除的服务帐号。

gcloud

执行 gcloud beta iam service-accounts undelete 命令可恢复删除的服务帐号。

命令:

gcloud beta iam service-accounts undelete ACCOUNT_ID

输出:

restoredAccount:
  email: SA_NAME@PROJECT_ID.iam.gserviceaccount.com
  etag: BwWWE7zpApg=
  name: projects/PROJECT_ID/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com
  oauth2ClientId: '123456789012345678901'
  projectId: PROJECT_ID
  uniqueId: 'ACCOUNT_ID'

REST

serviceAccounts.undelete 方法可恢复已删除的服务帐号。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目 ID。 项目 ID 是字母数字字符串,例如 my-project
  • SA_NUMERIC_ID:服务帐号的唯一数字 ID。

HTTP 方法和网址:

POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_NUMERIC_ID:undelete

如需发送您的请求,请展开以下选项之一:

如果可以恢复删除的帐号,您会收到一个 200 OK 响应代码,其中包含已恢复服务帐号的详细信息,如下所示:

{
  "restoredAccount": {
    "name": "projects/my-project/serviceAccounts/my-service-account@my-project.iam.gserviceaccount.com",
    "projectId": "my-project",
    "uniqueId": "123456789012345678901",
    "email": "my-service-account@my-project.iam.gserviceaccount.com",
    "displayName": "My service account",
    "etag": "BwUp3rVlzes=",
    "description": "A service account for running jobs in my project",
    "oauth2ClientId": "987654321098765432109"
  }
}

后续步骤

自行试用

如果您是 Google Cloud 新手,请创建一个帐号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。

免费开始使用