列出服务账号

演示如何列出服务账号。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

C++

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。 如需了解详情,请参阅 IAM C++ API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

namespace iam = ::google::cloud::iam_admin_v1;
[](std::string const& project_id) {
  iam::IAMClient client(iam::MakeIAMConnection());
  int count = 0;
  for (auto& sa : client.ListServiceAccounts("projects/" + project_id)) {
    if (!sa) throw std::move(sa).status();
    std::cout << "ServiceAccount successfully retrieved: " << sa->name()
              << "\n";
    ++count;
  }
  if (count == 0) {
    std::cout << "No service accounts found in project: " << project_id
              << "\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 ServiceAccounts
{
    public static IList<ServiceAccount> ListServiceAccounts(string projectId)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var response = service.Projects.ServiceAccounts.List(
            "projects/" + projectId).Execute();
        foreach (ServiceAccount account in response.Accounts)
        {
            Console.WriteLine("Name: " + account.Name);
            Console.WriteLine("Display Name: " + account.DisplayName);
            Console.WriteLine("Email: " + account.Email);
            Console.WriteLine();
        }
        return response.Accounts;
    }
}

Go

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。 如需了解详情,请参阅 IAM Go API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"

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

// listServiceAccounts lists a project's service accounts.
func listServiceAccounts(w io.Writer, projectID string) ([]*iam.ServiceAccount, error) {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return nil, fmt.Errorf("iam.NewService: %w", err)
	}

	response, err := service.Projects.ServiceAccounts.List("projects/" + projectID).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.ServiceAccounts.List: %w", err)
	}
	for _, account := range response.Accounts {
		fmt.Fprintf(w, "Listing service account: %v\n", account.Name)
	}
	return response.Accounts, nil
}

Java

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。 如需了解详情,请参阅 IAM Java API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


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

public class ListServiceAccounts {

  public static void main(String[] args) throws IOException {
    // TODO(Developer): Replace the below variables before running.
    String projectId = "your-project-id";

    listServiceAccounts(projectId);
  }

  // Lists all service accounts for the current project.
  public static IAMClient.ListServiceAccountsPagedResponse listServiceAccounts(String projectId)
          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.
    try (IAMClient iamClient = IAMClient.create()) {
      IAMClient.ListServiceAccountsPagedResponse response =
              iamClient.listServiceAccounts(String.format("projects/%s", projectId));

      for (ServiceAccount account : response.iterateAll()) {
        System.out.println("Name: " + account.getName());
        System.out.println("Display name: " + account.getDisplayName());
        System.out.println("Email: " + account.getEmail() + "\n");
      }

      return response;
    }
  }
}

Python

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。 如需了解详情,请参阅 IAM Python API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

from typing import List

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


def list_service_accounts(project_id: str) -> List[iam_admin_v1.ServiceAccount]:
    """
    Get list of project service accounts.

    project_id: ID or number of the Google Cloud project you want to use.
    """

    iam_admin_client = iam_admin_v1.IAMClient()
    request = types.ListServiceAccountsRequest()
    request.name = f"projects/{project_id}"

    accounts = iam_admin_client.list_service_accounts(request=request)
    return accounts.accounts

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器