cloud-foundrypivotal-web-services

PCF: How to find the list of all the spaces where you have Developer privileges


If you are not an admin in Pivotal Cloud Foundry, how will you find or list all the orgs/spaces where you have developer privileges? Is there a command or menu to get that, instead of going into each space and verifying it?


Solution

  • Here's a script that will dump the org & space names of which the currently logged in user is a part.

    A quick explanation. It will call the /v2/spaces api, which already filters to only show spaces of which the currently logged in user can see (if you run with a user that has admin access, it will list all orgs and spaces). We then iterate over the results & take the space's organization_url field and cf curl that to get the organization name (there's a hashmap to cache results).

    This script requires Bash 4+ for the hashmap support. If you don't have that, you can remove that part and it will just be a little slower. It also requires jq, and of course the cf cli.

    #!/usr/bin/env bash
    #
    # List all spaces available to the current user
    #
    set -e
    
    function load_all_pages {
        URL="$1"
        DATA=""
        until [ "$URL" == "null" ]; do
            RESP=$(cf curl "$URL")
            DATA+=$(echo "$RESP" | jq .resources)
            URL=$(echo "$RESP" | jq -r .next_url)
        done
        # dump the data
        echo "$DATA" | jq .[] | jq -s
    }
    
    function load_all_spaces {
        load_all_pages "/v2/spaces"
    }
    
    function main {
        declare -A ORGS  # cache org name lookups
    
        # load all the spaces & properly paginate
        SPACES=$(load_all_spaces)
    
        # filter out the name & org_url
        SPACES_DATA=$(echo "$SPACES" | jq -rc '.[].entity | {"name": .name, "org_url": .organization_url}')
    
        printf "Org\tSpace\n"
        for SPACE_JSON in $SPACES_DATA; do
            SPACE_NAME=$(echo "$SPACE_JSON" | jq -r '.name')
            # take the org_url and look up the org name, cache responses for speed
            ORG_URL=$(echo "$SPACE_JSON" | jq -r '.org_url')
            ORG_NAME="${ORGS[$ORG_URL]}"
            if [ "$ORG_NAME" == "" ]; then
                ORG_NAME=$(cf curl "$ORG_URL" | jq -r '.entity.name')
                ORGS[$ORG_URL]="$ORG_NAME"
            fi
            printf "$ORG_NAME\t$SPACE_NAME\n"
        done
    }
    
    main "$@"