Skip to content

Instantly share code, notes, and snippets.

@cnelson
Last active December 10, 2016 00:47
Show Gist options
  • Save cnelson/3ad50b1f609535d1d5ab1fb22b0d916c to your computer and use it in GitHub Desktop.
Save cnelson/3ad50b1f609535d1d5ab1fb22b0d916c to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import json
import sys
import subprocess
# To use this script: `uaac` and `cf` must be in your PATH
#
# Use `uaac target` and `uaac token client get` to ensure uaac can perform operations
#
# Use `cf login` to target the cf environment associated with that UAA to ensure cf can perform operations
def get_uid(username):
"""Use uaac to convert a username to a user id
Args:
username (str): The username to find a user id for
Returns:
str: The user id
Raises:
ValueError: The user was not found or an error occured executing uaac
"""
try:
uid = subprocess.check_output(['uaac', 'user', 'get', username, '-a', 'id']).strip()
except subprocess.CalledProcessError as exc:
raise ValueError(exc.output.strip())
if not uid.startswith("id: "):
raise ValueError(uid)
return uid.split(': ')[1]
def jank_api(url):
"""Use the cf cli to make an api call for us.
Args:
url(str): The user to load. Example: "/v2/info"
Returns:
dict: The decoded json response
"""
return json.loads(subprocess.check_output(['cf', 'curl', url]))
def lookup_space(sid):
"""Find a organization and space name by space id
Args:
sid(string): The space id
Returns:
tuple: (org name, space name)
Raises:
ValueError: Invalid space id
"""
try:
space = jank_api('/v2/spaces/{0}'.format(sid))
org = jank_api(space['entity']['organization_url'])
return (org['entity']['name'], space['entity']['name'])
except KeyError:
raise ValueError("{0} is an invalid space id: {1}".format(sid, space))
def get_orgs(uid):
"""Return all roles in all organizations for a given user id
Args:
uid(str): The user id
Returns:
List of tuples: [(org name, org role)]
"""
summary = jank_api('/v2/users/{0}/summary'.format(uid))
orgs = []
for kind, role in {"audited_organizations": "OrgAuditor", "billing_managed_organizations": "BillingManager", "managed_organizations": "OrgManager"}.items():
for org in summary['entity'][kind]:
orgs.append((org['entity']['name'], role))
return orgs
def get_spaces(uid, ignore_sandboxes=False):
"""Return all roles in all spaces for a given user id
Args:
uid(str): The user id
ignore_sandboxes(bool): ignore any spaces in organzations that start with "sandbox"
Returns:
List of tuples: [(org name, space name, space role)]
"""
summary = jank_api('/v2/users/{0}/summary'.format(uid))
spaces = []
for kind, role in {"spaces": "SpaceDeveloper", "audited_spaces": "SpaceAuditor", "managed_spaces": "SpaceManager"}.items():
for space in summary['entity'][kind]:
org_name, space_name = lookup_space((space['metadata']['guid']))
spaces.append((org_name, space_name, role))
if ignore_sandboxes:
return [x for x in spaces if not x[0].startswith('sandbox')]
return spaces
if __name__ == "__main__":
try:
username = sys.argv[1]
uid = get_uid(username)
except IndexError:
raise SystemExit("USAGE: {0} <username>".format(sys.argv[0]))
except ValueError as exc:
raise SystemExit("## {0} - {1}".format(username, exc))
print('## {0} - {1}'.format(username, uid))
spaces = get_spaces(uid, ignore_sandboxes=False)
orgs = get_orgs(uid)
for space in spaces:
print ("cf unset-space-role {0} {1}".format(username, " ".join(space)))
for org in orgs:
print ("cf unset-org-role {0} {1}".format(username, " ".join(org)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment