Spaces and Orgs a user is associated to in CloudFoundry

Share on:
  1. You have admin rights of CloudFoundry.
  2. You have cf cli installed.
  3. You are using v3 of CloudFoundry API.
 1#!/bin/bash
 2
 3set -eu -o pipefail
 4userObject="$(cf curl '/v3/users?usernames=<SomeUserName>')"
 5orgName=""
 6spaceName=""
 7userFound="$(echo "$userObject" | jq .pagination.total_results)"
 8#This script assumes there should be only 1 user with the given username
 9if [ "$userFound" == "1" ]; then
10  userID="$(echo "$userObject" | jq -r .resources[0].guid)"
11#This script assumes that the user has got maximum of 1000 roles, otherwise increase the value from 1000 in below line
12  rolesObject="$(cf curl "/v3/roles?user_guids=$userID&per_page=1000")"
13  for key in $(jq '.resources | keys | .[]' <<< "$rolesObject"); do
14    value=$(jq -r ".resources[$key]" <<< "$rolesObject");
15    roleType="$(jq -r '.type' <<< "$value")"
16    if [[ "$roleType" == *"org"* ]]; then
17          orgURL="/v3/organizations/$(jq -r '.relationships.organization.data.guid' <<< "$value")"
18          orgName="$(cf curl "$orgURL" | jq -r .name)"
19    fi
20    if [[ "$roleType" == *"space"* ]]; then
21          spaceURL="/v3/spaces/$(jq -r '.relationships.space.data.guid' <<< "$value")"
22          spaceName="$(cf curl "$spaceURL" | jq -r .name)"
23          orgURL="/v3/organizations/$(cf curl "$spaceURL" | jq -r '.relationships.organization.data.guid')"
24          orgName="$(cf curl "$orgURL" | jq -r .name)"
25    fi
26#This part prints the output, adjust it to your requirements
27    echo "Role: $roleType"
28    echo "OrgName: $orgName"
29    echo "SpaceName: $spaceName"
30  done
31fi
...
shell

To use the above script login to your CloudFoundry api using cf cli and admin credentials. Than in the above script replace <SomeUserName> with the username for which you need the details, and then run the script.

That is it, you get the required data.