red888
red888

Reputation: 31510

how do I get the project of a service account?

I'm using the python google.cloud api

For example using the metrics module

from google.cloud import monitoring

client = monitoring.Client()
client.query(my/gcp/metric, minutes=10)

For my GOOGLE_APPLICATION_CREDENTIALS im using a service account that has specific access to a gcp project.

Does google.cloud have any modules that can let me derive the project from the service account (like get what project the service account is in)?

This would be convenient because each service account only has access to a single project, so I could set my service account and be able to reference that project in code.

Upvotes: 0

Views: 1900

Answers (3)

Luiz Ferraz
Luiz Ferraz

Reputation: 1525

The method google.auth.default return a tuple (project_id, credentials) if that information is available on the environment.

Also, the client object knows to which project it is linked from (either client.project or client.project_id, I'm not sure which one for the Monitoring API).

If you set the service account manually with the GOOGLE_APPLICATION_CREDENTIALS env var, you can open the file and load its json. One of the parameters in a service account key file is the project id.

Upvotes: 1

Amruth Bahadursha
Amruth Bahadursha

Reputation: 74

Google Cloud Identity and Access Management (IAM) API has ‘serviceAccounts.get’ method and which shows the projects associated with a service account as shown here. You need to have proper permissions on the projects for the API to work.

Upvotes: 0

Oliver
Oliver

Reputation: 29453

Not sure if this will work, you may need to tweak it:

from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
credentials = GoogleCredentials.get_application_default() 
service = discovery.build('yourservicename', credentials=credentials) 
request = service.projects().list()[0]

Upvotes: 1

Related Questions