Skip to content

Instantly share code, notes, and snippets.

@miotke
Last active March 20, 2024 23:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miotke/a6dd7e11fdb1849297aae3cf9244780b to your computer and use it in GitHub Desktop.
Save miotke/a6dd7e11fdb1849297aae3cf9244780b to your computer and use it in GitHub Desktop.
"""
Gets all users assigned to a specified app then adds them to the specified group.
"""
import os
import time
import requests
OKTA_API_KEY = os.environ["okta_api"]
OKTA_ADMIN_BASE_URL = os.environ["okta_url"]
payload={}
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': f'SSWS {OKTA_API_KEY}',
}
params = {
"limit": 200
}
def main():
""" Get all users who are assinged to the specified app (APP_ID) by ID """
user_ids = []
emails = []
# Add the app ID in quotes
APP_ID = ""
url = f"{OKTA_ADMIN_BASE_URL}/api/v1/apps/{APP_ID}/users"
print(f"Getting users from app ID: {APP_ID}")
while url:
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
for user in data:
status = user.get("status")
# Check that the user is ACTIVE
# NOTE: This is more useful when checking group members
if status == "ACTIVE":
# Get the user's ID
user_id = user.get("id")
user_ids.append(user_id)
# Okta API pagination
if "next" in response.links.keys():
url = response.links["next"]["url"]
else:
url = None
else:
print(f"Failed to fetch members. Status code: {response.status_code}")
break
add_users_to_group(user_ids)
def add_users_to_group(user_ids: list):
""" Add the user to the group based the user ID """
count = 0
# TODO: Add the group ID in quotes
GROUP_ID = ""
if user_ids != []:
for user_id in user_ids:
# To avoid Okta API rate limites we increment count to 100
count += 1
url = f"{OKTA_ADMIN_BASE_URL}/api/v1/groups/{GROUP_ID}/users/{user_id}"
# Add the user to the group based on the GROUP_ID and user_id
response = requests.request("PUT", url, headers=headers, data=payload)
response.raise_for_status()
print(f"Successfully added {user_id} to group ID {GROUP_ID}")
# If count reaches 100 pause for 30 seconds to let the Okta API rate limit cool off.
if count == 100:
print(f"Count is at {count}...waiting for 30 seconds before continuing...")
time.sleep(30)
count = 0
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment