创建和管理服务帐号

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

当您创建新的 Cloud 项目时,Google Cloud 会自动在该项目下创建一个 Compute Engine 服务帐号和一个 App Engine 服务帐号。您最多可以为项目创建 98 个额外的服务帐号,以控制对资源的访问权限。

准备工作

所需权限

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

  • Service Account User (roles/iam.serviceAccountUser):授予获取、列出或模拟服务帐号的权限。
  • Service Account Admin (roles/iam.serviceAccountAdmin):涵盖 Service Account User 权限,另外还授予创建、更新、删除服务帐号的权限,以及设置或获取服务帐号的 Cloud IAM 政策的权限。

Cloud IAM 原初角色还包含管理服务帐号的权限。不过,我们建议授予上述预定义角色之一,以防止对其他 Google Cloud 资源的不必要访问。如需详细了解这些角色,请参阅服务帐号角色列表

创建服务帐号

创建服务帐号与为项目添加成员类似,只不过服务帐号为您应用所有,而非属于某个最终用户。

在下面的示例中,[SA-NAME] 是您提供的服务帐号的名称,例如 my-service-account。此为唯一标识符,并将出现在创建过程中预配的服务帐号电子邮件地址中,例如 my-service-account@project-id.iam.gserviceaccount.com。您还可使用该名称通过其他 API 来更新服务帐号。该名称一旦创建便无法更改。

另外请提供以下值:

  • [SA-DESCRIPTION] 是可选的服务帐号说明
  • [SA-DISPLAY-NAME] 是服务帐号的易记名称
  • [PROJECT-ID] 是您的 Google Cloud 项目 ID

要创建服务帐号,用户必须至少被授予 Service Account Admin 角色 (roles/iam.serviceAccountAdmin) 或 Editor 原初角色 (roles/editor)。

控制台

  1. 在 Cloud Console 中打开服务帐号页面。

    打开“服务帐号”页面

  2. 点击选择项目,然后选择您的项目并点击打开

  3. 点击创建服务帐号

  4. 输入服务帐号名称(易记的显示名)、可选说明,并选择您希望授予服务帐号的角色,然后点击保存

gcloud 命令

执行 gcloud iam service-accounts create 命令可创建服务帐号。

命令:

gcloud iam service-accounts create [SA-NAME] \
        --description "[SA-DESCRIPTION]" \
        --display-name "[SA-DISPLAY-NAME]"
    

输出内容包括服务帐号的名称:

Created service account [SA-NAME].
    

REST API

调用 serviceAccounts.create() 可创建服务帐号。

POST https://iam.googleapis.com/v1/projects/[PROJECT-ID]/serviceAccounts
    

请求正文应包含服务帐号的属性。

{
        "accountId": "[SA-NAME]",
        "serviceAccount": {
            "description": "[SA-DESCRIPTION]",
            "displayName": "[SA-DISPLAY-NAME]"
        }
    }
    

响应:

{
        "name": "projects/PROJECT-ID/serviceAccounts/SA-NAME@PROJECT-ID.iam.gserviceaccount.com",
        "projectId": "PROJECT-ID",
        "uniqueId": "113948692397867021414",
        "email": "SA-NAME@PROJECT-ID.iam.gserviceaccount.com",
        "description": "SA-DESCRIPTION",
        "displayName": "SA-DISPLAY-NAME",
        "etag": "BwUp3rVlzes=",
        "oauth2ClientId": "117249000288840666939"
    }
    

C#

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 C# 设置说明进行操作。如需了解详情,请参阅 Cloud 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

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 Go 设置说明进行操作。如需了解详情,请参阅 Cloud 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

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 Java 设置说明进行操作。如需了解详情,请参阅 Cloud IAM Java API 参考文档

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
    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 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 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 {
          ServiceAccount serviceAccount = new ServiceAccount();
          serviceAccount.setDisplayName("your-display-name");
          CreateServiceAccountRequest request = new CreateServiceAccountRequest();
          request.setAccountId("your-service-account-name");
          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
        GoogleCredential credential =
            GoogleCredential.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(),
                    credential)
                .setApplicationName("service-accounts")
                .build();
        return service;
      }
    }

Python

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 Python 设置说明进行操作。如需了解详情,请参阅 Cloud 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

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

列出服务帐号

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

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

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

控制台

  1. 在 Cloud Console 中打开服务帐号页面。

    打开“服务帐号”页面

  2. 点击选择项目

  3. 选择您的项目,然后点击打开。所有服务帐号都列在“服务帐号”页面中。

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 API

调用 serviceAccounts.list() 方法。

请求:

GET https://iam.googleapis.com/v1/projects/[PROJECT-ID]/serviceAccounts
    

响应:

{
        "accounts": [
        {
            "name": "projects/PROJECT-ID/serviceAccounts/SA-NAME-1@PROJECT-ID.iam.gserviceaccount.com",
            "projectId": "PROJECT-ID",
            "uniqueId": "108979773878059201436",
            "email": "SA-NAME-1@PROJECT-ID.iam.gserviceaccount.com",
            "description": "SA-DESCRIPTION-1",
            "displayName": "SA-DISPLAY-NAME-1",
            "etag": "BwUpTsLVUkQ=",
            "oauth2ClientId": "102240834887833340852"
        },
        {
            "name": "projects/PROJECT-ID/serviceAccounts/SA-NAME-2@PROJECT-ID.iam.gserviceaccount.com",
            "projectId": "PROJECT-ID",
            "uniqueId": "108979773878059201436",
            "email": "SA-NAME-2@PROJECT-ID.iam.gserviceaccount.com",
            "description": "SA-DESCRIPTION-2",
            "displayName": "SA-DISPLAY-NAME-2",
            "etag": "BwUpTsLVUkQ=",
            "oauth2ClientId": "102240834887833340852"
        }]
    }
    

C#

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 C# 设置说明进行操作。如需了解详情,请参阅 Cloud 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

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 Go 设置说明进行操作。如需了解详情,请参阅 Cloud 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

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 Java 设置说明进行操作。如需了解详情,请参阅 Cloud IAM Java API 参考文档

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
    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 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
        GoogleCredential credential =
            GoogleCredential.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(),
                    credential)
                .setApplicationName("service-accounts")
                .build();
        return service;
      }
    }

Python

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 Python 设置说明进行操作。如需了解详情,请参阅 Cloud IAM Python API 参考文档

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 description
    displayName: Updated display name
    name: projects/PROJECT-ID/serviceAccounts/SA-NAME@PROJECT-ID.iam.gserviceaccount.com
    

REST API

使用 serviceAccounts.patch() 方法。

请求:

PATCH https://iam.googleapis.com/v1/projects/[PROJECT-ID]/serviceAccounts/[SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com
    

请求正文必须包含服务帐号电子邮件和新的显示名或说明。

{
        "serviceAccount": {
            "email": "[SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com",
            "displayName": "[UPDATED-DISPLAY-NAME]",
            "description": "[UPDATED-DESCRIPTION]"
        },
        "updateMask": "displayName,description"
    }
    

响应:

{
        "name": "projects/PROJECT-ID/serviceAccounts/SA-NAME@PROJECT-ID.iam.gserviceaccount.com",
        "projectId": "PROJECT-ID",
        "uniqueId": "107522985251862639552",
        "email": "SA-NAME@PROJECT-ID.iam.gserviceaccount.com",
        "description": "SA-DESCRIPTION",
        "displayName": "Updated display name",
        "etag": "BwUqLK4bL9U=",
        "oauth2ClientId": "105236325228757713905"
    }
    

C#

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 C# 设置说明进行操作。如需了解详情,请参阅 Cloud 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

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 Go 设置说明进行操作。如需了解详情,请参阅 Cloud 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

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 Java 设置说明进行操作。如需了解详情,请参阅 Cloud IAM Java API 参考文档

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
    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 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 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 {
          // First, get a service account using List() or Get()
          ServiceAccount serviceAccount =
              service
                  .projects()
                  .serviceAccounts()
                  .get(
                      "projects/-/serviceAccounts/"
                          + "your-service-account-name@"
                          + projectId
                          + ".iam.gserviceaccount.com")
                  .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
        GoogleCredential credential =
            GoogleCredential.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(),
                    credential)
                .setApplicationName("service-accounts")
                .build();
        return service;
      }
    }

Python

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 Python 设置说明进行操作。如需了解详情,请参阅 Cloud 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 API

使用 serviceAccounts.disable() 方法。

POST https://iam.googleapis.com/v1/projects/[PROJECT-ID]/serviceAccounts/[SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com:disable
    

C#

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 C# 设置说明进行操作。如需了解详情,请参阅 Cloud 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

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 Go 设置说明进行操作。如需了解详情,请参阅 Cloud 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

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 Java 设置说明进行操作。如需了解详情,请参阅 Cloud IAM Java API 参考文档

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
    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 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 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 {
          DisableServiceAccountRequest request = new DisableServiceAccountRequest();
          service
              .projects()
              .serviceAccounts()
              .disable(
                  "projects/-/serviceAccounts/"
                      + "your-service-account-name@"
                      + projectId
                      + ".iam.gserviceaccount.com",
                  request)
              .execute();

          System.out.println(
              "Disabled service account: "
                  + "your-service-account-name@"
                  + projectId
                  + ".iam.gserviceaccount.com");
        } 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
        GoogleCredential credential =
            GoogleCredential.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(),
                    credential)
                .setApplicationName("service-accounts")
                .build();
        return service;
      }
    }

Python

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 Python 设置说明进行操作。如需了解详情,请参阅 Cloud 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 API

使用 serviceAccounts.enable() 方法。

POST https://iam.googleapis.com/v1/projects/[PROJECT-ID]/serviceAccounts/[SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com:enable
    

C#

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 C# 设置说明进行操作。如需了解详情,请参阅 Cloud 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

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 Go 设置说明进行操作。如需了解详情,请参阅 Cloud 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

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 Java 设置说明进行操作。如需了解详情,请参阅 Cloud IAM Java API 参考文档

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
    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 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 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 {
          EnableServiceAccountRequest request = new EnableServiceAccountRequest();
          service
              .projects()
              .serviceAccounts()
              .enable(
                  "projects/-/serviceAccounts/"
                      + "your-service-account-name@"
                      + projectId
                      + ".iam.gserviceaccount.com",
                  request)
              .execute();

          System.out.println(
              "Enabled service account: "
                  + "your-service-account-name@"
                  + projectId
                  + ".iam.gserviceaccount.com");
        } 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
        GoogleCredential credential =
            GoogleCredential.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(),
                    credential)
                .setApplicationName("service-accounts")
                .build();
        return service;
      }
    }

Python

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 Python 设置说明进行操作。如需了解详情,请参阅 Cloud 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("Disabled 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 API

使用 serviceAccounts.delete() 方法。

DELETE https://iam.googleapis.com/v1/projects/[PROJECT-ID]/serviceAccounts/[SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com
    

C#

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 C# 设置说明进行操作。如需了解详情,请参阅 Cloud 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

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 Go 设置说明进行操作。如需了解详情,请参阅 Cloud 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

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 Java 设置说明进行操作。如需了解详情,请参阅 Cloud IAM Java API 参考文档

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
    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 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 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 {
          service
              .projects()
              .serviceAccounts()
              .delete(
                  "projects/-/serviceAccounts/"
                      + "your-service-account-name@"
                      + projectId
                      + ".iam.gserviceaccount.com")
              .execute();

          System.out.println(
              "Deleted service account: "
                  + "your-service-account-name@"
                  + projectId
                  + ".iam.gserviceaccount.com");
        } 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
        GoogleCredential credential =
            GoogleCredential.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(),
                    credential)
                .setApplicationName("service-accounts")
                .build();
        return service;
      }
    }

Python

在试用此示例之前,请按照《Cloud IAM 快速入门:使用客户端库》中的 Python 设置说明进行操作。如需了解详情,请参阅 Cloud 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 天后,Cloud 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。

要查找已删除的服务帐号的数字 ID,您可以在审核日志中搜索 DeleteServiceAccount 操作:

  1. 在 Cloud Console 中,转到日志查看器页面。

    转到“日志查看器”

  2. 在靠近页面顶部的搜索框中,点击 arrow_drop_down 展开箭头,然后选择转换为高级过滤器

  3. 在搜索框中,输入以下查询,将 [SERVICE_ACCOUNT_NAME] 替换为您的服务帐号名称(例如 my-service-account@project-id.iam.gserviceaccount.com):

    resource.type="service_account"
        resource.labels.email_id="[SERVICE_ACCOUNT_NAME]"
        "DeleteServiceAccount"
        
  4. 如果服务帐号已被删除超过 1 小时,请选择 schedule过去 1 小时下拉列表,然后选择一段较长的时间。

    如果服务帐号已被删除超过 7 天,请选择无限制

  5. 点击提交过滤条件。日志查看器会显示具有您指定的名称的影响服务帐号的 DeleteServiceAccount 操作。每个服务帐号的数字 ID 会显示在文本 DeleteServiceAccount 的旁边。

    如果搜索结果仅包含一项 DeleteServiceAccount 操作,请记下数字 ID。您将使用该数字 ID 恢复删除的服务帐号。

    如果具有多个搜索结果,请点击相应搜索结果旁边的 arrow_right 展开箭头。查看日志条目的详细信息,并确定日志条目是否显示您要撤消的操作。重复此过程,直至找到正确的日志条目,然后记下该条目中的数字 ID。

按数字 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 API

使用 serviceAccounts.undelete() 方法。将 [ACCOUNT_UNIQUE_ID] 替换为服务帐号的数字 ID。

POST https://iam.googleapis.com/v1/projects/-/serviceAccounts/[ACCOUNT_UNIQUE_ID]:undelete
    

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

后续步骤