השבתה והפעלה של חשבונות שירות

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

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

  • 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 את התפקיד אדמין של חשבון שירות (roles/iam.serviceAccountAdmin) בפרויקט. להסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.

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

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

השבתת חשבון שירות

בדומה למחיקת חשבון שירות, כשמשביתים חשבון שירות, לאפליקציות לא תהיה יותר גישה למשאבים דרך חשבון השירות הזה. Google Cloud אם משביתים את חשבונות השירות שהם ברירת המחדל של App Engine ושל Compute Engine, למכונות כבר לא תהיה גישה למשאבים בפרויקט. אם מנסים להשבית חשבון שירות שכבר הושבת, לא תהיה לכך השפעה.

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

המסוף

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

    כניסה לדף Service accounts

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

  3. לוחצים על השם של חשבון השירות שרוצים להשבית.

  4. בקטע Service account status, לוחצים על Disable service account, ולאחר מכן לוחצים על Disable כדי לאשר את השינוי.

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 disable כדי להשבית חשבון שירות.

    פקודה:

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

    פלט:

    Disabled service account 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) {
      iam::IAMClient client(iam::MakeIAMConnection());
      google::iam::admin::v1::DisableServiceAccountRequest request;
      request.set_name(name);
      auto response = client.DisableServiceAccount(request);
      if (!response.ok()) throw std::runtime_error(response.message());
      std::cout << "ServiceAccount successfully disabled.\n";
    }

    C#

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

    כדי לבצע אימות ב-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 void DisableServiceAccount(string email)
        {
            var credential = GoogleCredential.GetApplicationDefault()
                .CreateScoped(IamService.Scope.CloudPlatform);
            var service = new IamService(new IamService.Initializer
            {
                HttpClientInitializer = credential
            });
    
            var request = new DisableServiceAccountRequest();
    
            string resource = "projects/-/serviceAccounts/" + email;
            service.Projects.ServiceAccounts.Disable(request, resource).Execute();
            Console.WriteLine("Disabled service account: " + email);
        }
    }

    Go

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

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

    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: %w", err)
    	}
    
    	request := &iam.DisableServiceAccountRequest{}
    	_, err = service.Projects.ServiceAccounts.Disable("projects/-/serviceAccounts/"+email, request).Do()
    	if err != nil {
    		return fmt.Errorf("Projects.ServiceAccounts.Disable: %w", err)
    	}
    	fmt.Fprintf(w, "Disabled service account: %v", email)
    	return 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.DisableServiceAccountRequest;
    import java.io.IOException;
    
    public class DisableServiceAccount {
    
      public static void main(String[] args) throws IOException {
        // TODO(Developer): Replace the below variables before running.
        String projectId = "your-project-id";
        String serviceAccountName = "your-service-account-name";
    
        disableServiceAccount(projectId, serviceAccountName);
      }
    
      // Disables a service account.
      public static void disableServiceAccount(String projectId, String accountName)
              throws IOException {
        String email = String.format("%s@%s.iam.gserviceaccount.com", accountName, projectId);
    
        // 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.disableServiceAccount(DisableServiceAccountRequest.newBuilder()
                  .setName(String.format("projects/%s/serviceAccounts/%s", projectId, email))
                  .build());
    
          System.out.println("Disabled service account: " + accountName);
        }
      }
    }

    Python

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

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

    import time
    
    from google.cloud import iam_admin_v1
    from google.cloud.iam_admin_v1 import types
    
    
    def disable_service_account(project_id: str, account: str) -> types.ServiceAccount:
        """Disables a service account.
    
        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.
        """
    
        iam_admin_client = iam_admin_v1.IAMClient()
        request = types.DisableServiceAccountRequest()
        name = f"projects/{project_id}/serviceAccounts/{account}"
        request.name = name
    
        iam_admin_client.disable_service_account(request=request)
        time.sleep(5)  # waiting to make sure changes applied
    
        get_request = types.GetServiceAccountRequest()
        get_request.name = name
    
        service_account = iam_admin_client.get_service_account(request=get_request)
        if service_account.disabled:
            print(f"Disabled service account: {account}")
        return service_account

    REST

    השיטה serviceAccounts.disable משביתה באופן מיידי חשבון שירות.

    לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud . מזהי פרויקטים הם מחרוזות אלפאנומריות, כמו my-project.
    • SA_ID: המזהה של חשבון השירות. הוא יכול להיות כתובת האימייל של חשבון השירות בתבנית SA_NAME@PROJECT_ID.iam.gserviceaccount.com, או המזהה המספרי שייחודי לחשבון השירות.

    שיטת ה-HTTP וכתובת ה-URL:

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

    כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

    אם הביצוע יהיה תקין, גוף התגובה יהיה ריק.

הפעלת חשבונות שירות

אחרי שמפעילים חשבון שירות מושבת, האפליקציות שוב מקבלות גישה למשאבים שלGoogle Cloud דרך אותו חשבון שירות.

אפשר להפעיל חשבון שירות מושבת מתי שצריך. אם תנסו להפעיל חשבון שירות שכבר מופעל, לא תהיה לכך השפעה.

המסוף

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

    כניסה לדף Service accounts

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

  3. לוחצים על השם של חשבון השירות שרוצים להפעיל.

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

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 enable כדי להפעיל חשבון שירות.

    פקודה:

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

    פלט:

    Enabled service account 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) {
      iam::IAMClient client(iam::MakeIAMConnection());
      google::iam::admin::v1::EnableServiceAccountRequest request;
      request.set_name(name);
      auto response = client.EnableServiceAccount(request);
      if (!response.ok()) throw std::runtime_error(response.message());
      std::cout << "ServiceAccount successfully enabled.\n";
    }

    C#

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

    כדי לבצע אימות ב-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 void EnableServiceAccount(string email)
        {
            var credential = GoogleCredential.GetApplicationDefault()
                .CreateScoped(IamService.Scope.CloudPlatform);
            var service = new IamService(new IamService.Initializer
            {
                HttpClientInitializer = credential
            });
    
            var request = new EnableServiceAccountRequest();
    
            string resource = "projects/-/serviceAccounts/" + email;
            service.Projects.ServiceAccounts.Enable(request, resource).Execute();
            Console.WriteLine("Enabled service account: " + email);
        }
    }

    Go

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

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

    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: %w", err)
    	}
    
    	request := &iam.EnableServiceAccountRequest{}
    	_, err = service.Projects.ServiceAccounts.Enable("projects/-/serviceAccounts/"+email, request).Do()
    	if err != nil {
    		return fmt.Errorf("Projects.ServiceAccounts.Enable: %w", err)
    	}
    	fmt.Fprintf(w, "Enabled service account: %v", email)
    	return 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.EnableServiceAccountRequest;
    import java.io.IOException;
    
    
    public class EnableServiceAccount {
    
      public static void main(String[] args) throws IOException {
        // TODO(Developer): Replace the below variables before running.
        String projectId = "your-project-id";
        String serviceAccountName = "your-service-account-name";
    
        enableServiceAccount(projectId, serviceAccountName);
      }
    
      // Enables a service account.
      public static void enableServiceAccount(String projectId, String accountName)
              throws IOException {
        String email = String.format("%s@%s.iam.gserviceaccount.com", accountName, projectId);
    
        // 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.enableServiceAccount(EnableServiceAccountRequest.newBuilder()
                  .setName(String.format("projects/%s/serviceAccounts/%s", projectId, email))
                  .build());
    
          System.out.println("Enabled service account: " + email);
        }
      }
    }

    Python

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

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

    import time
    
    from google.cloud import iam_admin_v1
    from google.cloud.iam_admin_v1 import types
    
    
    def enable_service_account(project_id: str, account: str) -> types.ServiceAccount:
        """Enables a service account.
    
        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.
        """
    
        iam_admin_client = iam_admin_v1.IAMClient()
        request = types.EnableServiceAccountRequest()
        name = f"projects/{project_id}/serviceAccounts/{account}"
        request.name = name
    
        iam_admin_client.enable_service_account(request=request)
        time.sleep(5)  # waiting to make sure changes applied
    
        get_request = types.GetServiceAccountRequest()
        get_request.name = name
    
        service_account = iam_admin_client.get_service_account(request=get_request)
        if not service_account.disabled:
            print(f"Enabled service account: {account}")
        return service_account

    REST

    השיטה serviceAccounts.enable מפעילה חשבון שירות שהושבת בעבר.

    לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud . מזהי פרויקטים הם מחרוזות אלפאנומריות, כמו my-project.
    • SA_ID: המזהה של חשבון השירות. הוא יכול להיות כתובת האימייל של חשבון השירות בתבנית SA_NAME@PROJECT_ID.iam.gserviceaccount.com, או המזהה המספרי שייחודי לחשבון השירות.

    שיטת ה-HTTP וכתובת ה-URL:

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

    כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

    אם הביצוע יהיה תקין, גוף התגובה יהיה ריק.

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

נסו בעצמכם

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

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