I wrote a python script that returns me the Usage Details for all my subscriptions and saves them in a dataframe. It later sums up the properties.cost and returns the total of the ongoing month. My goal ist to know how much i already spent this month. But with every new request i make, the total of my costs goes up or down.
Output example:
{'request1': {'costTotal': 96.99047619273139,
'time': '17-03-2020T13:39:19:000Z'},
'request2': {'costTotal': 105.28680062444838,
'time': '17-03-2020T13:41:19:000Z'},
'request3': {'costTotal': 103.50071786335579,
'time': '17-03-2020T13:43:19:000Z'},
'request4': {'costTotal': 103.04300834107798,
'time': '17-03-2020T13:45:19:000Z'}}
The API im using:
https://management.azure.com/{scope}/providers/Microsoft.Consumption/usageDetails?api-version=2019-10-01
Part of my download.py script which concats the dataframes and saves it as pkl:
ENV = sys.argv[1]
ORG_FILES = None
RESULTING_FILES = ["billing_file.pkl"]
def main():
execution = {"file": RESULTING_FILES, "orgfile": ORG_FILES}
def generate_billinginfo(subscription, cred):
scope = "subscriptions/" + subscription
url = (
"https://management.azure.com/"
+ scope
+ "/providers/Microsoft.Consumption/usageDetails?api-version=2019-10-01"
)
headers = {
"Authorization": "Bearer " + cred.token["access_token"],
"Content-Type": "application/json",
}
connection_attempts = 0
while True:
httpresponse = requests.get(url=url, headers=headers, verify=False)
connection_attempts = connection_attempts + 1
if httpresponse.status_code != 200:
logger.error(
"Problem accessing server status code: %s",
httpresponse.status_code,
)
if connection_attempts >= 3:
raise ValueError(
"Can not access server. Status code: %s",
httpresponse.status_code,
)
else:
time.sleep(3 * connection_attempts)
else:
break
# Extracting tags & properties
Tags = []
Properties = []
for resource in httpresponse.json()["value"]:
Tags.append(resource["tags"])
Properties.append(resource["properties"])
dfgeneral = pd.DataFrame(httpresponse.json()["value"])
dfprop = pd.DataFrame(Properties)
# Rejoining dataframes
billingdf = dfprop.join(dfgeneral[["tags"]])
return billingdf
cred = ServicePrincipalCredentials(
client_id=config["client_id"],
secret=config["password"],
tenant=config["tenant_id"],
)
subscriptions = [
"0f5dd24a-f6e0-473f-8643-75dc3481bdc1",
....
]
for subscription in subscriptions:
try:
billinginfo
billinginfoexists = True
except:
billinginfoexists = False
if billinginfoexists:
billinginfo = pd.concat(
[billinginfo, generate_billinginfo(subscription, cred)]
)
else:
billinginfo = generate_billinginfo(subscription, cred)
billinginfo.to_pickle(RESULTING_FILES[0])
# Resulting file
with open(Path("./execution.json"), "w") as outfile:
json.dump(execution, outfile, indent=4)
Any ideas what the problem could be?