Method: projects.serviceAccounts.list

Lists every ServiceAccount that belongs to a specific project.

HTTP request

GET https://iam.googleapis.com/v1/{name=projects/*}/serviceAccounts

The URL uses gRPC Transcoding syntax.

Path parameters

Parameters
name

string

Required. The resource name of the project associated with the service accounts, such as projects/my-project-123.

Authorization requires the following IAM permission on the specified resource name:

  • iam.serviceAccounts.list

Query parameters

Parameters
pageSize

integer

Optional limit on the number of service accounts to include in the response. Further accounts can subsequently be obtained by including the ListServiceAccountsResponse.next_page_token in a subsequent request.

The default is 20, and the maximum is 100.

pageToken

string

Optional pagination token returned in an earlier ListServiceAccountsResponse.next_page_token.

Request body

The request body must be empty.

Response body

The service account list response.

If successful, the response body contains data with the following structure:

JSON representation
{
  "accounts": [
    {
      object (ServiceAccount)
    }
  ],
  "nextPageToken": string
}
Fields
accounts[]

object (ServiceAccount)

The list of matching service accounts.

nextPageToken

string

To retrieve the next page of results, set ListServiceAccountsRequest.page_token to this value.

Authorization scopes

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/iam
  • https://www.googleapis.com/auth/cloud-platform

For more information, see the Authentication Overview.

Examples

Uses the .NET client library.

// BEFORE RUNNING:
// ---------------
// 1. If not already done, enable the Identity and Access Management (IAM) API
//    and check the quota for your project at
//    https://console.developers.google.com/apis/api/iam
// 2. This sample uses Application Default Credentials for authentication.
//    If not already done, install the gcloud CLI from
//    https://cloud.google.com/sdk and run
//    `gcloud beta auth application-default login`.
//    For more information, see
//    https://developers.google.com/identity/protocols/application-default-credentials
// 3. Install the C# client library by adding a dependency on the relevant NuGet
//    package. Libraries published by Google are owned by google-apis-packages:
//    https://www.nuget.org/profiles/google-apis-packages

using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Iam.v1;
using Newtonsoft.Json;
using System;
using System.Threading.Tasks;

using Data = Google.Apis.Iam.v1.Data;

namespace IamSample
{
   
public class IamExample
   
{
       
public static void Main(string[] args)
       
{
           
IamService iamService = new IamService(new BaseClientService.Initializer
           
{
               
HttpClientInitializer = GetCredential(),
               
ApplicationName = "Google-iamSample/0.1",
           
});

           
// Required. The resource name of the project associated with the service
           
// accounts, such as `projects/my-project-123`.
           
string name = "projects/my-project";  // TODO: Update placeholder value.

           
ProjectsResource.ServiceAccountsResource.ListRequest request = iamService.Projects.ServiceAccounts.List(name);

           
Data.ListServiceAccountsResponse response;
           
do
           
{
               
// To execute asynchronously in an async method, replace `request.Execute()` as shown:
                response
= request.Execute();
               
// response = await request.ExecuteAsync();

               
if (response.Accounts == null)
               
{
                   
continue;
               
}
               
foreach (Data.ServiceAccount serviceAccount in response.Accounts)
               
{
                   
// TODO: Change code below to process each `serviceAccount` resource:
                   
Console.WriteLine(JsonConvert.SerializeObject(serviceAccount));
               
}
                request
.PageToken = response.NextPageToken;
           
} while (response.NextPageToken != null);
       
}

       
public static GoogleCredential GetCredential()
       
{
           
GoogleCredential credential = Task.Run(() => GoogleCredential.GetApplicationDefaultAsync()).Result;
           
if (credential.IsCreateScopedRequired)
           
{
                credential
= credential.CreateScoped("https://www.googleapis.com/auth/cloud-platform");
           
}
           
return credential;
       
}
   
}
}

Uses the Go client library.

package main

// BEFORE RUNNING:
// ---------------
// 1. If not already done, enable the Identity and Access Management (IAM) API
//    and check the quota for your project at
//    https://console.developers.google.com/apis/api/iam
// 2. This sample uses Application Default Credentials for authentication.
//    If not already done, install the gcloud CLI from
//    https://cloud.google.com/sdk/ and run
//    `gcloud beta auth application-default login`.
//    For more information, see
//    https://developers.google.com/identity/protocols/application-default-credentials
// 3. Install and update the Go dependencies by running `go get -u` in the
//    project directory.

import (
       
"fmt"
       
"log"

       
"golang.org/x/net/context"
       
"golang.org/x/oauth2/google"
       
"google.golang.org/api/iam/v1"
)

func main
() {
        ctx
:= context.Background()

        iamService
, err := iam.NewService(ctx)
       
if err != nil {
                log
.Fatal(err)
       
}

       
// Required. The resource name of the project associated with the service
       
// accounts, such as `projects/my-project-123`.
        name
:= "projects/my-project" // TODO: Update placeholder value.

        req
:= iamService.Projects.ServiceAccounts.List(name)
       
if err := req.Pages(ctx, func(page *iam.ListServiceAccountsResponse) error {
               
for _, serviceAccount := range page.Accounts {
                       
// TODO: Change code below to process each `serviceAccount` resource:
                        fmt
.Printf("%#v\n", serviceAccount)
               
}
               
return nil
       
}); err != nil {
                log
.Fatal(err)
       
}
}

Uses the Java client library.

/*
 * BEFORE RUNNING:
 * ---------------
 * 1. If not already done, enable the Identity and Access Management (IAM) API
 *    and check the quota for your project at
 *    https://console.developers.google.com/apis/api/iam
 * 2. This sample uses Application Default Credentials for authentication.
 *    If not already done, install the gcloud CLI from
 *    https://cloud.google.com/sdk and run
 *    `gcloud beta auth application-default login`.
 *    For more information, see
 *    https://developers.google.com/identity/protocols/application-default-credentials
 * 3. Install the Java client library on Maven or Gradle. Check installation
 *    instructions at https://github.com/google/google-api-java-client.
 *    On other build systems, you can add the jar files to your project from
 *    https://developers.google.com/resources/api-libraries/download/iam/v1/java
 */

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.model.ListServiceAccountsResponse;
import com.google.api.services.iam.v1.model.ServiceAccount;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;

public class IamExample {
 
public static void main(String args[]) throws IOException, GeneralSecurityException {
   
// Required. The resource name of the project associated with the service
   
// accounts, such as `projects/my-project-123`.
   
String name = "projects/my-project"; // TODO: Update placeholder value.

   
Iam iamService = createIamService();
   
Iam.Projects.ServiceAccounts.List request = iamService.projects().serviceAccounts().list(name);

   
ListServiceAccountsResponse response;
   
do {
      response
= request.execute();
     
if (response.getAccounts() == null) {
       
continue;
     
}
     
for (ServiceAccount serviceAccount : response.getAccounts()) {
       
// TODO: Change code below to process each `serviceAccount` resource:
       
System.out.println(serviceAccount);
     
}
      request
.setPageToken(response.getNextPageToken());
   
} while (response.getNextPageToken() != null);
 
}

 
public static Iam createIamService() throws IOException, GeneralSecurityException {
   
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
   
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

   
GoogleCredential credential = GoogleCredential.getApplicationDefault();
   
if (credential.createScopedRequired()) {
      credential
=
          credential
.createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
   
}

   
return new Iam.Builder(httpTransport, jsonFactory, credential)
       
.setApplicationName("Google-iamSample/0.1")
       
.build();
 
}
}

Uses the Node.js client library.

// BEFORE RUNNING:
// ---------------
// 1. If not already done, enable the Identity and Access Management (IAM) API
//    and check the quota for your project at
//    https://console.developers.google.com/apis/api/iam
// 2. This sample uses Application Default Credentials for authentication.
//    If not already done, install the gcloud CLI from
//    https://cloud.google.com/sdk and run
//    `gcloud beta auth application-default login`.
//    For more information, see
//    https://developers.google.com/identity/protocols/application-default-credentials
// 3. Install the Node.js client library by running
//    `npm install googleapis --save`

const {google} = require('googleapis');
const iam = google.iam('v1');

async
function main () {
 
const authClient = await authorize();
 
const request = {
   
// Required. The resource name of the project associated with the service
   
// accounts, such as `projects/my-project-123`.
    name
: 'projects/my-project',  // TODO: Update placeholder value.

    auth
: authClient,
 
};

  let response
;
 
do {
   
if (response && response.nextPageToken) {
      request
.pageToken = response.nextPageToken;
   
}
    response
= (await iam.projects.serviceAccounts.list(request)).data;
   
const accountsPage = response.accounts;
   
if (accountsPage) {
     
for (let i = 0; i < accountsPage.length; i++) {
       
// TODO: Change code below to process each resource in `accountsPage`:
        console
.log(JSON.stringify(accountsPage[i], null, 2));
     
}
   
}
 
} while (response.nextPageToken);
}
main
();

async
function authorize() {
 
const auth = new google.auth.GoogleAuth({
    scopes
: ['https://www.googleapis.com/auth/cloud-platform']
 
});
 
return await auth.getClient();
}

Uses the PHP client library.

<?php
/*
 * BEFORE RUNNING:
 * ---------------
 * 1. If not already done, enable the Identity and Access Management (IAM) API
 *    and check the quota for your project at
 *    https://console.developers.google.com/apis/api/iam
 * 2. This sample uses Application Default Credentials for authentication.
 *    If not already done, install the gcloud CLI from
 *    https://cloud.google.com/sdk and run
 *    `gcloud beta auth application-default login`.
 *    For more information, see
 *    https://developers.google.com/identity/protocols/application-default-credentials
 * 3. Install the PHP client library with Composer. Check installation
 *    instructions at https://github.com/google/google-api-php-client.
 */


// Autoload Composer.
require_once __DIR__
. '/vendor/autoload.php';

$client
= new Google_Client();
$client
->setApplicationName('Google-iamSample/0.1');
$client
->useApplicationDefaultCredentials();
$client
->addScope('https://www.googleapis.com/auth/cloud-platform');

$service
= new Google_Service_Iam($client);

// Required. The resource name of the project associated with the service
// accounts, such as `projects/my-project-123`.
$name
= 'projects/my-project';  // TODO: Update placeholder value.

$optParams
= [];

do {
  $response
= $service->projects_serviceAccounts->listProjectsServiceAccounts($name, $optParams);

 
foreach ($response['accounts'] as $serviceAccount) {
   
// TODO: Change code below to process each `serviceAccount` resource:
    echo
'<pre>', var_export($serviceAccount, true), '</pre>', "\n";
 
}

  $optParams
['pageToken'] = $response->getNextPageToken();
} while ($optParams['pageToken']);
?>

Uses the Python client library.

"""
BEFORE RUNNING:
---------------
1. If not already done, enable the Identity and Access Management (IAM) API
   and check the quota for your project at
   https://console.developers.google.com/apis/api/iam
2. This sample uses Application Default Credentials for authentication.
   If not already done, install the gcloud CLI from
   https://cloud.google.com/sdk and run
   `gcloud beta auth application-default login`.
   For more information, see
   https://developers.google.com/identity/protocols/application-default-credentials
3. Install the Python client library for Google APIs by running
   `pip install --upgrade google-api-python-client`
4. Install the OAuth 2.0 client for Google APIs by running
   `pip install --upgrade oauth2client`
"""

from pprint import pprint

from googleapiclient import discovery
from oauth2client.client import GoogleCredentials

credentials
= GoogleCredentials.get_application_default()

service
= discovery.build('iam', 'v1', credentials=credentials)

# Required. The resource name of the project associated with the service
# accounts, such as `projects/my-project-123`.
name
= 'projects/my-project'  # TODO: Update placeholder value.

request
= service.projects().serviceAccounts().list(name=name)
while True:
    response
= request.execute()

   
for service_account in response.get('accounts', []):
       
# TODO: Change code below to process each `service_account` resource:
        pprint
(service_account)

    request
= service.projects().serviceAccounts().list_next(previous_request=request, previous_response=response)
   
if request is None:
       
break

Uses the Ruby client library.

# BEFORE RUNNING:
# ---------------
# 1. If not already done, enable the Identity and Access Management (IAM) API
#    and check the quota for your project at
#    https://console.developers.google.com/apis/api/iam
# 2. This sample uses Application Default Credentials for authentication.
#    If not already done, install the gcloud CLI from
#    https://cloud.google.com/sdk and run
#    `gcloud beta auth application-default login`.
#    For more information, see
#    https://developers.google.com/identity/protocols/application-default-credentials
# 3. Install the Ruby client library and Application Default Credentials
#    library by running `gem install google-api-client` and
#    `gem install googleauth`

require 'googleauth'
require 'google/apis/iam_v1'

service
= Google::Apis::IamV1::IamService.new

service
.authorization = \
   
Google::Auth.get_application_default(['https://www.googleapis.com/auth/cloud-platform'])

# Required. The resource name of the project associated with the service
# accounts, such as `projects/my-project-123`.
name
= 'projects/my-project'  # TODO: Update placeholder value.

accounts
= service.fetch_all(items: :accounts) do |token|
  service
.list_project_service_accounts(name, page_token: token)
end

accounts
.each do |service_account|
 
# TODO: Change code below to process each `service_account` resource:
  puts service_account
.to_json
end