-1

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?

Atef Hares
  • 4,715
  • 3
  • 29
  • 61
usertj
  • 21
  • 4
  • Plz edit your question and include the code (remove sensitive data). Also show how do you authenticate the python client lib and list the permissions given to the `identity` that is authenticated. – Atef Hares Feb 27 '22 at 07:50
  • I have included the code.. – usertj Feb 27 '22 at 21:12

2 Answers2

0

the error means that you have insufficient permissions on the user project or it is deleted or not found.

A User Project is for quota and billing purposes. The caller must have the IAM permission serviceusage.services.use permission on the project. The user/quota project is set with this command:

gcloud auth application-default set-quota-project
John Hanley
  • 74,467
  • 6
  • 95
  • 159
0

You should always use project_id in your requests unless otherwise specified in documentation.

Notice the change in your code:

for project in response.get('projects', []):
    projectid = project['projectId']
    projectname = project['name']

    headers = {
    'Authorization': 'Bearer ' + token,
    'x-goog-user-project': projectid # >>> HERE <<<, use projectid instead of projectname and make sure you have the required permission/s
    }
    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)
Atef Hares
  • 4,715
  • 3
  • 29
  • 61
  • @usertj You are welcome. if this or any answer has solved your question please consider [accepting it](https://meta.stackexchange.com/q/5234/179419) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. – Atef Hares Mar 01 '22 at 18:30