서비스 계정 나열 및 수정

이 페이지에서는 Identity and Access Management(IAM) API, Trusted Cloud 콘솔, gcloud 명령줄 도구를 사용하여 서비스 계정을 나열하고 수정하는 방법을 설명합니다.

시작하기 전에

  • Enable the IAM API.

    Enable the API

  • 인증을 설정합니다.

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

    Console

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

    gcloud

    Google Cloud CLI를 설치한 후 제휴 ID로 gcloud CLI에 로그인합니다. 로그인한 후 다음 명령어를 실행하여 Google Cloud CLI를 초기화합니다.

    gcloud init

    C#

    로컬 개발 환경에서 이 페이지의 .NET 샘플을 사용하려면 gcloud CLI를 설치하고 초기화한 후 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정합니다.

      Google Cloud CLI를 설치한 후 제휴 ID로 gcloud CLI에 로그인합니다.

      Create local authentication credentials for your user account:

      gcloud auth application-default login

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    자세한 내용은 Trusted Cloud 인증 문서의 로컬 개발 환경의 ADC 설정을 참조하세요.

    C++

    로컬 개발 환경에서 이 페이지의 C++ 샘플을 사용하려면 gcloud CLI를 설치하고 초기화한 후 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정합니다.

      Google Cloud CLI를 설치한 후 제휴 ID로 gcloud CLI에 로그인합니다.

      Create local authentication credentials for your user account:

      gcloud auth application-default login

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    자세한 내용은 Trusted Cloud 인증 문서의 로컬 개발 환경의 ADC 설정을 참조하세요.

    Go

    로컬 개발 환경에서 이 페이지의 Go 샘플을 사용하려면 gcloud CLI를 설치하고 초기화한 후 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정합니다.

      Google Cloud CLI를 설치한 후 제휴 ID로 gcloud CLI에 로그인합니다.

      Create local authentication credentials for your user account:

      gcloud auth application-default login

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    자세한 내용은 Trusted Cloud 인증 문서의 로컬 개발 환경의 ADC 설정을 참조하세요.

    Java

    로컬 개발 환경에서 이 페이지의 Java 샘플을 사용하려면 gcloud CLI를 설치하고 초기화한 후 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정합니다.

      Google Cloud CLI를 설치한 후 제휴 ID로 gcloud CLI에 로그인합니다.

      Create local authentication credentials for your user account:

      gcloud auth application-default login

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    자세한 내용은 Trusted Cloud 인증 문서의 로컬 개발 환경의 ADC 설정을 참조하세요.

    Python

    로컬 개발 환경에서 이 페이지의 Python 샘플을 사용하려면 gcloud CLI를 설치하고 초기화한 후 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정합니다.

      Google Cloud CLI를 설치한 후 제휴 ID로 gcloud CLI에 로그인합니다.

      Create local authentication credentials for your user account:

      gcloud auth application-default login

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    자세한 내용은 Trusted Cloud 인증 문서의 로컬 개발 환경의 ADC 설정을 참조하세요.

    REST

    로컬 개발 환경에서 이 페이지의 REST API 샘플을 사용하려면 gcloud CLI에 제공한 사용자 인증 정보를 사용합니다.

      Google Cloud CLI를 설치한 후 제휴 ID로 gcloud CLI에 로그인합니다.

    자세한 내용은 Trusted Cloud 인증 문서의 REST 사용을 위한 인증을 참조하세요.

  • IAM 서비스 계정 이해

필요한 역할

서비스 계정을 관리하는 데 필요한 권한을 얻으려면 관리자에게 프로젝트에 대한 다음 IAM 역할을 부여해 달라고 요청합니다.

역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.

커스텀 역할이나 다른 사전 정의된 역할을 통해 필요한 권한을 얻을 수도 있습니다.

이러한 역할에 대한 자세한 내용은 서비스 계정 역할을 참조하세요.

IAM 기본 역할도 서비스 계정을 관리하는 권한을 포함하지만, 프로덕션 환경에서는 기본 역할을 부여하지 말아야 하지만 개발 환경 또는 테스트 환경에서는 부여해도 됩니다.

서비스 계정 나열

사용자 관리 서비스 계정을 프로젝트에 나열하여 서비스 계정 및 키를 감사하거나 서비스 계정 관리를 위한 커스텀 도구의 일부로 사용할 수 있습니다.

프로젝트 허용 정책과 감사 로그에 표시될 수 있는 서비스 에이전트를 나열할 수 없습니다. 서비스 에이전트가 프로젝트에 없으므로 직접 액세스할 수 없습니다.

콘솔

  1. Trusted Cloud 콘솔에서 서비스 계정 페이지로 이동합니다.

    서비스 계정으로 이동

  2. 프로젝트를 선택합니다.

    서비스 계정 페이지에는 선택한 프로젝트의 모든 사용자 관리 서비스 계정이 나열됩니다.

gcloud

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

    Activate Cloud Shell

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

  2. gcloud iam service-accounts list 명령어를 실행하여 프로젝트의 모든 서비스 계정을 나열합니다.

    명령어:

    gcloud iam service-accounts list

    프로젝트의 모든 사용자 관리형 서비스 계정 목록이 출력됩니다.

    NAME                    EMAIL
    SA_DISPLAY_NAME_1    SA_NAME_1@PROJECT_ID.s3ns-system.iam.gserviceaccount.com
    SA_DISPLAY_NAME_2    SA_NAME_2@PROJECT_ID.s3ns-system.iam.gserviceaccount.com
    
  3. C++

    IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM C++ API 참고 문서를 참조하세요.

    IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

    코드 샘플을 실행하기 전에 GOOGLE_CLOUD_UNIVERSE_DOMAIN 환경 변수를 s3nsapis.fr으로 설정합니다.

    namespace iam = ::google::cloud::iam_admin_v1;
    [](std::string const& project_id) {
      iam::IAMClient client(iam::MakeIAMConnection());
      int count = 0;
      for (auto& sa : client.ListServiceAccounts("projects/" + project_id)) {
        if (!sa) throw std::move(sa).status();
        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 참고 문서를 참조하세요.

    IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

    코드 샘플을 실행하기 전에 GOOGLE_CLOUD_UNIVERSE_DOMAIN 환경 변수를 s3nsapis.fr으로 설정합니다.

    
    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 참고 문서를 참조하세요.

    IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

    코드 샘플을 실행하기 전에 GOOGLE_CLOUD_UNIVERSE_DOMAIN 환경 변수를 s3nsapis.fr으로 설정합니다.

    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: %w", err)
    	}
    
    	response, err := service.Projects.ServiceAccounts.List("projects/" + projectID).Do()
    	if err != nil {
    		return nil, fmt.Errorf("Projects.ServiceAccounts.List: %w", 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 참고 문서를 참조하세요.

    IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

    코드 샘플을 실행하기 전에 GOOGLE_CLOUD_UNIVERSE_DOMAIN 환경 변수를 s3nsapis.fr으로 설정합니다.

    
    import com.google.cloud.iam.admin.v1.IAMClient;
    import com.google.iam.admin.v1.ServiceAccount;
    import java.io.IOException;
    
    public class ListServiceAccounts {
    
      public static void main(String[] args) throws IOException {
        // TODO(Developer): Replace the below variables before running.
        String projectId = "your-project-id";
    
        listServiceAccounts(projectId);
      }
    
      // Lists all service accounts for the current project.
      public static IAMClient.ListServiceAccountsPagedResponse listServiceAccounts(String projectId)
              throws IOException {
        // Initialize client that will be used to send requests.
        // This client only needs to be created once, and can be reused for multiple requests.
        try (IAMClient iamClient = IAMClient.create()) {
          IAMClient.ListServiceAccountsPagedResponse response =
                  iamClient.listServiceAccounts(String.format("projects/%s", projectId));
    
          for (ServiceAccount account : response.iterateAll()) {
            System.out.println("Name: " + account.getName());
            System.out.println("Display name: " + account.getDisplayName());
            System.out.println("Email: " + account.getEmail() + "\n");
          }
    
          return response;
        }
      }
    }

    Python

    IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Python API 참고 문서를 참조하세요.

    IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

    코드 샘플을 실행하기 전에 GOOGLE_CLOUD_UNIVERSE_DOMAIN 환경 변수를 s3nsapis.fr으로 설정합니다.

    from typing import List
    
    from google.cloud import iam_admin_v1
    from google.cloud.iam_admin_v1 import types
    
    
    def list_service_accounts(project_id: str) -> List[iam_admin_v1.ServiceAccount]:
        """Get list of project service accounts.
    
        project_id: ID or number of the Google Cloud project you want to use.
    
        returns a list of iam_admin_v1.ServiceAccount
        """
    
        iam_admin_client = iam_admin_v1.IAMClient()
        request = types.ListServiceAccountsRequest()
        request.name = f"projects/{project_id}"
    
        accounts = iam_admin_client.list_service_accounts(request=request)
        return accounts.accounts

    REST

    serviceAccounts.list 메서드는 프로젝트의 모든 사용자 관리 서비스 계정을 나열합니다.

    요청 데이터를 사용하기 전에 다음을 바꿉니다.

    • PROJECT_ID: Trusted Cloud 프로젝트 ID. 프로젝트 ID는 my-project와 같은 영숫자 문자열입니다.

    HTTP 메서드 및 URL:

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

    요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

    다음과 비슷한 JSON 응답이 표시됩니다.

    {
      "accounts": [
        {
          "name": "projects/my-project/serviceAccounts/sa-1@my-project.s3ns-system.iam.gserviceaccount.com",
          "projectId": "my-project",
          "uniqueId": "123456789012345678901",
          "email": "sa-1@my-project.s3ns-system.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.s3ns-system.iam.gserviceaccount.com",
          "projectId": "my-project",
          "uniqueId": "234567890123456789012",
          "email": "sa-2@my-project.s3ns-system.iam.gserviceaccount.com",
          "description": "My second service account",
          "displayName": "Service account 2",
          "etag": "UkQpTwBVUsL=",
          "oauth2ClientId": "876543210987654321098"
        }
      ]
    }
    

서비스 계정 수정

서비스 계정의 표시 이름(별칭) 및 설명은 일반적으로 서비스 계정의 용도나 서비스 계정 담당자와 같이 서비스 계정에 대한 추가 정보를 파악하는 데 사용됩니다.

콘솔

  1. Trusted Cloud 콘솔에서 서비스 계정 페이지로 이동합니다.

    서비스 계정으로 이동

  2. 프로젝트를 선택합니다.

  3. 이름을 바꿀 서비스 계정의 이메일 주소를 클릭합니다.

  4. 이름 상자에 새 이름을 입력한 다음 저장을 클릭합니다.

gcloud

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

    Activate Cloud Shell

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

  2. gcloud iam service-accounts update 명령어를 실행하여 서비스 계정을 업데이트합니다.

    명령어:

    gcloud iam service-accounts update 
    SA_NAME@PROJECT_ID.s3ns-system.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.s3ns-system.iam.gserviceaccount.com
    
  3. C++

    IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM C++ API 참고 문서를 참조하세요.

    IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

    코드 샘플을 실행하기 전에 GOOGLE_CLOUD_UNIVERSE_DOMAIN 환경 변수를 s3nsapis.fr으로 설정합니다.

    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에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

    코드 샘플을 실행하기 전에 GOOGLE_CLOUD_UNIVERSE_DOMAIN 환경 변수를 s3nsapis.fr으로 설정합니다.

    
    using System;
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Iam.v1;
    using Google.Apis.Iam.v1.Data;
    
    public partial class ServiceAccounts
    {
        public static 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에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

    코드 샘플을 실행하기 전에 GOOGLE_CLOUD_UNIVERSE_DOMAIN 환경 변수를 s3nsapis.fr으로 설정합니다.

    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에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

    코드 샘플을 실행하기 전에 GOOGLE_CLOUD_UNIVERSE_DOMAIN 환경 변수를 s3nsapis.fr으로 설정합니다.

    
    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에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

    코드 샘플을 실행하기 전에 GOOGLE_CLOUD_UNIVERSE_DOMAIN 환경 변수를 s3nsapis.fr으로 설정합니다.

    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

    REST

    serviceAccounts.patch 메서드는 서비스 계정을 업데이트합니다.

    요청 데이터를 사용하기 전에 다음을 바꿉니다.

    • PROJECT_ID: Trusted Cloud 프로젝트 ID. 프로젝트 ID는 my-project와 같은 영숫자 문자열입니다.
    • SA_ID: 서비스 계정의 ID입니다. SA_NAME@PROJECT_ID.s3ns-system.iam.gserviceaccount.com 형식의 서비스 계정 이메일 주소이거나 서비스 계정의 고유 숫자 ID일 수 있습니다.
    • SA_NAME: 서비스 계정의 영숫자 ID. ID는 6~30자(영문 기준)여야 하며 소문자 영숫자 문자와 대시를 포함할 수 있습니다.
    • 다음 중 하나 이상을 바꿉니다.
      • UPDATED_DISPLAY_NAME: 서비스 계정의 새 표시 이름
      • UPDATED_DESCRIPTION: 서비스 계정에 대한 새 설명

    HTTP 메서드 및 URL:

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

    JSON 요청 본문:

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

    요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

    다음과 비슷한 JSON 응답이 표시됩니다.

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

다음 단계