Skip to content

Instantly share code, notes, and snippets.

@jbaker10
Created January 9, 2019 19:02
Show Gist options
  • Save jbaker10/6622b81eb25f707ad90cd1ed6d14cc35 to your computer and use it in GitHub Desktop.
Save jbaker10/6622b81eb25f707ad90cd1ed6d14cc35 to your computer and use it in GitHub Desktop.
import json
import time
from httplib2 import Http
from apiclient import discovery, errors
from datadog import initialize, api
from datetime import datetime
from oauth2client.service_account import ServiceAccountCredentials
## Global vars
users_updated = 0
suspended_in_gsuite = []
admin_in_gsuite = []
not_found_in_gsuite = []
update_errors = []
## Create the Gsuite service to upload the users
scopes = [
'https://www.googleapis.com/auth/admin.directory.user'
]
with open('workday-gsuite-pipeline-0501a0645479.json', 'r') as cred_file:
gsuite_cred = json.loads(cred_file.read())
credentials = ServiceAccountCredentials.from_json_keyfile_dict(
keyfile_dict=gsuite_cred,
scopes=scopes
)
credentials = credentials.create_delegated("[email protected]")
service = discovery.build('admin', 'directory_v1', http=credentials.authorize(Http()))
## Read in the users dictionary to be used with the updates
with open('all_users.json', 'r') as users_file:
users = users_file.read()
users = json.loads(users)
for user in users:
print("Updating user: {}".format(user.get("primaryEmail", "")))
try:
# projection="full" is required to return the customSchemas attribute
service.users().update(userKey=user.get("primaryEmail"), body=user).execute()
users_updated += 1
except errors.HttpError as e:
# Retry if 5XX http code
if e.resp.status >= 500:
retry_fix = 1000 # in milliseconds
time.sleep(retry_fix / 1000)
try:
service.users().update(userKey=user.get("primaryEmail"), body=user).execute()
users_updated += 1
except errors.HttpError as e:
print(e)
if e.resp.status == 400:
suspended_in_gsuite.append(user.get("primaryEmail"))
elif e.resp.status == 403:
admin_in_gsuite.append(user.get("primaryEmail"))
elif e.resp.status == 404:
not_found_in_gsuite.append(user.get("primaryEmail"))
elif e.resp.status >= 300:
update_errors.append('{}'.format(e))
print("\nResults:\n")
print("Number of profiles updated: \n\t{}".format(users_updated))
print("The following accounts are suspended in Gsuite: \n\t{}".format("\n\t".join(suspended_in_gsuite)))
print("The following accounts are admins in Gsuite: \n\t{}".format("\n\t".join(admin_in_gsuite)))
print("The following accounts were not found in Gsuite: \n\t{}".format("\n\t".join(not_found_in_gsuite)))
print("The following update errors occurred: \n\t{}".format("\n\t".join(update_errors)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment