서비스 계정 키 나열

서비스 계정 키를 나열하는 방법을 보여줍니다.

더 살펴보기

이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.

코드 샘플

C++

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM C++ API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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#

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM C# API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


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

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Go API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Java API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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.ServiceAccountKey;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;

public class ListServiceAccountKeys {

  // Lists all keys for a service account.
  public static void listKeys(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.toString());
      return;
    }

    String serviceAccountEmail = serviceAccountName + "@" + projectId + ".iam.gserviceaccount.com";
    try {
      List<ServiceAccountKey> keys =
          service
              .projects()
              .serviceAccounts()
              .keys()
              .list("projects/-/serviceAccounts/" + serviceAccountEmail)
              .execute()
              .getKeys();

      for (ServiceAccountKey key : keys) {
        System.out.println("Key: " + key.getName());
      }
    } catch (IOException e) {
      System.out.println("Unable to list service account keys: \n" + e.toString());
    }
  }

  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

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Python API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import os

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

def list_keys(service_account_email: str) -> None:
    """Lists all keys 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)

    keys = (
        service.projects()
        .serviceAccounts()
        .keys()
        .list(name="projects/-/serviceAccounts/" + service_account_email)
        .execute()
    )

    for key in keys["keys"]:
        print("Key: " + key["name"])

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.