Walter_C
Databricks Employee
Databricks Employee

Please try the following:

def import_service_principal(sp, target_host, target_token):
headers = get_headers(target_token)
url = f'{target_host}/api/2.0/preview/scim/v2/ServicePrincipals'
sp_check_url = f'{url}/{sp["applicationId"]}'

# Check if service principal already exists by application ID
if resource_exists(sp_check_url, headers):
logging.warning(f"Service Principal with ID {sp['applicationId']} already exists in target system. Skipping import.")
return False

data = {
"schemas": sp.get("schemas", []),
"applicationId": sp["applicationId"],
"displayName": sp.get("displayName", ""),
"description": sp.get("description", ""),
"entitlements": sp.get("entitlements", [])
}

try:
make_request_with_error_handling(url, headers, method='POST', data=data)
logging.info(f"Service Principal {sp['applicationId']} imported successfully.")
return True
except KeyError as ke:
logging.error(f"KeyError importing service principal: {sp}. Missing key: {ke}")
except requests.exceptions.HTTPError as err:
if err.response.status_code == 409:
logging.warning(f"Service Principal with ID {sp['applicationId']} already exists in target system. Skipping import.")
else:
logging.error(f"HTTP error occurred importing service principal: {sp}. Error: {err}")
except Exception as e:
logging.error(f"Error importing service principal: {sp}. Error: {e}")

return False