Skip to content

Instantly share code, notes, and snippets.

@willianantunes
Created October 27, 2021 20:52
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 willianantunes/fedc383bc38189de9ecfb88c8b8b5683 to your computer and use it in GitHub Desktop.
Save willianantunes/fedc383bc38189de9ecfb88c8b8b5683 to your computer and use it in GitHub Desktop.
Azure DevOps: Collect metrics given a project from an organization
import base64
import json
import sys
import urllib.parse
from urllib.request import Request
from urllib.request import urlopen
print("Collecting parameters...")
organization_name, project_id, user_with_token = sys.argv[1], sys.argv[2], sys.argv[3]
assert organization_name and project_id and user_with_token
print("Configuring dependencies")
base_url = f"https://dev.azure.com/{organization_name}"
# https://docs.microsoft.com/en-us/rest/api/azure/devops/build/metrics/get-project-metrics?view=azure-devops-rest-6.1
endpoint = f"{base_url}/{project_id}/_apis/build/metrics/daily"
params = {
"minMetricsTime": "2021-09-27",
"api-version": "6.1-preview.1",
}
query_string = urllib.parse.urlencode(params)
final_endpoint = f"{endpoint}?{query_string}"
print(f"Built endpoint: {final_endpoint}")
def execute_get_request(api_url, user_with_token):
encoded_user_with_token = base64.standard_b64encode(user_with_token.encode("utf-8"))
headers = {
"Content-Type": "application/json",
"Authorization": f"Basic {encoded_user_with_token.decode('utf-8')}",
}
body = None
print("Creating request object...")
request = Request(api_url, body, headers, method="GET")
print("Sending to Azure Devops...")
request_answer = urlopen(request)
assert request_answer.status == 200
body_as_byte = request_answer.read()
body_as_str = body_as_byte.decode("utf-8")
return json.loads(body_as_str)
def do_the_thing(api_url, credentials):
metrics_details = execute_get_request(api_url, credentials)
aggregated_data = {}
for entry in metrics_details["value"]:
metric_name = entry["name"]
metric_value = entry["intValue"]
if aggregated_data.get(metric_name):
aggregated_data[metric_name] += metric_value
else:
aggregated_data[metric_name] = metric_value
print(aggregated_data)
do_the_thing(final_endpoint, user_with_token)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment