Membuat kunci akun layanan

Mendemonstrasikan pembuatan kunci akun layanan.

Jelajahi lebih lanjut

Untuk dokumentasi mendetail yang menyertakan contoh kode ini, lihat artikel berikut:

Contoh kode

C++

Untuk mempelajari cara menginstal dan menggunakan library klien untuk IAM, lihat library klien IAM. Untuk informasi selengkapnya, lihat dokumentasi referensi API C++ IAM.

Untuk melakukan autentikasi ke IAM, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

namespace iam = ::google::cloud::iam_admin_v1;
return [](std::string const& name) {
  iam::IAMClient client(iam::MakeIAMConnection());
  auto response = client.CreateServiceAccountKey(
      name,
      google::iam::admin::v1::ServiceAccountPrivateKeyType::
          TYPE_GOOGLE_CREDENTIALS_FILE,
      google::iam::admin::v1::ServiceAccountKeyAlgorithm::KEY_ALG_RSA_2048);
  if (!response) throw std::move(response).status();
  std::cout << "ServiceAccountKey successfully created: "
            << response->DebugString() << "\n"
            << "Please save the key in a secure location, as they cannot "
               "be downloaded later\n";
  return response->name();
}

C#

Untuk mempelajari cara menginstal dan menggunakan library klien untuk IAM, lihat library klien IAM. Untuk informasi selengkapnya, lihat dokumentasi referensi API C# IAM.

Untuk melakukan autentikasi ke IAM, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


using System;
using System.Text;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Iam.v1;
using Google.Apis.Iam.v1.Data;

public partial class ServiceAccountKeys
{
    public static ServiceAccountKey CreateKey(string serviceAccountEmail)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var key = service.Projects.ServiceAccounts.Keys.Create(
            new CreateServiceAccountKeyRequest(),
            "projects/-/serviceAccounts/" + serviceAccountEmail)
            .Execute();

        // The PrivateKeyData field contains the base64-encoded service account key
        // in JSON format.
        // TODO(Developer): Save the below key (jsonKeyFile) to a secure location.
        //  You cannot download it later.
        byte[] valueBytes = System.Convert.FromBase64String(key.PrivateKeyData);
        string jsonKeyContent = Encoding.UTF8.GetString(valueBytes);

        Console.WriteLine("Key created successfully");
        return key;
    }
}

Go

Untuk mempelajari cara menginstal dan menggunakan library klien untuk IAM, lihat library klien IAM. Untuk informasi selengkapnya, lihat dokumentasi referensi API Go IAM.

Untuk melakukan autentikasi ke IAM, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import (
	"context"
	// "encoding/base64"
	"fmt"
	"io"

	iam "google.golang.org/api/iam/v1"
)

// createKey creates a service account key.
func createKey(w io.Writer, serviceAccountEmail string) (*iam.ServiceAccountKey, error) {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return nil, fmt.Errorf("iam.NewService: %w", err)
	}

	resource := "projects/-/serviceAccounts/" + serviceAccountEmail
	request := &iam.CreateServiceAccountKeyRequest{}
	key, err := service.Projects.ServiceAccounts.Keys.Create(resource, request).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.ServiceAccounts.Keys.Create: %w", err)
	}
	// The PrivateKeyData field contains the base64-encoded service account key
	// in JSON format.
	// TODO(Developer): Save the below key (jsonKeyFile) to a secure location.
	// You cannot download it later.
	// jsonKeyFile, _ := base64.StdEncoding.DecodeString(key.PrivateKeyData)
	fmt.Fprintf(w, "Key created successfully")
	return key, nil
}

Java

Untuk mempelajari cara menginstal dan menggunakan library klien untuk IAM, lihat library klien IAM. Untuk informasi selengkapnya, lihat dokumentasi referensi API Java IAM.

Untuk melakukan autentikasi ke IAM, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.IamScopes;
import com.google.api.services.iam.v1.model.CreateServiceAccountKeyRequest;
import com.google.api.services.iam.v1.model.ServiceAccountKey;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Base64;
import java.util.Collections;

public class CreateServiceAccountKey {

  // Creates a key for a service account.
  public static String createKey(String projectId, String serviceAccountName) {
    // String projectId = "my-project-id";
    // String serviceAccountName = "my-service-account-name";

    Iam service = null;
    try {
      service = initService();
    } catch (IOException | GeneralSecurityException e) {
      System.out.println("Unable to initialize service: \n" + e);
      return null;
    }

    // Construct the service account email.
    // You can modify the ".iam.gserviceaccount.com" to match the service account name in which
    // you want to create the key.
    // See, https://cloud.google.com/iam/docs/creating-managing-service-account-keys?hl=en#creating
    String serviceAccountEmail = serviceAccountName + "@" + projectId + ".iam.gserviceaccount.com";
    try {
      ServiceAccountKey key =
          service
              .projects()
              .serviceAccounts()
              .keys()
              .create(
                  "projects/-/serviceAccounts/" + serviceAccountEmail,
                  new CreateServiceAccountKeyRequest())
              .execute();

      // The privateKeyData field contains the base64-encoded service account key
      // in JSON format.
      // TODO(Developer): Save the below key (jsonKeyFile) to a secure location.
      //  You cannot download it later.
      String jsonKeyFile = new String(Base64.getDecoder().decode(key.getPrivateKeyData()));

      System.out.println("Key created successfully");
      String keyName = key.getName();
      return keyName.substring(keyName.lastIndexOf("/") + 1).trim();
    } catch (IOException e) {
      System.out.println("Unable to create service account key: \n" + e);
      return null;
    }
  }

  private static Iam initService() throws GeneralSecurityException, IOException {
    // Use the Application Default Credentials strategy for authentication. For more info, see:
    // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
    // Initialize the IAM service, which can be used to send requests to the IAM API.
    Iam service =
        new Iam.Builder(
            GoogleNetHttpTransport.newTrustedTransport(),
            GsonFactory.getDefaultInstance(),
            new HttpCredentialsAdapter(credential))
            .setApplicationName("service-account-keys")
            .build();
    return service;
  }
}

Python

Untuk mempelajari cara menginstal dan menggunakan library klien untuk IAM, lihat library klien IAM. Untuk informasi selengkapnya, lihat dokumentasi referensi API Python IAM.

Untuk melakukan autentikasi ke IAM, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import os

from google.oauth2 import service_account
import googleapiclient.discovery  # type: ignore

def create_key(service_account_email: str) -> None:
    """Creates a key for a service account."""

    credentials = service_account.Credentials.from_service_account_file(
        filename=os.environ["GOOGLE_APPLICATION_CREDENTIALS"],
        scopes=["https://www.googleapis.com/auth/cloud-platform"],
    )

    service = googleapiclient.discovery.build("iam", "v1", credentials=credentials)

    key = (
        service.projects()
        .serviceAccounts()
        .keys()
        .create(name="projects/-/serviceAccounts/" + service_account_email, body={})
        .execute()
    )

    # The privateKeyData field contains the base64-encoded service account key
    # in JSON format.
    # TODO(Developer): Save the below key {json_key_file} to a secure location.
    #  You cannot download it again later.
    # import base64
    # json_key_file = base64.b64decode(key['privateKeyData']).decode('utf-8')

    if not key["disabled"]:
        print("Created json key")

Langkah selanjutnya

Untuk menelusuri dan memfilter contoh kode untuk produk Google Cloud lainnya, lihat browser contoh Google Cloud.