הצגת רשימה ועריכה של חשבונות שירות

בדף הזה מוסבר איך מציגים את רשימת חשבונות השירות ואיך עורכים אותם, באמצעות ה-API של ניהול זהויות והרשאות גישה (IAM), מסוף Google Cloud וכלי שורת הפקודה gcloud.

לפני שמתחילים

  • Enable the IAM API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

  • מגדירים אימות.

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

    Console

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

    gcloud

    In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google 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.

    C#‎

    כדי להשתמש בסביבת פיתוח מקומית בדוגמאות של .NET שבדף הזה, מתקינים ומפעילים את ה-CLI של gcloud, ואז מגדירים את Application Default Credentials באמצעות פרטי הכניסה של המשתמש.

      התקינו את ה-CLI של Google Cloud.

      אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

      If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      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.

    למידע נוסף, ראו הגדרת ADC לסביבת פיתוח מקומית במאמרי העזרה בנושא אימות Google Cloud .

    C++‎

    כדי להשתמש בסביבת פיתוח מקומית בדוגמאות של C++ שבדף הזה, מתקינים ומפעילים את ה-CLI של gcloud, ואז מגדירים את Application Default Credentials באמצעות פרטי הכניסה של המשתמש.

      התקינו את ה-CLI של Google Cloud.

      אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

      If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      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.

    למידע נוסף, ראו הגדרת ADC לסביבת פיתוח מקומית במאמרי העזרה בנושא אימות Google Cloud .

    Go

    כדי להשתמש בסביבת פיתוח מקומית בדוגמאות של Go שבדף הזה, מתקינים ומפעילים את ה-CLI של gcloud, ואז מגדירים את Application Default Credentials באמצעות פרטי הכניסה של המשתמש.

      התקינו את ה-CLI של Google Cloud.

      אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

      If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      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.

    למידע נוסף, ראו הגדרת ADC לסביבת פיתוח מקומית במאמרי העזרה בנושא אימות Google Cloud .

    Java

    כדי להשתמש בסביבת פיתוח מקומית בדוגמאות של Java שבדף הזה, מתקינים ומפעילים את ה-CLI של gcloud, ואז מגדירים את Application Default Credentials באמצעות פרטי הכניסה של המשתמש.

      התקינו את ה-CLI של Google Cloud.

      אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

      If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      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.

    למידע נוסף, ראו הגדרת ADC לסביבת פיתוח מקומית במאמרי העזרה בנושא אימות Google Cloud .

    Python

    כדי להשתמש בסביבת פיתוח מקומית בדוגמאות של Python שבדף הזה, מתקינים ומפעילים את ה-CLI של gcloud, ואז מגדירים את Application Default Credentials באמצעות פרטי הכניסה של המשתמש.

      התקינו את ה-CLI של Google Cloud.

      אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

      If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      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.

    למידע נוסף, ראו הגדרת ADC לסביבת פיתוח מקומית במאמרי העזרה בנושא אימות Google Cloud .

    REST

    כדי להשתמש בדוגמאות של API בארכיטקטורת REST שבדף הזה בסביבת פיתוח מקומית, צריך להשתמש בפרטי הכניסה שאתם נותנים ל-CLI של gcloud.

      התקינו את ה-CLI של Google Cloud.

      אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

    מידע נוסף מופיע במאמר אימות לשימוש ב-REST במסמכי האימות של Google Cloud .

  • הסבר על חשבונות שירות של IAM

התפקידים הנדרשים

כדי לקבל את ההרשאות שדרושות לניהול חשבונות שירות, צריך לבקש מהאדמין להקצות לכם את תפקידי ה-IAM הבאים בפרויקט:

להסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.

יכול להיות שאפשר לקבל את ההרשאות הנדרשות גם באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש.

תפקידים בסיסיים ב-IAM כוללים גם הרשאות לניהול חשבונות שירות. בסביבת ייצור לא מומלץ להקצות תפקידים בסיסיים, אבל אפשר להעניק אותם בסביבת פיתוח או בסביבת בדיקה.

הצגת רשימה של חשבונות שירות

אתם יכולים להציג את רשימת חשבונות השירות בניהול המשתמשים בפרויקט כדי לבדוק את חשבונות השירות והמפתחות, או כחלק מכלי מותאם אישית לניהול חשבונות השירות.

אי אפשר להציג את רשימת סוכני השירות שעשויים להופיע במדיניות ההרשאות וביומני הביקורת של הפרויקט. סוכני השירות לא נמצאים בפרויקט, ואי אפשר לגשת אליהם ישירות.

המסוף

  1. נכנסים לדף Service accounts במסוף Google Cloud .

    כניסה לדף Service accounts

  2. בוחרים פרויקט.

    בדף Service accounts מוצגת הרשימה של כל חשבונות השירות בניהול המשתמשים בפרויקט שבחרתם.

gcloud

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

    Activate Cloud Shell

    At the bottom of the Google 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.iam.gserviceaccount.com
    SA_DISPLAY_NAME_2    SA_NAME_2@PROJECT_ID.iam.gserviceaccount.com
    
  3. C++

    במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM C++ API‎.

    כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

    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, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

    
    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, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

    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, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

    
    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, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

    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: מזהה הפרויקט ב- Google Cloud . מזהי פרויקטים הם מחרוזות אלפאנומריות, כמו 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.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"
        }
      ]
    }
    

עריכה של חשבון שירות

בדרך כלל משתמשים בשם המוצג (השם הידידותי) ובתיאור של חשבון השירות כדי לקבל מידע נוסף על חשבון השירות, כמו המטרה שלו או איש הקשר שלו.

המסוף

  1. נכנסים לדף Service accounts במסוף Google Cloud .

    כניסה לדף Service accounts

  2. בוחרים פרויקט.

  3. לוחצים על כתובת האימייל של חשבון השירות שאת שמו רוצים לשנות.

  4. מזינים את השם החדש בתיבה Name ולוחצים על Save.

gcloud

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

    Activate Cloud Shell

    At the bottom of the Google 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.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
    
  3. C++

    במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM C++ API‎.

    כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

    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, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

    
    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, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

    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, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

    
    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, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

    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: מזהה הפרויקט ב- Google Cloud . מזהי פרויקטים הם מחרוזות אלפאנומריות, כמו my-project.
    • SA_ID: המזהה של חשבון השירות. זו יכולה להיות כתובת האימייל של חשבון השירות בתבנית SA_NAME@PROJECT_ID.iam.gserviceaccount.com, או המזהה המספרי שייחודי לחשבון השירות.
    • SA_NAME: המזהה האלפאנומרי של חשבון השירות. השם צריך להיות באורך שבין 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.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"
    }
    

המאמרים הבאים

נסו בעצמכם

אתם משתמשים חדשים ב- Google Cloud? אנחנו ממליצים לכם ליצור חשבון, להתנסות בעצמכם במוצרים שלנו ולבחון אותם באמצעות תרחישים ממשיים. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.

מתחילים לעבוד בלי לשלם