Tomas Jansson
Tomas Jansson

Reputation: 23472

Is there a way to list google project names through the .NET google cloud sdk?

I want to do some housekeeping in all our google projects, and to do so I need to be able to list all the available projects. I can't find that anywhere in the API, am I missing something? I thought it might be in the IAM sdk, but didn't find it there. Any ideas of where it could be, or do I need to implement something myself on top of the API?

Upvotes: 1

Views: 1106

Answers (3)

Jeffrey Rennie
Jeffrey Rennie

Reputation: 3443

The C# code looks like this. It assumes you have set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the service account key json file you downloaded.

using Google.Apis.Auth.OAuth2;
using Google.Apis.CloudResourceManager.v1;
using Google.Apis.Services;
using System;

namespace ListProjects
{
    class Program
    {
        static void Main(string[] args)
        {

             GoogleCredential credential =
                GoogleCredential.GetApplicationDefault();
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[]
                {
                    CloudResourceManagerService.Scope.CloudPlatformReadOnly
                });
            }
            var crmService = new CloudResourceManagerService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
            });
            var request = new ProjectsResource.ListRequest(crmService);
            while (true)
            {
                var result = request.Execute();
                foreach (var project in result.Projects)
                {
                    Console.WriteLine(project.ProjectId);
                }
                if (string.IsNullOrEmpty(result.NextPageToken))
                {
                    break;
                }
                request.PageToken = result.NextPageToken;
            }
        }
    }
}

Upvotes: 2

John Hanley
John Hanley

Reputation: 81416

I liked Tomas Jansson Question / Answer on using Google Cloud Resource Manager to list projects.

Permissions and what you can access:

You can only list projects for which you have permissions to access. This means that you cannot see all projects unless you have the rights to access it. In my examples below I show which scopes are required. This also means that you can list projects across accounts. This allows you to see which projects you have access to using the credentials specified in the examples. I show how to use Application Default Credentials (ADC) and Service Account Credentials (Json file format).

This answer includes two examples in Python that use two different Google Cloud Python libraries. These examples produce the same output as the Google CLI gcloud projects list command.

Example 1 using the Python Client Library (services discovery method):

from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
from google.oauth2 import service_account

# Example using the Python Client Library

# Documentation
# https://github.com/googleapis/google-api-python-client
# https://developers.google.com/resources/api-libraries/documentation/cloudresourcemanager/v2/python/latest/

# Library Installation
# pip install -U google-api-python-client
# pip install -U oauth2client

# Requires one of the following scopes
# https://www.googleapis.com/auth/cloud-platform
# https://www.googleapis.com/auth/cloud-platform.read-only
# https://www.googleapis.com/auth/cloudplatformprojects
# https://www.googleapis.com/auth/cloudplatformprojects.readonly

print('{:<20} {:<22} {:<21}'.format('PROJECT_ID', 'NAME', 'PROJECT_NUMBER'))

# Uncomment to use Application Default Credentials (ADC)
credentials = GoogleCredentials.get_application_default()

# Uncomment to use Service Account Credentials in Json format
# credentials = service_account.Credentials.from_service_account_file('service-account.json')

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

request = service.projects().list()

while request is not None:
        response = request.execute()

        for project in response.get('projects', []):
                print('{:<20} {:<22} {:<21}'.format(project['projectId'], project['name'], project['projectNumber']))

        request = service.projects().list_next(previous_request=request, previous_response=response)

Example 2 using the Python Google Cloud Resource Manager API Client Library:

from google.cloud import resource_manager

# Example using the Python Google Cloud Resource Manager API Client Library

# Documentation
# https://pypi.org/project/google-cloud-resource-manager/
# https://github.com/googleapis/google-cloud-python
# https://googleapis.github.io/google-cloud-python/latest/resource-manager/index.html
# https://googleapis.github.io/google-cloud-python/latest/resource-manager/client.html
# https://googleapis.github.io/google-cloud-python/latest/resource-manager/project.html

# Library Installation
# pip install -U google-cloud-resource-manager

# Requires one of the following scopes
# https://www.googleapis.com/auth/cloud-platform
# https://www.googleapis.com/auth/cloud-platform.read-only
# https://www.googleapis.com/auth/cloudplatformprojects
# https://www.googleapis.com/auth/cloudplatformprojects.readonly

print('{:<20} {:<22} {:<21}'.format('PROJECT_ID', 'NAME', 'PROJECT_NUMBER'))

# Uncomment to use Application Default Credentials (ADC)
client = resource_manager.Client()

# Uncomment to use Service Account Credentials in Json format
# client = resource_manager.Client.from_service_account_json('service-account.json')

for project in client.list_projects():
        print('{:<20} {:<22} {:<21}'.format(project.project_id, project.name, project.number))

Upvotes: 0

Tomas Jansson
Tomas Jansson

Reputation: 23472

To be able to do this you have to use the raw API clients. The API to use is this one Google.Apis.CloudResourceManager.v1.CloudResourceManagerService.

The code should look something like this (F#) given that you want to use the application default credentials

let getCredentials() = GoogleCredential.GetApplicationDefaultAsync() |> Async.AwaitTask
async {
    let! credentials = getCredentials()
    initializer.HttpClientInitializer <- credentials
    let crmService = new Google.Apis.CloudResourceManager.v1.CloudResourceManagerService(initializer)
    let projectsResource = crmService.Projects
    let projects = projectsResource.List().Execute().Projects
    .
    .
    .
}
``´

Upvotes: 2

Related Questions