Created
May 29, 2020 13:01
-
-
Save bridgpal/b77b3b8f7e60aac2c84e2c88c475de7e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Sub Account Query Script | |
# By Anil Bridpgal (abridgpal@) | |
# May 2020 | |
# Instructions | |
# Update the API Key | |
# Change out the sub_account query, use https://api.newrelic.com/graphiql | |
require 'json' | |
require 'uri' | |
require 'net/http' | |
# Step 1 - Update API Key | |
$api_key = "NRAK-XXXXXXXXXXXXXXXXXXX" | |
# Step 2 - Paste in GraphQL, use "account_id" for account placeholder | |
$sub_account_query = <<NRQL.chomp | |
{ | |
actor { | |
account(id: account_id) { | |
nrql(query: "SELECT uniqueCount(appId),earliest(timestamp),latest(timestamp) from PageView since last month") { | |
results | |
} | |
} | |
} | |
} | |
NRQL | |
class NerdGraph | |
def initialize(api_key) | |
nerdgraph_url = "https://api.newrelic.com/graphql" | |
@uri = URI.parse(nerdgraph_url) | |
@request = Net::HTTP::Post.new(@uri) | |
@request.content_type = "application/json" | |
@req_options = { use_ssl: @uri.scheme == "https"} | |
@request["API-Key"] = api_key | |
@response = nil | |
end | |
def query(graphql_query) | |
@request.body = {query: graphql_query}.to_json | |
response = Net::HTTP.start(@uri.hostname, @uri.port, @req_options) do |http| | |
http.request(@request) | |
end | |
@response = JSON.parse(response.body)["data"] | |
end | |
def get_sub_accounts | |
@request.body = '{ "query": "{ actor {accounts {name id }}}" } ' | |
response = Net::HTTP.start(@uri.hostname, @uri.port, @req_options) do |http| | |
http.request(@request) | |
end | |
@response = JSON.parse(response.body)["data"]["actor"]["accounts"] | |
end | |
def pretty_print | |
puts JSON.pretty_generate(@response) | |
end | |
end | |
master_account = NerdGraph.new($api_key) | |
sub_accounts = master_account.get_sub_accounts | |
# Processing sub account queries | |
sub_accounts.each do |account| | |
# Add in the current sub account number to the query at the top of the page | |
sub_account_query = $sub_account_query.gsub("account_id", account["id"].to_s) | |
# Run a query using the Master Account API Key | |
account_query = master_account.query(sub_account_query) | |
# Adding the query result to the sub_accounts object | |
# account["uniqueCount"] = account_query["actor"]["account"]["nrql"]["results"][0]["uniqueCount.appId"] | |
account["uniqueCount"] = account_query["actor"]["account"]["nrql"]["results"][0]["uniqueCount.appId"] | |
# Printing out the current row, in csv format | |
puts "#{account["id"]}, #{account["name"]}, #{account["uniqueCount"]}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment