Advertisement
Guest User

Untitled

a guest
Dec 9th, 2016
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.58 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. import json
  4. import sys
  5. import subprocess
  6.  
  7. # To use this script: `uaac` and `cf` must be in your PATH
  8. #
  9. # Use `uaac target` and `uaac token client get` to ensure uaac can perform operations
  10. #
  11. # Use `cf login` to target the cf environment associated with that UAA to ensure cf can perform operations
  12.  
  13. def get_uid(username):
  14. """Use uaac to convert a username to a user id
  15.  
  16. Args:
  17. username (str): The username to find a user id for
  18.  
  19. Returns:
  20. str: The user id
  21.  
  22. Raises:
  23. ValueError: The user was not found or an error occured executing uaac
  24.  
  25. """
  26. try:
  27. uid = subprocess.check_output(['uaac', 'user', 'get', username, '-a', 'id']).strip()
  28. except subprocess.CalledProcessError as exc:
  29. raise ValueError(exc.output.strip())
  30.  
  31. if not uid.startswith("id: "):
  32. raise ValueError(uid)
  33.  
  34. return uid.split(': ')[1]
  35.  
  36. def jank_api(url):
  37. """Use the cf cli to make an api call for us.
  38.  
  39. Args:
  40. url(str): The user to load. Example: "/v2/info"
  41.  
  42. Returns:
  43. dict: The decoded json response
  44. """
  45. return json.loads(subprocess.check_output(['cf', 'curl', url]))
  46.  
  47. def lookup_space(sid):
  48. """Find a organization and space name by space id
  49.  
  50. Args:
  51. sid(string): The space id
  52.  
  53. Returns:
  54. tuple: (org name, space name)
  55.  
  56. Raises:
  57. ValueError: Invalid space id
  58.  
  59. """
  60.  
  61. try:
  62. space = jank_api('/v2/spaces/{0}'.format(sid))
  63. org = jank_api(space['entity']['organization_url'])
  64.  
  65. return (org['entity']['name'], space['entity']['name'])
  66. except KeyError:
  67. raise ValueError("{0} is an invalid space id: {1}".format(sid, space))
  68.  
  69. def get_orgs(uid):
  70. """Return all roles in all organizations for a given user id
  71.  
  72. Args:
  73. uid(str): The user id
  74.  
  75. Returns:
  76. List of tuples: [(org name, org role)]
  77.  
  78. """
  79. summary = jank_api('/v2/users/{0}/summary'.format(uid))
  80.  
  81. orgs = []
  82. for kind, role in {"audited_organizations": "OrgAuditor", "billing_managed_organizations": "BillingManager", "managed_organizations": "OrgManager"}.items():
  83. for org in summary['entity'][kind]:
  84. orgs.append((org['entity']['name'], role))
  85.  
  86. return orgs
  87.  
  88. def get_spaces(uid, ignore_sandboxes=False):
  89. """Return all roles in all spaces for a given user id
  90.  
  91. Args:
  92. uid(str): The user id
  93. ignore_sandboxes(bool): ignore any spaces in organzations that start with "sandbox"
  94.  
  95. Returns:
  96. List of tuples: [(org name, org role)]
  97.  
  98. """
  99.  
  100. summary = jank_api('/v2/users/{0}/summary'.format(uid))
  101.  
  102. spaces = []
  103.  
  104. for kind, role in {"spaces": "SpaceDeveloper", "audited_spaces": "SpaceAuditor", "managed_spaces": "SpaceManager"}.items():
  105. for space in summary['entity'][kind]:
  106. org_name, space_name = lookup_space((space['metadata']['guid']))
  107. spaces.append((org_name, space_name, role))
  108.  
  109. if ignore_sandboxes:
  110. return [x for x in spaces if not x[0].startswith('sandbox')]
  111.  
  112. return spaces
  113.  
  114. if __name__ == "__main__":
  115. try:
  116. username = sys.argv[1]
  117. uid = get_uid(sys.argv[1])
  118. except IndexError:
  119. raise SystemExit("USAGE: {0} <username>".format(sys.argv[0]))
  120. except ValueError as exc:
  121. raise SystemExit("## {0} - {1}".format(username, exc))
  122.  
  123. print('## {0} - {1}'.format(username, uid))
  124.  
  125. spaces = get_spaces(uid, ignore_sandboxes=False)
  126. orgs = get_orgs(uid)
  127.  
  128. for space in spaces:
  129. print ("cf unset-space-role {0} {1}".format(username, " ".join(space)))
  130.  
  131. for org in orgs:
  132. print ("cf unset-org-role {0} {1}".format(username, " ".join(org)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement