Search code examples
google-apigoogle-workspacegoogle-admin-sdk

Is there a way to get a list of projects and API calls associated with a user's Google Workspace account?


I'm performing a large clean up of Google Workspace accounts and I'd like to programmatically determine whether any of the accounts have projects associated with them, and if so, when the last API calls associated with that project were made. Is there any way to do this programmatically via the Google Admin (or some other) APIs? Thank you


Solution

  • Yes... probably ;-)

    This is a naive solution and I will be interested to see better ways to do this.

    Please run this on a subset of your Projects and Users to ensure it addresses your need

    For you to consider:

    • You write "Projects" but identities can be bound to many Google Cloud resources (Organizations, Folders, Buckets etc.) too
    • How many Projects and Users are there?
    • serviceAccount: should be excluded but what about other identities?
    • We'll filter by log entries for user: (?) currently in a Project Policy.
    Org Admin

    You'll need to use an Org Admin identity.

    List all Projects
    PROJECTS=$(\
      gcloud projects list --format="value(projectId)")
    for PROJECT in ${PROJECTS}
    do
      echo "Project: ${PROJECT}"
      ...
    done
    
    Get each Project's Policy's user:

    Filter the policy by members of the form user:{email}

    Extract the value {email} from user:{email}

    USERS=$(\
      gcloud projects get-iam-policy ${PROJECT} \
      --flatten="bindings[].members[]" \
      --filter="bindings.members:user" \
      --format="value(bindings.members.split(\":\").slice(1:))")
    echo "Users: ${USERS}"
    
    Filter Audit Logs actually Admin Activity Logs

    Grep the activity logs for the last 30 days for the most recent (!) log entry for this user.

    for USER in ${USERS}
    do
      echo "User: ${USER}"
      FILTER="
        logName=\"projects/${PROJECT}/logs/cloudaudit.googleapis.com%2Factivity\"
        protoPayload.authenticationInfo.principalEmail=\"${USER}\"
      "
      LOG=$(gcloud logging read "${FILTER}" \
      --project=${PROJECT} \
      --freshness="30d" \
      --order=desc \
      --limit=1)
      printf "Log:\n%s" "${LOG}"
    done