from decouple import config import yaml import requests import json import pandas as pd import sys #proxies=dict(http='socks5://localhost:3020', https='socks5://localhost:3020') def get_request(url, headers): try: response = requests.get(url, headers=headers) response.raise_for_status() except requests.exceptions.HTTPError as errh: return "An Http Error occurred:" + repr(errh) except requests.exceptions.ConnectionError as errc: return "An Error Connecting to the API occurred:" + repr(errc) except requests.exceptions.Timeout as errt: return "A Timeout Error occurred:" + repr(errt) except requests.exceptions.RequestException as err: return "An Unknown Error occurred" + repr(err) return response def post_request(url, headers,body): try: response = requests.post(url, body, headers=headers,verify=False) response.raise_for_status() except requests.exceptions.HTTPError as errh: return "An Http Error occurred:" + repr(errh) except requests.exceptions.ConnectionError as errc: return "An Error Connecting to the API occurred:" + repr(errc) except requests.exceptions.Timeout as errt: return "A Timeout Error occurred:" + repr(errt) except requests.exceptions.RequestException as err: return "An Unknown Error occurred" + repr(err) return response def put_request(url, headers,body): try: response = requests.put(url, body, headers=headers,verify=False) response.raise_for_status() except requests.exceptions.HTTPError as errh: return "An Http Error occurred:" + repr(errh) except requests.exceptions.ConnectionError as errc: return "An Error Connecting to the API occurred:" + repr(errc) except requests.exceptions.Timeout as errt: return "A Timeout Error occurred:" + repr(errt) except requests.exceptions.RequestException as err: return "An Unknown Error occurred" + repr(err) return response def CreateToken(DTAPIToken, DTENV,nwzone, dtEnvInfo, tokenname,scope): env = DTENV DTAPIToken = DTAPIToken DTAPIURL = env + "/api/v2/apiTokens" headers = { 'Content-Type': 'application/json', 'Authorization': 'Api-Token ' + DTAPIToken } DynatraceInstaller = [ "InstallerDownload", "SupportAlert" ] DevOps_Read = [ "DataExport", # Access problem and event feed, metrics, and topology. "DTAQLAccess", # User sessions. "ReadSyntheticData", # Read synthetic monitors, locations, and nodes. "metrics.read", # Read metrics. "entities.read", # Read entities. "problems.read", # Read problems. "syntheticLocations.read", # Read synthetic locations. "slo.read", # Read SLO. "releases.read", # Read releases. "activeGates.read" ] ReadAll = [ "DataExport", # Access problem and event feed, metrics, and topology. "ReadConfig", # Read configuration. "DTAQLAccess", # User sessions. "ReadSyntheticData", # Read synthetic monitors, locations, and nodes. "auditLogs.read", # Read audit logs. "metrics.read", # Read metrics. "entities.read", # Read entities. "problems.read", # Read problems. "networkZones.read", # Read network zones. "activeGates.read", # Read ActiveGates. "credentialVault.read", # Read credential vault entries. "extensions.read", # Read extensions. "extensionConfigurations.read", # Read extension monitoring configurations. "extensionEnvironment.read", # Read extension environment configurations. "securityProblems.read", # Read security problems. "syntheticLocations.read", # Read synthetic locations. "slo.read", # Read SLO. "releases.read", # Read releases. "apiTokens.read" # Read API tokens. ] temp=[] if "DynatraceInstaller" in scope: temp.extend(DynatraceInstaller) if "DevOps_Read" in scope: temp.extend(DevOps_Read) if "ReadAll" in scope: temp.extend(ReadAll) if not temp: print("scope not supported") sys.exit() data = '{"name":"' + tokenname + '","scopes":["' + "\",\"".join(temp) + '"]}' #[""] InstallerDownload","" #data = '{"name":"' + tokenname + '","scopes":' + str(temp) + '}' #[""] r = post_request(DTAPIURL,headers,data) print(r) row = {'Environment':dtEnvInfo,'DT_API_URL':env +"/api", 'DT_[API|PAAS]_TOKEN':r.json()['token'],'DT_NETWORK_ZONE':nwzone} return row ################# ##main ################# print(sys.argv) if len(sys.argv) != 6: print("createToken.py \n") print("TYPE: API, PAAS, APIPAAS") print("SCOPE: DynatraceInstaller, DevOps_Read, ReadAll") print("further details: https://atc.bmwgroup.net/confluence/display/OPMAAS/Token+Management") sys.exit() with open('./environment.yaml') as file: doc = yaml.safe_load(file) df = pd.DataFrame() #tokenname="runtime_AKS" type=sys.argv[1] scope=sys.argv[2] ticketnr=sys.argv[3] email=sys.argv[4].replace("_","-") purpose=sys.argv[5] tokenname=type+"_"+ticketnr+"_"+email+"_"+purpose for item, doc in doc.items(): token = dict(doc[2]) url = dict(doc[1]) nwzone = dict(doc[3]) dtEnvInfo = dict(doc[4]) print("Crawling through: " + item) print("Check if token exists in environment...") if(config(token.get('env-token-name')) != ""): print("Gather data, hold on a minute") DTTOKEN = config(token.get('env-token-name')) DTURL = url.get('env-url') row = CreateToken(DTTOKEN,DTURL,nwzone.get('network-zone'),dtEnvInfo.get('env-info'),tokenname,scope) df = df.append(row,ignore_index=True) else: print("token not found, skipping " + item) print(df) df.to_excel(tokenname+".xlsx")