重命名服务账号

演示如何重命名服务账号。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

C++

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

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

namespace iam = ::google::cloud::iam_admin_v1;
[](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::move(response).status();
  std::cout << "ServiceAccount successfully updated: "
            << response->DebugString() << "\n";
}

C#

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

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


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 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

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

Java

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

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.iam.admin.v1.IAMClient;
import com.google.iam.admin.v1.GetServiceAccountRequest;
import com.google.iam.admin.v1.PatchServiceAccountRequest;
import com.google.iam.admin.v1.ServiceAccount;
import com.google.iam.admin.v1.ServiceAccountName;
import com.google.protobuf.FieldMask;
import java.io.IOException;

public class RenameServiceAccount {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace the variables before running the sample.
    String projectId = "your-project-id";
    String serviceAccountName = "my-service-account-name";
    String displayName = "your-new-display-name";

    renameServiceAccount(projectId, serviceAccountName, displayName);
  }

  // Changes a service account's display name.
  public static ServiceAccount renameServiceAccount(String projectId, String serviceAccountName,
                                                    String displayName) throws IOException {
    // Construct the service account email.
    // You can modify the ".iam.gserviceaccount.com" to match the service account name in which
    // you want to delete the key.
    // See, https://cloud.google.com/iam/docs/creating-managing-service-account-keys?hl=en#deleting
    String serviceAccountEmail = serviceAccountName + "@" + projectId + ".iam.gserviceaccount.com";

    // Initialize client that will be used to send requests.
    // This client only needs to be created once, and can be reused for multiple requests.
    try (IAMClient iamClient = IAMClient.create()) {
      // First, get a service account using getServiceAccount or listServiceAccounts
      GetServiceAccountRequest serviceAccountRequest = GetServiceAccountRequest.newBuilder()
              .setName(ServiceAccountName.of(projectId, serviceAccountEmail).toString())
              .build();
      ServiceAccount serviceAccount = iamClient.getServiceAccount(serviceAccountRequest);

      // You can patch only the `display_name` and `description` fields. You must use
      //  the `update_mask` field to specify which of these fields you want to patch.
      serviceAccount = serviceAccount.toBuilder().setDisplayName(displayName).build();
      PatchServiceAccountRequest patchServiceAccountRequest =
              PatchServiceAccountRequest.newBuilder()
                      .setServiceAccount(serviceAccount)
                      .setUpdateMask(FieldMask.newBuilder().addPaths("display_name").build())
                      .build();
      serviceAccount = iamClient.patchServiceAccount(patchServiceAccountRequest);

      System.out.println(
              "Updated display name for "
                      + serviceAccount.getName()
                      + " to: "
                      + serviceAccount.getDisplayName());
      return serviceAccount;
    }
  }
}

Python

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

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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


def rename_service_account(
    project_id: str, account: str, new_name: str
) -> types.ServiceAccount:
    """
    Renames service account display name.

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

    iam_admin_client = iam_admin_v1.IAMClient()

    get_request = types.GetServiceAccountRequest()
    get_request.name = f"projects/{project_id}/serviceAccounts/{account}"
    service_account = iam_admin_client.get_service_account(request=get_request)

    service_account.display_name = new_name

    request = types.PatchServiceAccountRequest()
    request.service_account = service_account
    # You can patch only the `display_name` and `description` fields. You must use
    # the `update_mask` field to specify which of these fields you want to patch.
    # To successfully set update mask you need to transform snake_case field to camelCase.
    # e.g. `display_name` will become `displayName`
    request.update_mask = "displayName"

    updated_account = iam_admin_client.patch_service_account(request=request)
    return updated_account

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器