I am trying to list unused service accounts in a gcp project
Working fine when using gcloud command
gcloud recommender insights list \
--insight-type=google.iam.serviceAccount.Insight \
--location=global \
--filter=insightSubtype=SERVICE_ACCOUNT_USAGE --project
Getting an error when i am trying to list the unused service accounts using python sdk. Below is the error
import requests
import json
import re
import sys
import subprocess
import os
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_file("")
service = discovery.build('cloudresourcemanager', 'v1', credentials=credentials)
request = service.projects().list()
token1 = subprocess.Popen("gcloud auth print-access-token", stdout=subprocess.PIPE, shell = True)
token, error = token1.communicate()
token = str(token.decode("utf-8"))
token = token.rstrip("\n")
token = token.rstrip("\r")
while request is not None:
response = request.execute()
print(response)
for project in response.get('projects', []):
projectid = project['projectId']
projectname = project['name']
headers = {
'Authorization': 'Bearer ' + token,
'x-goog-user-project': projectname
}
post_url= "https://recommender.googleapis.com/v1/projects/" + projectid + "/locations/"+ "global" +"/insightTypes/google.iam.serviceAccount.Insight/insights?filter=insightSubtype=SERVICE_ACCOUNT_USAGE"
post_url_data = requests.get(post_url, headers = headers)
get_api_json = json.loads(post_url_data.text)
print(get_api_json)
I am iterating through all projects, for some projects i am getting below error, I have checked in the console, the projects exist..
Error: project not found or deleted, status; INVALID_ARGUMENT, details: [{'@type': 'type.googleapis.com/google.rpc/ErrorInfo', 'reason':'USER_PROJECT_DENIED'
Any idea what's missing here?