演示如何列出服务帐号。
深入探索
如需查看包含此代码示例的详细文档,请参阅以下内容:
代码示例
C#
如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM C# API 参考文档。
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;
}
}
C++
如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM C++ API 参考文档。
namespace iam = ::google::cloud::iam;
[](std::string const& project_id) {
iam::IAMClient client(iam::MakeIAMConnection());
int count = 0;
for (auto const& sa :
client.ListServiceAccounts("projects/" + project_id)) {
if (!sa) throw std::runtime_error(sa.status().message());
std::cout << "ServiceAccount successfully retrieved: " << sa->name()
<< "\n";
++count;
}
if (count == 0) {
std::cout << "No service accounts found in project: " << project_id
<< "\n";
}
}
Go
如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Go API 参考文档。
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: %v", err)
}
response, err := service.Projects.ServiceAccounts.List("projects/" + projectID).Do()
if err != nil {
return nil, fmt.Errorf("Projects.ServiceAccounts.List: %v", 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 参考文档。
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.IamScopes;
import com.google.api.services.iam.v1.model.ListServiceAccountsResponse;
import com.google.api.services.iam.v1.model.ServiceAccount;
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 ListServiceAccounts {
// Lists all service accounts for the current project.
public static void listServiceAccounts(String projectId) {
// String projectId = "my-project-id"
Iam service = null;
try {
service = initService();
} catch (IOException | GeneralSecurityException e) {
System.out.println("Unable to initialize service: \n" + e.toString());
return;
}
try {
ListServiceAccountsResponse response =
service.projects().serviceAccounts().list("projects/" + projectId).execute();
List<ServiceAccount> serviceAccounts = response.getAccounts();
for (ServiceAccount account : serviceAccounts) {
System.out.println("Name: " + account.getName());
System.out.println("Display Name: " + account.getDisplayName());
System.out.println("Email: " + account.getEmail());
System.out.println();
}
} catch (IOException e) {
System.out.println("Unable to list service accounts: \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(),
JacksonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credential))
.setApplicationName("service-accounts")
.build();
return service;
}
}
Python
如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Python API 参考文档。
import os
from google.oauth2 import service_account
import googleapiclient.discovery
def list_service_accounts(project_id):
"""Lists all service accounts for the current project."""
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)
service_accounts = service.projects().serviceAccounts().list(
name='projects/' + project_id).execute()
for account in service_accounts['accounts']:
print('Name: ' + account['name'])
print('Email: ' + account['email'])
print(' ')
return service_accounts
后续步骤
如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器。