Dienstkontoschlüssel auflisten

Veranschaulicht das Auflisten von Dienstkontoschlüsseln.

Weitere Informationen

Eine ausführliche Dokumentation, die dieses Codebeispiel enthält, finden Sie hier:

Codebeispiel

C++

Informationen zum Installieren und Verwenden der Clientbibliothek für IAM finden Sie unter IAM-Clientbibliotheken. Weitere Informationen finden Sie in der IAM-Referenzdokumentation zur C++ API.

Richten Sie zur Authentifizierung bei IAM die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

namespace iam = ::google::cloud::iam_admin_v1;
[](std::string const& service_account_name,
   std::vector<std::string> const& key_type_labels) {
  iam::IAMClient client(iam::MakeIAMConnection());
  std::vector<google::iam::admin::v1::ListServiceAccountKeysRequest::KeyType>
      key_types;
  for (auto const& type : key_type_labels) {
    if (type == "USER_MANAGED") {
      key_types.push_back(google::iam::admin::v1::
                              ListServiceAccountKeysRequest::USER_MANAGED);
    } else if (type == "SYSTEM_MANAGED") {
      key_types.push_back(google::iam::admin::v1::
                              ListServiceAccountKeysRequest::SYSTEM_MANAGED);
    }
  }
  auto response =
      client.ListServiceAccountKeys(service_account_name, key_types);
  if (!response) throw std::move(response).status();
  std::cout << "ServiceAccountKeys successfully retrieved: "
            << response->DebugString() << "\n";
}

C#

Informationen zum Installieren und Verwenden der Clientbibliothek für IAM finden Sie unter IAM-Clientbibliotheken. Weitere Informationen finden Sie in der IAM-Referenzdokumentation zur C# API.

Richten Sie zur Authentifizierung bei IAM die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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 ServiceAccountKeys
{
    public static IList<ServiceAccountKey> ListKeys(string serviceAccountEmail)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var response = service.Projects.ServiceAccounts.Keys
            .List($"projects/-/serviceAccounts/{serviceAccountEmail}")
            .Execute();
        foreach (ServiceAccountKey key in response.Keys)
        {
            Console.WriteLine("Key: " + key.Name);
        }
        return response.Keys;
    }
}

Go

Informationen zum Installieren und Verwenden der Clientbibliothek für IAM finden Sie unter IAM-Clientbibliotheken. Weitere Informationen finden Sie in der IAM-Referenzdokumentation zur Go API.

Richten Sie zur Authentifizierung bei IAM die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import (
	"context"
	"fmt"
	"io"

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

// listKey lists a service account's keys.
func listKeys(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
	response, err := service.Projects.ServiceAccounts.Keys.List(resource).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.ServiceAccounts.Keys.List: %w", err)
	}
	for _, key := range response.Keys {
		fmt.Fprintf(w, "Listing key: %v", key.Name)
	}
	return response.Keys, nil
}

Java

Informationen zum Installieren und Verwenden der Clientbibliothek für IAM finden Sie unter IAM-Clientbibliotheken. Weitere Informationen finden Sie in der IAM-Referenzdokumentation zur Java API.

Richten Sie zur Authentifizierung bei IAM die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import com.google.cloud.iam.admin.v1.IAMClient;
import com.google.iam.admin.v1.ListServiceAccountKeysRequest;
import com.google.iam.admin.v1.ServiceAccountKey;
import java.io.IOException;
import java.util.List;

public class ListServiceAccountKeys {

  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";

    List<ServiceAccountKey> keys = listKeys(projectId, serviceAccountName);
    keys.forEach(key -> System.out.println("Key: " + key.getName()));
  }

  // Lists all keys for a service account.
  public static List<ServiceAccountKey> listKeys(String projectId, String accountName)
          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.
    String email = String.format("%s@%s.iam.gserviceaccount.com", accountName, projectId);
    try (IAMClient iamClient = IAMClient.create()) {
      ListServiceAccountKeysRequest req = ListServiceAccountKeysRequest.newBuilder()
              .setName(String.format("projects/%s/serviceAccounts/%s", projectId, email))
              .build();

      return iamClient.listServiceAccountKeys(req).getKeysList();
    }
  }
}

Python

Informationen zum Installieren und Verwenden der Clientbibliothek für IAM finden Sie unter IAM-Clientbibliotheken. Weitere Informationen finden Sie in der IAM-Referenzdokumentation zur Python API.

Richten Sie zur Authentifizierung bei IAM die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

from typing import List

from google.cloud import iam_admin_v1
from google.cloud.iam_admin_v1 import types


def list_keys(project_id: str, account: str) -> List[iam_admin_v1.ServiceAccountKey]:
    """Creates a key for 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.ListServiceAccountKeysRequest()
    request.name = f"projects/{project_id}/serviceAccounts/{account}"

    response = iam_admin_client.list_service_account_keys(request=request)
    return response.keys

Nächste Schritte

Informationen zum Suchen und Filtern von Codebeispielen für andere Google Cloud -Produkte finden Sie im Google Cloud Beispielbrowser.