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

הדגמה של הפעלת מפתח לחשבון שירות IAM שהושבת.

המשך למידה

לקבלת הסבר מפורט שכולל את דוגמת הקוד הזו, קראו את המאמר:

דוגמת קוד

Java

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

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


import com.google.cloud.iam.admin.v1.IAMClient;
import java.io.IOException;


public class EnableServiceAccountKey {

  public static void main(String[] args) throws IOException {
    // TODO(Developer): Replace the below variables before running.
    String projectId = "gcloud-project-id";
    String serviceAccountName = "service-account-name";
    String serviceAccountKeyName = "service-account-key-name";

    enableServiceAccountKey(projectId, serviceAccountName, serviceAccountKeyName);
  }

  // Enables a service account key.
  public static void enableServiceAccountKey(String projectId,
                                             String accountName,
                                             String key) 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 enable the key.
    // See, https://cloud.google.com/iam/docs/creating-managing-service-account-keys#enabling
    String email = String.format("%s@%s.iam.gserviceaccount.com", accountName, projectId);
    String name = String.format("projects/%s/serviceAccounts/%s/keys/%s", projectId, email, key);

    // 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.enableServiceAccountKey(name);

      System.out.println("Enabled service account key: " + name);
    }
  }
}

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

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