Skip to content

Instantly share code, notes, and snippets.

@gspncr
Created May 26, 2021 13:49
Show Gist options
  • Save gspncr/14418b95816871cfe3f246eca9fe53fa to your computer and use it in GitHub Desktop.
Save gspncr/14418b95816871cfe3f246eca9fe53fa to your computer and use it in GitHub Desktop.
Check NR with a query, if conditions are met, run a Jenkins or other API call
import requests, json
graphQLEndpoint = 'https://api.newrelic.com/graphql'
APIKey = '<Your-NRAK-Key>'
# check New Relic for the stock status
def checkNewRelic():
# set headers for the request
headers = {
"Content-Type": 'application/json',
"API-Key": APIKey
}
# set the query from https://api.newrelic.com/graphiql
query = """
{
actor {
account(id: <YOUR-ID>) {
nrql(query: "SELECT min(`custom.CL`) as 'allFlavours' FROM SyntheticCheck WHERE monitorName = 'CL Stock' since 30 minutes ago ") {
results
}
}
}
}
"""
# make the request to NerdGraph
request = requests.post(
graphQLEndpoint,
json={'query': query},
headers=headers
)
# export the values from NerdGraph so that we can work with them
jsonpayload = json.loads(request.text)
global allFlavours, allMachines
entries = len(jsonpayload["data"]["actor"]["account"]["nrql"]["results"])
for x in range(entries):
allFlavours = jsonpayload["data"]["actor"]["account"]["nrql"]["results"][x]["allFlavours"]
print("all flavours: ", allFlavours)
def evaluateResults():
# check against results
allFlavoursThreshold = 20
# compare the products against the thresholds. If does not meet the threshold, run jenkins job for that product. Priority order, first match will finish the statement.
if not (allFlavours >= allFlavoursThreshold): runJenkins('allFlavours')
elif not (allMachines >= allMachinesThreshold): runJenkins('allMachines')
def runJenkins(product):
# send request to run jenkins job -> https://stackoverflow.com/questions/36548690/start-jenkins-build-using-batch-script
url = "http://google.com/" + product + "?TOKEN=your_api_token"
# match the product with the correct jenkins call
if (product == 'allFlavours'):
response = requests.request("POST", url)
print("Running Jenkins for all products. Function was sent: " + product + ". Got status code: ", response.status_code)
elif (product == 'allMachines'):
response = requests.request("POST", url)
print("Running Jenkins for allMachines. Function was sent: " + product + ". Got status code: ", response.status_code)
else:
print("Unknown product. Nothing to do. Received: " + product)
return 0
checkNewRelic()
evaluateResults()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment