1

I am a python noob looking for best practice advice and a resolution to this problem. I am able to successfully pull the data I require from the Okta API which results in the output "PRECONDITION FAILED. Errors reported by remote server: Failed to update. Resource changed on the server." thats only half of what I want. I would like to be able to check for that output every 60 minutes and if it doesnt exist do nothing. I thought thats what I was doing in code below in the "start" function but it doesnt seem to behave the way I want it to. How do I store json objects in the variable events or exit the app if the object doesnt appear? Thank you in advance!

import requests
import os
import json
import time
from datetime import datetime, timedelta

key = os.environ['OKTA_AUTH']
outcome = 'outcome.result eq "FAILURE"'
event_type = 'eventType eq "application.provision.user.deactivate"'
app_id = 'target.id eq "*******"'
all_params = f'{event_type} and {app_id} and {outcome}'
api_url = f'https://domain.okta.com/api/v1/logs'

last_hour_date_time = datetime.utcnow() - timedelta(minutes=60)
since = str(last_hour_date_time.strftime('%Y-%m-%dT%H:%M:%S.000Z'))

def auth_okta():
    url = api_url.format()
    print(url)
    params = {
        'filter': all_params,
        'since': since
    }
    response = requests.get(url, params=params,
                        headers={'Accept': 'application/json', 
                        'authorization': key})
    response_json = response.json()
    return response_json

def start():
    for event_data in auth_okta():
        events = event_data['outcome']['reason']
        if not events:
            print('nothing there')
        else:
            print(events)

start()

Matthew Morcaldi
  • 466
  • 1
  • 5
  • 20

3 Answers3

1

You can use sys.exit() to end all execution.

if events == None:
    sys.exit(0)
Greg
  • 1,845
  • 2
  • 16
  • 26
0

Try using the .get command on your event_data:

for event_data in auth_okta():
    events = None
    while events is None:
        events = event_data.get("outcome", None).get("reason", None)
        print("Nothing found... waiting")
        time.sleep(3600) #wait one hour
    print(events)
Python on Toast
  • 254
  • 1
  • 5
0

seems that my initial structure of the code was creating far too many lists and I ended up restructuring the whole script. I also took some advice from greg.

import requests
import sys
import os
import json
import time
from datetime import datetime, timedelta

key = os.environ['OKTA_AUTH']
outcome = 'outcome.result eq "FAILURE"'
event_type = 'eventType eq "application.provision.user.deactivate"'
target_type = 'target.type eq "User"'
app_id = 'target.id eq "APP-ID-HERE"'
all_params = f'{event_type} and {target_type} and {app_id} and {outcome}'
api_url = f'https://DOMAIN.okta.com/api/v1/logs'
slack_url = "SLACK WEBHOOK URL"
last_hour_date_time = datetime.utcnow() - timedelta(days=1)
since = str(last_hour_date_time.strftime('%Y-%m-%dT%H:%M:%S.000Z'))
unique_set=[]


class Events:
    def okta_auth(self):
        event_list=[]
        url = api_url.format()
        params = {
            'filter': all_params,
            'since': since
        }
        response = requests.get(url, params=params,
                            headers={'Accept': 'application/json', 
                            'authorization': key})
        response_json = response.json()
        for event_data in response_json:
            events = event_data['outcome']['reason']
            targets = event_data['target']
            parse = list(map(lambda x: x['alternateId'], targets))
            target_list=[]
            event_list.append(events)
            target_list.append(parse[1])
            for item in target_list:
                if item not in unique_set:
                    unique_set.append(item)
        if event_list != []:
            self.post_slack()
        else:
            sys.exit(0)

    def post_slack(self):
        url = slack_url.format()
        payload =  "{\"text\": \" Twilio Flex provisioing failure. Please check the following users: \n %s \"}" % '\n'.join(unique_set)        
        requests.post(url, headers={'Accept': 'application/json'}, data=payload)

if __name__ == "__main__":
    Events().okta_auth()

Matthew Morcaldi
  • 466
  • 1
  • 5
  • 20