List service accounts

Demonstrates listing service accounts.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C++

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM C++ API reference documentation.

To authenticate to IAM, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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#

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM C# API reference documentation.

To authenticate to IAM, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM Go API reference documentation.

To authenticate to IAM, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM Java API reference documentation.

To authenticate to IAM, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM Python API reference documentation.

To authenticate to IAM, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.