Skip to content

Instantly share code, notes, and snippets.

@jmcarp
Last active February 3, 2017 02:35
Show Gist options
  • Save jmcarp/c402227e91b6ae69955d5190e5576b58 to your computer and use it in GitHub Desktop.
Save jmcarp/c402227e91b6ae69955d5190e5576b58 to your computer and use it in GitHub Desktop.
notify-sandbox-users.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import requests
from requests_oauthlib import OAuth2Session
def get_info(api_url):
resp = requests.get('{}/v2/info'.format(api_url))
resp.raise_for_status()
return resp.json()
def get_session(api_url, client_id, client_secret):
info = get_info(api_url)
resp = requests.post(
'{}/oauth/token'.format(info['token_endpoint']),
auth=(client_id, client_secret),
data={'grant_type': 'client_credentials', 'response_type': 'token'},
)
resp.raise_for_status()
return OAuth2Session(client_id, token=resp.json())
def paginate(session, api_url, next_url):
resources = []
while next_url:
resp = session.get('{}/{}'.format(api_url, next_url))
resp.raise_for_status()
resources.extend(resp.json()['resources'])
next_url = resp.json()['next_url']
return resources
def get_org_services(session, api_url, org_guid):
next_url = '/v2/service_instances?q=organization_guid:{}'.format(org_guid)
return paginate(session, api_url, next_url)
def get_org_spaces(session, api_url, org_guid):
next_url = '/v2/organizations/{}/spaces'.format(org_guid)
return paginate(session, api_url, next_url)
def send_mail(service, space):
print(service, space)
def main():
api_url = os.environ['API_URL']
org_guid = os.environ['ORG_GUID']
service_guids = os.environ['SERVICE_GUIDS'].split()
session = get_session(api_url, os.environ['CLIENT_ID'], os.environ['CLIENT_SECRET'])
services = [
service for service in get_org_services(session, api_url, org_guid)
if service['entity']['service_guid'] in service_guids
]
spaces = {
space['metadata']['guid']: space
for space in get_org_spaces(session, api_url, org_guid)
}
for service in services:
space_guid = service['entity']['space_guid']
send_mail(service, spaces[space_guid])
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment