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.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.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(),
                GsonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

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.

import os

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

def list_service_accounts(project_id: str) -> dict:
    """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

What's next

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